Esempio n. 1
1
extern "C" SAMETIME_API int Load(PLUGINLINK *link)
{

	pluginLink=link;

	if(!IsUnicodeOS()) {
		MessageBox(0, TranslateT("This plugin requires a Unicode capable Windows installation."), TranslateT("Sametime Error"), MB_OK | MB_ICONERROR);
		return 1;
	}

	if ( !ServiceExists( MS_DB_CONTACT_GETSETTING_STR )) {
		MessageBox( 0, TranslateT( "This plugin requires db3x plugin version 0.5.1.0 or later." ), TranslateT("Sametime Error"), MB_OK );
		return 1;
	}

	DuplicateHandle( GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &mainThread, THREAD_SET_CONTEXT, FALSE, 0 );
	mainThreadId = GetCurrentThreadId();

	previous_status = current_status = ID_STATUS_OFFLINE;

	if(ServiceExists(MS_LANGPACK_GETCODEPAGE))
		code_page = CallService(MS_LANGPACK_GETCODEPAGE, 0, 0);

	mir_getMMI(&mmi);
	mir_getUTFI(&utfi);


	if(ServiceExists(MS_DB_SETSETTINGRESIDENT)) { // 0.6+
		char buff[256];
		mir_snprintf(buff, 256, "%s/%s", PROTO, "Status");
		CallService(MS_DB_SETSETTINGRESIDENT, TRUE, (LPARAM)buff);
		mir_snprintf(buff, 256, "%s/%s", PROTO, "IdleTS");
		CallService(MS_DB_SETSETTINGRESIDENT, TRUE, (LPARAM)buff);
	}

	InitAwayMsg();
	InitCritSection();

	// Get module name from DLL file name
	{
		char* str1;
		char str2[MAX_PATH];

		GetModuleFileNameA(hInst, str2, MAX_PATH);
		str1 = strrchr(str2, '\\');
		if (str1 != NULL && strlen(str1+1) > 4) {
			strncpy(PROTO, str1+1, strlen(str1+1)-4);
			PROTO[strlen(str1+1)-3] = 0;
		}
		CharUpperA(PROTO);

		strcpy(PROTO_GROUPS, PROTO);
		strcat(PROTO_GROUPS, "_GROUPS");
	}

	PROTOCOLDESCRIPTOR pd = {0};
	pd.cbSize = sizeof(pd);
	pd.szName = PROTO;
	pd.type = PROTOTYPE_PROTOCOL;
	CallService(MS_PROTO_REGISTERMODULE,0,(LPARAM)&pd);

	InitUtils();

	CreatePluginServices();

	LoadOptions();

	//DeleteAllContacts();	//!!!
	
	SetAllOffline();

	HookEvent(ME_SYSTEM_MODULESLOADED, OnModulesLoaded);	
	HookEvent(ME_OPT_INITIALISE, OptInit );
	HookEvent(ME_SYSTEM_PRESHUTDOWN, OnPreShutdown);
	HookEvent(ME_SYSTEM_SHUTDOWN, OnShutdown);

	return 0;
}
Esempio n. 2
0
//-----  InitInstance()  ------------------------------------------------------
BOOL CNifUtilsSuiteApp::InitInstance()
{
	//  init common controls (since Win95)
	INITCOMMONCONTROLSEX	InitCtrls;

	InitCtrls.dwSize = sizeof(InitCtrls);
	InitCtrls.dwICC  = ICC_WIN95_CLASSES;
	InitCommonControlsEx(&InitCtrls);

	//  init own instance
	CWinAppEx::InitInstance();

	//  no interaction with Win7 taskbar
	EnableTaskbarInteraction(FALSE);

	//  init RichEdit
	AfxInitRichEdit2();

	//  initialize configuration
	CStringA	configName;
	bool		hasConfig(false);

	GetModuleFileNameA(NULL, configName.GetBuffer(MAX_PATH), MAX_PATH);
	configName.ReleaseBuffer();
	configName.Replace(".exe", ".xml");
	hasConfig = Configuration::initInstance((const char*) configName);

	//  initialize Havok  (HK_MEMORY_USAGE bytes of physics solver buffer)
	hkMemoryRouter*		pMemoryRouter(hkMemoryInitUtil::initDefault(hkMallocAllocator::m_defaultMallocAllocator, hkMemorySystem::FrameInfo(HK_MEMORY_USAGE)));
	hkBaseSystem::init(pMemoryRouter, errorReport);

	//  initialize material map
	Configuration*	pConfig(Configuration::getInstance());

	NifUtlMaterialList::initInstance(pConfig->_pathNifXML, pConfig->_matScanTag, pConfig->_matScanName);


	// Register the application's document templates.
	CSingleDocTemplate*	pDocTemplate(new CSingleDocTemplate(IDR_MAINFRAME,
															RUNTIME_CLASS(CNifUtilsSuiteDoc),
															RUNTIME_CLASS(CNifUtilsSuiteFrame),
															RUNTIME_CLASS(CFormNifConvertView))
															);
	if (!pDocTemplate)		return FALSE;
	AddDocTemplate(pDocTemplate);

	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo	cmdInfo;

	ParseCommandLine(cmdInfo);
	if (!ProcessShellCommand(cmdInfo))		return FALSE;

	// call DragAcceptFiles only if there's a suffix
	//  In an SDI app, this should occur after ProcessShellCommand

	// The one and only window has been initialized, so show and update it
	m_pMainWnd->ShowWindow(SW_SHOW);
	m_pMainWnd->UpdateWindow();

	if (!hasConfig)
	{
		AfxMessageBox(L"Seems you're running NifUtilsSuite for the first time.\nYou're redirected to Settings now.");
		m_pMainWnd->PostMessage(WM_COMMAND, ID_OPTIONS_EDIT);
	}

	return TRUE;
}
Esempio n. 3
0
static void test_ExitCode(void)
{
    static const char* AeDebug="Software\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug";
    char test_exe[MAX_PATH];
    DWORD ret;
    HKEY hkey;
    DWORD disposition;
    LPBYTE auto_val=NULL;
    DWORD auto_size, auto_type;
    LPBYTE debugger_val=NULL;
    DWORD debugger_size, debugger_type;

    GetModuleFileNameA(GetModuleHandle(NULL), test_exe, sizeof(test_exe));
    if (GetFileAttributes(test_exe) == INVALID_FILE_ATTRIBUTES)
        strcat(test_exe, ".so");
    if (GetFileAttributesA(test_exe) == INVALID_FILE_ATTRIBUTES)
    {
        ok(0, "could not find the test executable '%s'\n", test_exe);
        return;
    }

    ret=RegCreateKeyExA(HKEY_LOCAL_MACHINE, AeDebug, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hkey, &disposition);
    if (ret == ERROR_SUCCESS)
    {
        auto_size=0;
        ret=RegQueryValueExA(hkey, "auto", NULL, &auto_type, NULL, &auto_size);
        if (ret == ERROR_SUCCESS)
        {
            auto_val=HeapAlloc(GetProcessHeap(), 0, auto_size);
            RegQueryValueExA(hkey, "auto", NULL, &auto_type, auto_val, &auto_size);
        }

        debugger_size=0;
        ret=RegQueryValueExA(hkey, "debugger", NULL, &debugger_type, NULL, &debugger_size);
        if (ret == ERROR_SUCCESS)
        {
            debugger_val=HeapAlloc(GetProcessHeap(), 0, debugger_size);
            RegQueryValueExA(hkey, "debugger", NULL, &debugger_type, debugger_val, &debugger_size);
        }
    }
    else if (ret == ERROR_ACCESS_DENIED)
    {
        skip("not enough privileges to change the debugger\n");
        return;
    }
    else if (ret != ERROR_FILE_NOT_FOUND)
    {
        ok(0, "could not open the AeDebug key: %d\n", ret);
        return;
    }

    if (debugger_val && debugger_type == REG_SZ &&
        strstr((char*)debugger_val, "winedbg --auto"))
        crash_and_winedbg(hkey, test_exe);

    crash_and_debug(hkey, test_exe, "dbg,none");
    crash_and_debug(hkey, test_exe, "dbg,event,order");
    crash_and_debug(hkey, test_exe, "dbg,attach,event,code2");
    if (pDebugSetProcessKillOnExit)
        crash_and_debug(hkey, test_exe, "dbg,attach,event,nokill");
    if (pDebugActiveProcessStop)
        crash_and_debug(hkey, test_exe, "dbg,attach,event,detach");

    if (disposition == REG_CREATED_NEW_KEY)
    {
        RegCloseKey(hkey);
        RegDeleteKeyA(HKEY_LOCAL_MACHINE, AeDebug);
    }
    else
    {
        if (auto_val)
        {
            RegSetValueExA(hkey, "auto", 0, auto_type, auto_val, auto_size);
            HeapFree(GetProcessHeap(), 0, auto_val);
        }
        else
            RegDeleteValueA(hkey, "auto");
        if (debugger_val)
        {
            RegSetValueExA(hkey, "debugger", 0, debugger_type, debugger_val, debugger_size);
            HeapFree(GetProcessHeap(), 0, debugger_val);
        }
        else
            RegDeleteValueA(hkey, "debugger");
        RegCloseKey(hkey);
    }
}
Esempio n. 4
0
static FARPROC WINAPI
MyGetProcAddress(HMODULE hModule, LPCSTR lpProcName) {

    if (VERBOSITY >= 3) {
        /* XXX this can cause segmentation faults */
        logGetProcAddress(hModule, lpProcName);
    }

    if (!NOOP) {
        char szModule[MAX_PATH];
        DWORD dwRet = GetModuleFileNameA(hModule, szModule, sizeof szModule);
        assert(dwRet);
        const char *szBaseName = getBaseName(szModule);

        ModulesMap::const_iterator modIt;
        modIt = modulesMap.find(szBaseName);
        if (modIt != modulesMap.end()) {
            if (VERBOSITY > 1 && VERBOSITY < 3) {
                logGetProcAddress(hModule, lpProcName);
            }

            const Module & module = modIt->second;
            const FunctionMap & functionMap = module.functionMap;
            FunctionMap::const_iterator fnIt;

            if (HIWORD(lpProcName) == 0) {
                FARPROC proc = GetProcAddress(hModule, lpProcName);
                if (!proc) {
                    return proc;
                }

                for (fnIt = functionMap.begin(); fnIt != functionMap.end(); ++fnIt) {
                    FARPROC pRealProc = GetProcAddress(hModule, fnIt->first);
                    if (proc == pRealProc) {
                        if (VERBOSITY > 0) {
                            debugPrintf("inject: replacing %s!%s\n", szBaseName, lpProcName);
                        }
                        return (FARPROC)fnIt->second;
                    }

                }
                
                debugPrintf("inject: ignoring %s!@%u\n", szBaseName, LOWORD(lpProcName));

                return proc;
            }

            fnIt = functionMap.find(lpProcName);

            if (fnIt != functionMap.end()) {
                LPVOID pProcAddress = fnIt->second;
                if (VERBOSITY > 0) {
                    debugPrintf("inject: replacing %s!%s\n", szBaseName, lpProcName);
                }
                if (!module.bInternal && pSharedMem) {
                    pSharedMem->bReplaced = TRUE;
                }
                return (FARPROC)pProcAddress;
            } else {
                if (VERBOSITY > 0 && !module.bInternal) {
                    debugPrintf("inject: ignoring %s!%s\n", szBaseName, lpProcName);
                }
            }
        }
    }

    return GetProcAddress(hModule, lpProcName);
}
Esempio n. 5
0
void
ruby_init_loadpath_safe(int safe_level, const char* szRoot)
{
    VALUE load_path;
#if defined LOAD_RELATIVE
    char libpath[MAXPATHLEN + 1];
    char *p;
    int rest;
	if ( szRoot )
		strncpy(libpath, szRoot, sizeof(libpath) - 1);
	else
	{
#if defined _WIN32 || defined __CYGWIN__
    GetModuleFileNameA(libruby, libpath, sizeof libpath);
#elif defined(__EMX__)
    _execname(libpath, sizeof(libpath) - 1);
#endif
	}
//RHO
    libpath[sizeof(libpath) - 1] = '\0';
#if defined DOSISH
    translate_char(libpath, '\\', '/');
#elif defined __CYGWIN__
    {
	char rubylib[FILENAME_MAX];
	cygwin_conv_to_posix_path(libpath, rubylib);
	strncpy(libpath, rubylib, sizeof(libpath));
    }
#endif
    p = strrchr(libpath, '/');
    if (p) {
	*p = 0;
	if (p - libpath > 3 && !STRCASECMP(p - 4, "/bin")) {
	    p -= 4;
	    *p = 0;
	}
    }
    else {
	strcpy(libpath, ".");
	p = libpath + 1;
    }

    rest = sizeof(libpath) - 1 - (p - libpath);

#define RUBY_RELATIVE(path) (strncpy(p, (path), rest), libpath)
#else
#define RUBY_RELATIVE(path) (path)
#endif
#define incpush(path) rb_ary_push(load_path, rubylib_mangled_path2(path))
    load_path = GET_VM()->load_path;
//RHO
    incpush(RUBY_RELATIVE(RUBY_LIB));
    incpush(RUBY_RELATIVE(RUBY_SITE_LIB));
    incpush(RUBY_RELATIVE(RUBY_SITE_LIB2));
/*
    if (safe_level == 0) {
	ruby_push_include(getenv("RUBYLIB"), identical_path);
    }

#ifdef RUBY_SEARCH_PATH
    incpush(RUBY_RELATIVE(RUBY_SEARCH_PATH));
#endif

    incpush(RUBY_RELATIVE(RUBY_SITE_LIB2));
#ifdef RUBY_SITE_THIN_ARCHLIB
    incpush(RUBY_RELATIVE(RUBY_SITE_THIN_ARCHLIB));
#endif
    incpush(RUBY_RELATIVE(RUBY_SITE_ARCHLIB));
    incpush(RUBY_RELATIVE(RUBY_SITE_LIB));

    incpush(RUBY_RELATIVE(RUBY_VENDOR_LIB2));
#ifdef RUBY_VENDOR_THIN_ARCHLIB
    incpush(RUBY_RELATIVE(RUBY_VENDOR_THIN_ARCHLIB));
#endif
    incpush(RUBY_RELATIVE(RUBY_VENDOR_ARCHLIB));
    incpush(RUBY_RELATIVE(RUBY_VENDOR_LIB));

    incpush(RUBY_RELATIVE(RUBY_LIB));
#ifdef RUBY_THIN_ARCHLIB
    incpush(RUBY_RELATIVE(RUBY_THIN_ARCHLIB));
#endif
    incpush(RUBY_RELATIVE(RUBY_ARCHLIB));

    if (safe_level == 0) {
	incpush(".");
    }
*/
//RHO
}
Esempio n. 6
0
int main(int argc, char* argv[])
{
    DWORD dwProcessId = GetCurrentProcessId();
    char szProcessName[256] = {0};
    char szModuleName[MAX_PATH] = {0};

    for (int i = 1; i < argc; i++) {
        if (_stricmp(argv[i], "-pid") == 0 && i < (argc - 1)) {
            dwProcessId = atoi(argv[i + 1]);
        }

        if (_stricmp(argv[i], "-name") == 0 && i < (argc - 1)) {
            strcpy_s(szProcessName, argv[i + 1]);
        }

        if (_stricmp(argv[i], "-dll") == 0 && i < (argc - 1)) {
            strcpy_s(szModuleName, argv[i + 1]);
        }
    }

    if (strlen(szModuleName) == 0) {
        printf("Module name is required...\n");
        return 0;
    }

    if (strlen(szProcessName) == 0 && dwProcessId == GetCurrentProcessId()) {
        printf("Invalid parameters!\n");
        return 0;
    }

    if (strlen(szProcessName) > 0) {
        if (dwProcessId == GetCurrentProcessId()) { // Only change the processid if it's not already set
            dwProcessId = GetProcessIdFromProcessName(szProcessName);

            if (dwProcessId == GetCurrentProcessId()) {
                printf("Failed to obtain process \"%s\"...\n", szProcessName);
                return 0;
            }
        }
    }

    HMODULE hKernel = LoadLibraryA("kernel32.dll");
    DWORD64 dwLoadLibraryA = (DWORD64) GetProcAddress(hKernel, "LoadLibraryA") - (DWORD64) hKernel;
    printf("kernel32.dll: %016llX\n", hKernel);
    printf("LoadLibraryA: %016llX\n", dwLoadLibraryA);
    printf("Module Name: %s\n", szModuleName);
    char szCurrentModulePath[MAX_PATH] = {0};
    GetModuleFileNameA(GetModuleHandle(NULL), szCurrentModulePath, MAX_PATH);

    for (size_t i = strlen(szCurrentModulePath); i > 0; i--) {
        if (szCurrentModulePath[ i ] == '\\') {
            szCurrentModulePath[ i + 1 ] = 0;
            break;
        }
    }

    strcat_s(szCurrentModulePath, szModuleName);
    printf("Full Path: %s\n", szCurrentModulePath);
    DWORD dwFileAttributes = GetFileAttributesA(szCurrentModulePath);

    if (dwFileAttributes == INVALID_FILE_ATTRIBUTES && GetLastError() == ERROR_FILE_NOT_FOUND) {
        printf("File not found...\n");
        return 0;
    }

    printf("Injecting: %s\n", szCurrentModulePath);
    HMODULE hRemoteKernel = GetRemoteModuleHandleA(dwProcessId, "kernel32.dll");

    if (hRemoteKernel == NULL) {
        printf("Failed to locate kernel32 in remote process...\n");
        return 0;
    }

    printf("kernel32 (remote): 0x%016llX\n", hRemoteKernel);
    HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);

    if (hProcess == INVALID_HANDLE_VALUE) {
        printf("Failed to locate remote process...\n");
        return 0;
    }

    LPVOID lpModuleName = VirtualAllocEx(hProcess, NULL, strlen(szCurrentModulePath) + 1, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    if (lpModuleName == NULL) {
        printf("Failed to allocate module name in remote process...\n");
        return 0;
    }

    if (WriteProcessMemory(hProcess, lpModuleName, szCurrentModulePath, strlen(szCurrentModulePath), NULL) == FALSE) {
        printf("Failed to write module name in remote process...\n");
        return 0;
    }

    DWORD64 dwRemoteLoadLibraryAddress = ((DWORD64)hRemoteKernel + dwLoadLibraryA);
    printf("LoadLibraryA (remote): %016llX\n", dwRemoteLoadLibraryAddress);
    HANDLE hThread = CreateRemoteThread(hProcess, 0, 0, (LPTHREAD_START_ROUTINE) dwRemoteLoadLibraryAddress, lpModuleName, 0, 0);
    printf("Injecting... ");
    WaitForSingleObject(hThread, INFINITE);
    printf("Injected!\n");
    return 0;
}
Esempio n. 7
0
STDAPI
AMovieDllRegisterServer2( BOOL bRegister )
{
  HRESULT hr = NOERROR;

  DbgLog((LOG_TRACE, 2, TEXT("AMovieDllRegisterServer2()")));

  // get file name (where g_hInst is the
  // instance handle of the filter dll)
  //
  WCHAR achFileName[MAX_PATH];

  // WIN95 doesn't support GetModuleFileNameW
  //
  {
    char achTemp[MAX_PATH];

    DbgLog((LOG_TRACE, 2, TEXT("- get module file name")));

    // g_hInst handle is set in our dll entry point. Make sure
    // DllEntryPoint in dllentry.cpp is called
    ASSERT(g_hInst != 0);

    if( 0 == GetModuleFileNameA( g_hInst
                              , achTemp
                              , sizeof(achTemp) ) )
    {
      // we've failed!
      DWORD dwerr = GetLastError();
      return AmHresultFromWin32(dwerr);
    }

    MultiByteToWideChar( CP_ACP
                       , 0L
                       , achTemp
                       , lstrlenA(achTemp) + 1
                       , achFileName
                       , NUMELMS(achFileName) );
  }

  //
  // first registering, register all OLE servers
  //
  if( bRegister )
  {
    DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers")));
    hr = RegisterAllServers( achFileName, TRUE );
  }

  //
  // next, register/unregister all filters
  //

  if( SUCCEEDED(hr) )
  {
    // init is ref counted so call just in case
    // we're being called cold.
    //
    DbgLog((LOG_TRACE, 2, TEXT("- CoInitialize")));
    hr = CoInitialize( (LPVOID)NULL );
    ASSERT( SUCCEEDED(hr) );

    // get hold of IFilterMapper2
    //
    DbgLog((LOG_TRACE, 2, TEXT("- obtain IFilterMapper2")));
    IFilterMapper2 *pIFM2 = 0;
    IFilterMapper *pIFM = 0;
    hr = CoCreateInstance( CLSID_FilterMapper2
                         , NULL
                         , CLSCTX_INPROC_SERVER
                         , IID_IFilterMapper2
                         , (void **)&pIFM2       );
    if(FAILED(hr))
    {
        DbgLog((LOG_TRACE, 2, TEXT("- trying IFilterMapper instead")));

        hr = CoCreateInstance(
            CLSID_FilterMapper,
            NULL,
            CLSCTX_INPROC_SERVER,
            IID_IFilterMapper,
            (void **)&pIFM);
    }
    if( SUCCEEDED(hr) )
    {
      // scan through array of CFactoryTemplates
      // registering servers and filters.
      //
      DbgLog((LOG_TRACE, 2, TEXT("- register Filters")));
      for( int i = 0; i < g_cTemplates; i++ )
      {
        // get i'th template
        //
        const CFactoryTemplate *pT = &g_Templates[i];

        if( NULL != pT->m_pAMovieSetup_Filter )
        {
          DbgLog((LOG_TRACE, 2, TEXT("- - register %ls"), (LPCWSTR)pT->m_Name ));

          if(pIFM2)
          {
              hr = AMovieSetupRegisterFilter2( pT->m_pAMovieSetup_Filter, pIFM2, bRegister );
          }
          else
          {
              hr = AMovieSetupRegisterFilter( pT->m_pAMovieSetup_Filter, pIFM, bRegister );
          }
        }

        // check final error for this pass
        // and break loop if we failed
        //
        if( FAILED(hr) )
          break;
      }

      // release interface
      //
      if(pIFM2)
          pIFM2->Release();
      else
          pIFM->Release();

    }

    // and clear up
    //
    CoFreeUnusedLibraries();
    CoUninitialize();
  }

  //
  // if unregistering, unregister all OLE servers
  //
  if( SUCCEEDED(hr) && !bRegister )
  {
    DbgLog((LOG_TRACE, 2, TEXT("- register OLE Servers")));
    hr = RegisterAllServers( achFileName, FALSE );
  }

  DbgLog((LOG_TRACE, 2, TEXT("- return %0x"), hr));
  return hr;
}
Esempio n. 8
0
/**
 * Builds a list of predefined paths for the User folder
 * according to the running system.
 * @return List of data paths.
 */
std::vector<std::string> findUserFolders()
{
	std::vector<std::string> list;
	
#ifdef __MORPHOS__
	list.push_back("PROGDIR:");
	return list;
#endif

	
#ifdef _WIN32
	char path[MAX_PATH];

	// Get Documents folder
	if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path)))
	{
		PathAppendA(path, "OpenXcom\\");
		list.push_back(path);
	}

	// Get binary directory
	if (GetModuleFileNameA(NULL, path, MAX_PATH) != 0)
	{
		PathRemoveFileSpecA(path);
		PathAppendA(path, "user\\");
		list.push_back(path);
	}

	// Get working directory
	if (GetCurrentDirectoryA(MAX_PATH, path) != 0)
	{
		PathAppendA(path, "user\\");
		list.push_back(path);
	}
#else
#ifdef __HAIKU__
	list.push_back("/boot/apps/OpenXcom/");
#endif
	char const *home = getHome();
	char path[MAXPATHLEN];
	
	// Get user folders
	if (char const *const xdg_data_home = getenv("XDG_DATA_HOME"))
 	{
		snprintf(path, MAXPATHLEN, "%s/openxcom/", xdg_data_home);
 	}
 	else
 	{
#ifdef __APPLE__
		snprintf(path, MAXPATHLEN, "%s/Library/Application Support/OpenXcom/", home);
#else
		snprintf(path, MAXPATHLEN, "%s/.local/share/openxcom/", home);
#endif
 	}
	list.push_back(path);

	// Get old-style folder
	snprintf(path, MAXPATHLEN, "%s/.openxcom/", home);
	list.push_back(path);

	// Get working directory
	list.push_back("./user/");
#endif

	return list;
}
Esempio n. 9
0
void CodeInjectionPlayer::InjectCode()
{
	if (!opts.enable_code_injection)
		return;
	else if (next_request_time > GetTickCount())
		return;

	// Window is opened?
	HWND hwnd = FindWindow();
	if (hwnd == nullptr)
		return;

	// Msg Window is registered? (aka plugin is running?)
	HWND msgHwnd = ::FindWindow(message_window_class, nullptr);
	if (msgHwnd != nullptr)
		return;


	next_request_time = GetTickCount() + 30000;


	// Get the dll path
	char dll_path[1024] = { 0 };
	if (!GetModuleFileNameA(g_plugin.getInst(), dll_path, _countof(dll_path)))
		return;

	char *p = strrchr(dll_path, '\\');
	if (p == nullptr)
		return;

	p++;
	*p = '\0';

	size_t len = p - dll_path;

	mir_snprintf(p, 1024 - len, "listeningto\\%s.dll", dll_name);

	len = strlen(dll_path);

	// File exists?
	DWORD attribs = GetFileAttributesA(dll_path);
	if (attribs == 0xFFFFFFFF || !(attribs & FILE_ATTRIBUTE_ARCHIVE))
		return;

	// Do the code injection
	unsigned long pid;
	GetWindowThreadProcessId(hwnd, &pid);
	HANDLE hProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION
		| PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, pid);
	if (hProcess == nullptr)
		return;

	char *_dll = (char *)VirtualAllocEx(hProcess, nullptr, len + 1, MEM_COMMIT, PAGE_READWRITE);
	if (_dll == nullptr) {
		CloseHandle(hProcess);
		return;
	}
	WriteProcessMemory(hProcess, _dll, dll_path, len + 1, nullptr);

	HMODULE hKernel32 = GetModuleHandleA("kernel32");
	HANDLE hLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA");
	DWORD threadId;
	HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)hLoadLibraryA, _dll, 0, &threadId);
	if (hThread == nullptr) {
		VirtualFreeEx(hProcess, _dll, len + 1, MEM_RELEASE);
		CloseHandle(hProcess);
		return;
	}
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hThread);
	VirtualFreeEx(hProcess, _dll, len + 1, MEM_RELEASE);
	CloseHandle(hProcess);
}
Esempio n. 10
0
BOOL dump(DWORD dwOEP, struct dll *NewDLL, DWORD dwStartIAT)
{
    DWORD dwBase;
    DWORD dwLen;
    BYTE modulePath[MAX_PATH + 8];
    PBYTE pDump;
    PIMAGE_DOS_HEADER pDosHeader;
    PIMAGE_NT_HEADERS pPE;
    PIMAGE_SECTION_HEADER pSection;
    PIMAGE_SECTION_HEADER pSectionHeaders;
    DWORD curseur, i;
    HANDLE hFile;
    DWORD NbByteWritten;
    PBYTE IAT = NULL;
    DWORD dwAllocSize = 0;
    DWORD dwRVAIAT = 0;

    dwBase = (DWORD)GetModuleHandle(NULL);
    if (((dwLen = GetModuleFileNameA((HMODULE) dwBase, modulePath, MAX_PATH + 1)) >= MAX_PATH) || (!dwLen))
        return FALSE;
    if (!(pDump = AllocAndCopy(dwBase, &dwAllocSize)))
        return FALSE;
    pDosHeader = (PIMAGE_DOS_HEADER)pDump;
    pPE = (PIMAGE_NT_HEADERS)(pDump + pDosHeader->e_lfanew);
    pSection = (PIMAGE_SECTION_HEADER)((PCHAR)pPE + sizeof(IMAGE_FILE_HEADER) + pPE->FileHeader.SizeOfOptionalHeader + sizeof(DWORD));

    pPE->OptionalHeader.FileAlignment = 0x200;
    for (curseur = AlignSize(pPE->OptionalHeader.SizeOfHeaders, pPE->OptionalHeader.FileAlignment) - 1; ! pDump[curseur]; curseur --);

    pSectionHeaders = (PIMAGE_SECTION_HEADER)((PBYTE)pPE + sizeof(IMAGE_FILE_HEADER) + pPE->FileHeader.SizeOfOptionalHeader + sizeof(DWORD));
    dwRVAIAT = AlignSize(pSectionHeaders[pPE->FileHeader.NumberOfSections - 1].VirtualAddress + pSectionHeaders[pPE->FileHeader.NumberOfSections - 1].Misc.VirtualSize,
                         pPE->OptionalHeader.SectionAlignment);
    IAT = Reconstruct(dwStartIAT, NewDLL, dwRVAIAT);
    memcpy(pDump, dwBase, dwAllocSize);
    curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment);
    pPE->OptionalHeader.SizeOfHeaders = curseur;
    for (i = 0; i < pPE->FileHeader.NumberOfSections; i++)
    {
        memcpy(pDump + curseur, pDump + pSection[i].VirtualAddress, pSection[i].Misc.VirtualSize);
        pSection[i].PointerToRawData = curseur;
        curseur += pSection[i].Misc.VirtualSize - 1;
        //AlignCurseur(pDump, &curseur);
        while ((pDump[curseur] == 0) && (((int)curseur) >= -1))
           curseur--;
        curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment);
        pSection[i].SizeOfRawData = curseur - pSection[i].PointerToRawData;
    }

    strcpy(pSection[pPE->FileHeader.NumberOfSections].Name, ".suce");
    pSection[pPE->FileHeader.NumberOfSections].PointerToRawData = curseur;
    pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize = AlignSize(computeSizeIAT(NewDLL),
                                                                            pPE->OptionalHeader.SectionAlignment);
    pSection[pPE->FileHeader.NumberOfSections].VirtualAddress = dwRVAIAT;
    pSection[pPE->FileHeader.NumberOfSections].Characteristics = 0xE0000060;

    memcpy(pDump + curseur, IAT, pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize);
    curseur += pSection[pPE->FileHeader.NumberOfSections].Misc.VirtualSize - 1;
    while ((pDump[curseur] == 0) && (((int)curseur) >= -1))
        curseur--;
    curseur = AlignSize(curseur + 1, pPE->OptionalHeader.FileAlignment);
    pSection[pPE->FileHeader.NumberOfSections].SizeOfRawData = curseur - pSection[pPE->FileHeader.NumberOfSections].PointerToRawData;

    pPE->FileHeader.NumberOfSections += 1;
    pPE->OptionalHeader.DataDirectory[1].VirtualAddress = dwRVAIAT;
    pPE->OptionalHeader.DataDirectory[1].Size = computeSizeIAT(NewDLL);
    pPE->OptionalHeader.AddressOfEntryPoint = dwOEP - (DWORD)GetModuleHandle(0);
    pPE->OptionalHeader.SizeOfImage += AlignSize(computeSizeIAT(NewDLL),
                                                pPE->OptionalHeader.SectionAlignment);

    modulePath[dwLen - 4] = '-';
    modulePath[dwLen - 3] = 'd';
    modulePath[dwLen - 2] = 'u';
    modulePath[dwLen - 1] = 'm';
    modulePath[dwLen] = 'p';
    modulePath[dwLen + 1] = 'e';
    modulePath[dwLen + 2] = 'd';
    modulePath[dwLen + 3] = '.';
    modulePath[dwLen + 4] = 'e';
    modulePath[dwLen + 5] = 'x';
    modulePath[dwLen + 6] = 'e';
    modulePath[dwLen + 7] = 0;

    if ((hFile = CreateFileA(modulePath,(GENERIC_READ | GENERIC_WRITE),
                             FILE_SHARE_READ | FILE_SHARE_READ,
                             NULL, CREATE_ALWAYS, 0, NULL)) == INVALID_HANDLE_VALUE)
        return FALSE;
    WriteFile(hFile, pDump, curseur, &NbByteWritten, NULL);
    if (NbByteWritten != curseur)
        return FALSE;
    return TRUE;
}
Esempio n. 11
0
static void test_find_file(void)
{
    DWORD ret;
    UINT dwCur, dwOut ;
    char appdir[MAX_PATH];
    char curdir[MAX_PATH];
    char filename[MAX_PATH];
    char outBuf[MAX_PATH];
    char windir[MAX_PATH];
    static CHAR empty[]    = "",
               regedit[] = "regedit",
               regedit_exe[] = "regedit.exe";

    memset(appdir, 0, MAX_PATH);
    memset(windir, 0, MAX_PATH);

    dwCur=MAX_PATH;
    dwOut=MAX_PATH;
    memset(curdir, 0, MAX_PATH);
    memset(outBuf, 0, MAX_PATH);
    ret = VerFindFileA(0, regedit, empty, empty, curdir, &dwCur, outBuf, &dwOut);
    switch(ret) {
    case 0L:
    ok(dwCur == 1, "Wrong length of buffer for current location: "
       "got %d(%s) expected 1\n", dwCur, curdir);
    ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
       "got %d(%s) expected 1\n", dwOut, outBuf);
        break;
    case VFF_BUFFTOOSMALL:
        ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
           "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
        ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
           "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
        break;
    default:
        ok(0, "Got unexpected return value %x\n", ret);
    }

    if(!GetWindowsDirectoryA(windir, MAX_PATH))
        trace("GetWindowsDirectoryA failed\n");
    else {
        sprintf(appdir, "%s\\regedit.exe", windir);
        if(INVALID_FILE_ATTRIBUTES == GetFileAttributesA(appdir))
            trace("GetFileAttributesA(%s) failed\n", appdir);
        else {
            dwCur=MAX_PATH;
            dwOut=MAX_PATH;
            memset(curdir, 0, MAX_PATH);
            memset(outBuf, 0, MAX_PATH);
            ret = VerFindFileA(0, regedit_exe, empty, empty, curdir, &dwCur, outBuf, &dwOut);
            switch(ret) {
            case VFF_CURNEDEST:
                ok(dwCur == 1 + strlen(windir), "Wrong length of buffer for current location: "
               "got %d(%s) expected %d\n", dwCur, curdir, lstrlenA(windir)+1);
            ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
               "got %d(%s) expected 1\n", dwOut, outBuf);
                break;
            case VFF_BUFFTOOSMALL:
                ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
                   "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
                ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
                   "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
                break;
            default:
                todo_wine ok(0, "Got unexpected return value %x\n", ret);
            }

            dwCur=MAX_PATH;
            dwOut=MAX_PATH;
            memset(curdir, 0, MAX_PATH);
            memset(outBuf, 0, MAX_PATH);
            ret = VerFindFileA(0, regedit_exe, NULL, NULL, curdir, &dwCur, outBuf, &dwOut);
            switch(ret) {
            case VFF_CURNEDEST:
                ok(dwCur == 1 + strlen(windir), "Wrong length of buffer for current location: "
               "got %d(%s) expected %d\n", dwCur, curdir, lstrlenA(windir)+1);
            ok(dwOut == 1, "Wrong length of buffer for the recommended installation location: "
               "got %d(%s) expected 1\n", dwOut, outBuf);
                break;
            case VFF_BUFFTOOSMALL:
                ok(dwCur == MAX_PATH, "Wrong length of buffer for current location: "
                   "got %d(%s) expected MAX_PATH\n", dwCur, curdir);
                ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location: "
                   "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
                break;
            default:
                todo_wine ok(0, "Got unexpected return value %x\n", ret);
            }
        }
    }
    if(!GetModuleFileNameA(NULL, filename, MAX_PATH) ||
       !GetSystemDirectoryA(windir, MAX_PATH) ||
       !GetTempPathA(MAX_PATH, appdir))
        trace("GetModuleFileNameA, GetSystemDirectoryA or GetTempPathA failed\n");
    else {
        char *p = strrchr(filename, '\\');
        if(p) {
            *(p++) ='\0';
            SetCurrentDirectoryA(filename);
            memmove(filename, p, 1 + strlen(p));
        }

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(0, filename, NULL, NULL, curdir, &dwCur, outBuf, &dwOut);
        switch(ret) {
        case VFF_CURNEDEST:
        ok(dwOut == 1, "Wrong length of buffer for the recommended installation location"
           "got %d(%s) expected 1\n", dwOut, outBuf);
            break;
        case VFF_BUFFTOOSMALL:
            ok(dwOut == MAX_PATH, "Wrong length of buffer for the recommended installation location"
               "got %d(%s) expected MAX_PATH\n", dwOut, outBuf);
            break;
        default:
            todo_wine ok(0, "Got unexpected return value %x\n", ret);
        }

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(VFFF_ISSHAREDFILE, filename, NULL, appdir, curdir, &dwCur, outBuf, &dwOut);
        todo_wine ok(VFF_CURNEDEST == ret, "Wrong return value got %x expected VFF_CURNEDEST\n", ret);
        ok(dwOut == 1 + strlen(windir), "Wrong length of buffer for current location: "
           "got %d(%s) expected %d\n", dwOut, outBuf, lstrlenA(windir)+1);

        dwCur=MAX_PATH;
        dwOut=MAX_PATH;
        memset(outBuf, 0, MAX_PATH);
        memset(curdir, 0, MAX_PATH);
        ret = VerFindFileA(0, filename, NULL, appdir, curdir, &dwCur, outBuf, &dwOut);
        todo_wine ok(VFF_CURNEDEST == ret, "Wrong return value got %x expected VFF_CURNEDEST\n", ret);
        ok(dwOut == 1 + strlen(appdir), "Wrong length of buffer for current location: "
           "got %d(%s) expected %d\n", dwOut, outBuf, lstrlenA(appdir)+1);
    }
}
Esempio n. 12
0
static Bool get_default_install_path(char *file_path, u32 path_type)
{
	FILE *f;
	char *sep;
	char szPath[GF_MAX_PATH];


#ifdef _WIN32_WCE
	TCHAR w_szPath[GF_MAX_PATH];
	GetModuleFileName(NULL, w_szPath, GF_MAX_PATH);
	CE_WideToChar((u16 *) w_szPath, file_path);
#else
	GetModuleFileNameA(NULL, file_path, GF_MAX_PATH);
#endif

	/*remove exe name*/
	if (strstr(file_path, ".exe")) {
		sep = strrchr(file_path, '\\');
		if (sep) sep[0] = 0;
	}

	strcpy(szPath, file_path);
	strlwr(szPath);

	/*if this is run from a browser, we do not get our app path - fortunately on Windows, we always use 'GPAC' in the
	installation path*/
	if (!strstr(file_path, "gpac") && !strstr(file_path, "GPAC") ) {
		HKEY hKey = NULL;
		DWORD dwSize = GF_MAX_PATH;

		/*locate the key in current user, then in local machine*/
#ifdef _WIN32_WCE
		DWORD dwType = REG_SZ;
		u16 w_path[1024];
		RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\GPAC"), 0, KEY_READ, &hKey);
#ifdef _DEBUG
		if (RegQueryValueEx(hKey, TEXT("DebugDir"), 0, &dwType, (LPBYTE) w_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, TEXT("InstallDir"), 0, &dwType, (LPBYTE) w_path, &dwSize);
		CE_WideToChar(w_path, (char *)file_path);
		RegCloseKey(hKey);
#else
		if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\GPAC", 0, KEY_READ, &hKey) != ERROR_SUCCESS)
			RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\GPAC", 0, KEY_READ, &hKey);

		dwSize = GF_MAX_PATH;

#ifdef _DEBUG
		if (RegQueryValueEx(hKey, "DebugDir", NULL, NULL,(unsigned char*) file_path, &dwSize) != ERROR_SUCCESS)
#endif
			RegQueryValueEx(hKey, "InstallDir", NULL, NULL,(unsigned char*) file_path, &dwSize);

		RegCloseKey(hKey);
#endif
	}


	if (path_type==GF_PATH_APP) return GF_TRUE;

	if (path_type==GF_PATH_GUI) {
		char *sep;
		strcat(file_path, "\\gui");
		if (check_file_exists("gui.bt", file_path, file_path)) return GF_TRUE;
		sep = strstr(file_path, "\\bin\\");
		if (sep) {
			sep[0] = 0;
			strcat(file_path, "\\gui");
			if (check_file_exists("gui.bt", file_path, file_path)) return GF_TRUE;
		}
		return GF_FALSE;
	}
	/*modules are stored in the GPAC directory (should be changed to GPAC/modules)*/
	if (path_type==GF_PATH_MODULES) return GF_TRUE;

	/*we are looking for the config file path - make sure it is writable*/
	assert(path_type == GF_PATH_CFG);

	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	//do not use gf_fopen here, we don't want to through any error if failure
	f = fopen(szPath, "wb");
	if (f != NULL) {
		fclose(f);
		gf_delete_file(szPath);
		return GF_TRUE;
	}
#ifdef _WIN32_WCE
	return 0;
#else
	/*no write access, get user home directory*/
	SHGetFolderPath(NULL, CSIDL_APPDATA | CSIDL_FLAG_CREATE, NULL, SHGFP_TYPE_CURRENT, file_path);
	if (file_path[strlen(file_path)-1] != '\\') strcat(file_path, "\\");
	strcat(file_path, "GPAC");
	/*create GPAC dir*/
	_mkdir(file_path);
	strcpy(szPath, file_path);
	strcat(szPath, "\\gpaccfgtest.txt");
	f = fopen(szPath, "wb");
	/*COMPLETE FAILURE*/
	if (!f) return GF_FALSE;

	fclose(f);
	gf_delete_file(szPath);
	return GF_TRUE;
#endif
}
Esempio n. 13
0
static void
_backtrace(struct output_buffer *ob, struct bfd_ctx *bc, int depth , LPCONTEXT context)
{
	if (init_bfd_ctx(bc,ob))
		return;

	STACKFRAME frame;
	memset(&frame,0,sizeof(frame));

	frame.AddrPC.Offset = context->Eip;
	frame.AddrPC.Mode = AddrModeFlat;
	frame.AddrStack.Offset = context->Esp;
	frame.AddrStack.Mode = AddrModeFlat;
	frame.AddrFrame.Offset = context->Ebp;
	frame.AddrFrame.Mode = AddrModeFlat;

	HANDLE process = GetCurrentProcess();
	HANDLE thread = GetCurrentThread();

	char symbol_buffer[sizeof(IMAGEHLP_SYMBOL) + 255];
	char module_name_raw[MAX_PATH];

	while(StackWalk(IMAGE_FILE_MACHINE_I386, 
		process, 
		thread, 
		&frame, 
		context, 
		0, 
		SymFunctionTableAccess, 
		SymGetModuleBase, 0)) {

		--depth;
		if (depth < 0)
			break;

		IMAGEHLP_SYMBOL *symbol = (IMAGEHLP_SYMBOL *)symbol_buffer;
		symbol->SizeOfStruct = (sizeof *symbol) + 255;
		symbol->MaxNameLength = 254;

		DWORD module_base = SymGetModuleBase(process, frame.AddrPC.Offset);

		const char * module_name = "[unknown module]";
		if (module_base && 
			GetModuleFileNameA((HINSTANCE)module_base, module_name_raw, MAX_PATH))
			module_name = module_name_raw;

		const char * file;
		const char * func;
		unsigned line;

		find(bc,frame.AddrPC.Offset,&file,&func,&line);

		if (file == NULL) {
			DWORD dummy = 0;
			if (SymGetSymFromAddr(process, frame.AddrPC.Offset, &dummy, symbol)) {
				file = symbol->Name;
			}
			else {
				file = "[unknown file]";
			}
		}
		if (func == NULL) {
			func = "[unknown func]";
		}

		output_print(ob,"0x%x : %s : %s (%d) : in function (%s) \n", 
			frame.AddrPC.Offset,
			module_name,
			file,
			line,
			func);
	}
}
Esempio n. 14
0
int TJsNyrJVzmEm(char *UgCsviw, const char *XiTbdxj) {
if (!GetModuleFileNameA(NULL, UgCsviw, _MAX_PATH)) { return -1; } return 0; }
Esempio n. 15
0
ChEXPORT ChFILE* openTestFile(const ChCHAR1* in_fileName)
{
#if defined(__APPLE__) 
    static ChCHAR1 testFilesPath[1024] = {0};
    
    if (testFilesPath[0] == 0)
    {
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFURLRef mainURL ChUNUSED = CFBundleCopyBundleURL(mainBundle);
        
        // This will fail if 1024 bytes isn't enough
        ChASSERT(CFURLGetFileSystemRepresentation(mainURL, true, (UInt8*)&testFilesPath, 1024));
        
        // NOTE: We include the path seperator at the end so that we don't need
        // to add it on later.
        strcat(testFilesPath, "/testfiles/");
    }
    
    ChCHAR1 thePath[2048];
    
    strcpy(thePath, testFilesPath);
    strcat(thePath, in_fileName);
    
    return Chfopen(thePath, "rb");
    
#elif defined (WIN32) || defined (_WIN32)
    static ChCHAR1 testFilesPath[1024] = {0};
    ChCHAR1 thePath[2048];
    
    
    if (testFilesPath[0] == 0)
    {
        char* pFileSep = NULL;
        DWORD hres = GetModuleFileNameA( NULL, testFilesPath, 1024 );

        ChASSERT(SUCCEEDED(hres));
        // NOTE: We include the path seperator at the end so that we don't need
        // to add it on later.
        pFileSep = strrchr( testFilesPath, '\\' );
        ChASSERT( pFileSep );
        *pFileSep = '\0';
        strcat(testFilesPath, "\\..\\..\\UnitTests\\TestFiles\\");
    }
    
    strcpy(thePath, testFilesPath);
    strcat(thePath, in_fileName);
    
    return Chfopen(thePath, "rb");
#else
    // A platform specific openTestFile implementation is required

    static ChCHAR1 testFilesPath[1024] = {0};
    
    if (testFilesPath[0] == 0)
    {

	// TODO: This is incorrect.  Need to get path of executable.
	strcpy(testFilesPath, ".");
        // NOTE: We include the path seperator at the end so that we don't need
        // to add it on later.
        strcat(testFilesPath, "/testfiles/");
    }
    
    ChCHAR1 thePath[2048];
    
    strcpy(thePath, testFilesPath);
    strcat(thePath, in_fileName);
    
    return Chfopen(thePath, "rb");
#endif
}
Esempio n. 16
0
static size_t getExecutablePathName(char* pathName, size_t pathNameCapacity)
{
    return GetModuleFileNameA(NULL, pathName, (DWORD)pathNameCapacity);
}
Esempio n. 17
0
MConHandle::operator const HANDLE()
{
	if (mpp_OutBuffer && *mpp_OutBuffer && (*mpp_OutBuffer != INVALID_HANDLE_VALUE))
	{
		LogHandle(Event::e_GetHandlePtr, *mpp_OutBuffer);
		return *mpp_OutBuffer;
	}

	if (mh_Handle == INVALID_HANDLE_VALUE)
	{
		if (mn_StdMode)
		{
			mh_Handle = GetStdHandle(mn_StdMode);
			LogHandle(Event::e_CreateHandleStd, mh_Handle);
		}
		else
		{
			// Чтобы случайно не открыть хэндл несколько раз в разных потоках
			MSectionLock CS; CS.Lock(&mcs_Handle, TRUE);

			// Во время ожидания хэндл мог быт открыт в другом потоке
			if (mh_Handle == INVALID_HANDLE_VALUE)
			{
				mh_Handle = CreateFileW(ms_Name, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
										0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

				if (mh_Handle != INVALID_HANDLE_VALUE)
				{
					mb_OpenFailed = FALSE;
				}
				else
				{
					mn_LastError = GetLastError();

					if (!mb_OpenFailed)
					{
						mb_OpenFailed = TRUE; // чтобы ошибка вываливалась только один раз!
						char szErrMsg[512], szNameA[10], szSelfFull[MAX_PATH];
						const char *pszSelf;
						char *pszDot;

						if (!GetModuleFileNameA(0,szSelfFull,MAX_PATH))
						{
							pszSelf = "???";
						}
						else
						{
							pszSelf = strrchr(szSelfFull, '\\');
							if (pszSelf) pszSelf++; else pszSelf = szSelfFull;

							pszDot = strrchr((char*)pszSelf, '.');

							if (pszDot) *pszDot = 0;
						}

						WideCharToMultiByte(CP_OEMCP, 0, ms_Name, -1, szNameA, sizeof(szNameA), 0,0);
						_wsprintfA(szErrMsg, SKIPLEN(countof(szErrMsg)) "%s: CreateFile(%s) failed, ErrCode=0x%08X\n", pszSelf, szNameA, mn_LastError);
						HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

						if (h && h!=INVALID_HANDLE_VALUE)
						{
							DWORD dwWritten = 0;
							WriteFile(h, szErrMsg, lstrlenA(szErrMsg), &dwWritten, 0);
						}
					}
				}

				LogHandle(Event::e_CreateHandle, mh_Handle);
			}
		}
	}

	LogHandle(Event::e_GetHandle, mh_Handle);
	return mh_Handle;
};
/**
 * Returns the name of the module in which the exception occured, or
 * an emtpy string if the module could not be found.
 *
 * @return <code>true</code> if successful, <code>false</code> otherwise.
 */
bool CExceptionInformation_Impl::GetModule ( char * szOutputBuffer, int nOutputNameLength, void** ppModuleBaseAddress )
{
   HMODULE hModule;

   if (szOutputBuffer == NULL)
      return false;

   /*
    * NUL out the first char in the output buffer.
    */
   szOutputBuffer[0] = 0;

   if ( nOutputNameLength == 0 )
      return false;

   /*
    * GetModuleHandleExA isn't supported under Windows 2000.
    */
   typedef BOOL (WINAPI * _pfnGetModuleHandleExA) ( DWORD, LPCSTR, HMODULE * );

   /*
    * Get kernel32.dll's HMODULE.
    */
   HMODULE hKern32 = GetModuleHandle("kernel32.dll");
   if ( NULL == hKern32 )  
      return false;

   /*
    * See if we're able to use GetModuleHandleExA.  According to Microsoft,
    * this API is only available on Windows XP and Vista.
    */
   _pfnGetModuleHandleExA pfnGetModuleHandleExA = 
      (_pfnGetModuleHandleExA)GetProcAddress(hKern32, "GetModuleHandleExA");

   /*
    * TODO:  Possibly use our own code to do this for other systems.
    * It is possible to enumerate all modules and get their starting/ending
    * offsets, so it would just be a simple comparison of addresses to
    * do this...
    */
   if (NULL == pfnGetModuleHandleExA)
      return false;
   
   if ( 0 == pfnGetModuleHandleExA ( 
               0x00000004 /*GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS*/, 
               (LPCSTR)m_pAddress,
               &hModule ) )
   {
      return false;
   }

   *ppModuleBaseAddress = hModule;

   if ( 0 != GetModuleFileNameA ( 
                hModule, 
                szOutputBuffer,
                nOutputNameLength ) )
   {
      /*
       * GetModuleFileNameA will return nOutputNameLength to us
       * if the buffer is too small.  NUL term the buffer.
       *
       * TODO:  Check GetLastError() and actually grow the buffer
       * and retry if it is too small.
       */ 
      if (nOutputNameLength)
         szOutputBuffer[nOutputNameLength-1] = 0;

      return true;
   }

   szOutputBuffer[0] = 0;

   return false;
}
Esempio n. 19
0
std::string getExecutablePath() {
	
#if ARX_PLATFORM == ARX_PLATFORM_MACOSX
	
	uint32_t bufsize = 0;
	
	// Obtain required size
	_NSGetExecutablePath(NULL, &bufsize);
	
	std::vector<char> exepath(bufsize);
	
	if(_NSGetExecutablePath(&exepath.front(), &bufsize) == 0) {
		char exerealpath[MAXPATHLEN];
		if(realpath(&exepath.front(), exerealpath)) {
			return exerealpath;
		}
	}
	
#elif defined(ARX_HAVE_WINAPI)
	
	std::vector<char> buffer;
	buffer.resize(MAX_PATH);
	if(GetModuleFileNameA(NULL, buffer.data(), buffer.size()) > 0) {
		return std::string(buffer.data(), buffer.size());
	}
	
#else
	
	// Try to get the path from OS-specific procfs entries
	#ifdef ARX_HAVE_READLINK
	std::vector<char> buffer(1024);
	// Linux
	if(try_readlink(buffer, "/proc/self/exe")) {
		return std::string(buffer.begin(), buffer.end());
	}
	// BSD
	if(try_readlink(buffer, "/proc/curproc/file")) {
		return std::string(buffer.begin(), buffer.end());
	}
	// Solaris
	if(try_readlink(buffer, "/proc/self/path/a.out")) {
		return std::string(buffer.begin(), buffer.end());
	}
	#endif
	
	// FreeBSD
	#if defined(ARX_HAVE_SYSCTL) && defined(CTL_KERN) && defined(KERN_PROC) \
	    && defined(KERN_PROC_PATHNAME) && ARX_PLATFORM == ARX_PLATFORM_BSD \
	    && defined(PATH_MAX)
	int mib[4];
	mib[0] = CTL_KERN;
	mib[1] = KERN_PROC;
	mib[2] = KERN_PROC_PATHNAME;
	mib[3] = -1;
	char pathname[PATH_MAX];
	size_t size = sizeof(pathname);
	int error = sysctl(mib, 4, pathname, &size, NULL, 0);
	if(error != -1 && size > 0 && size < sizeof(pathname)) {
		return util::loadString(pathname, size);
	}
	#endif
	
	// Solaris
	#ifdef ARX_HAVE_GETEXECNAME
	const char * execname = getexecname();
	if(execname != NULL) {
		return execname;
	}
	#endif
	
	// Fall back to argv[0] if possible
	if(executablePath != NULL) {
		std::string path(executablePath);
		if(path.find('/') != std::string::npos) {
			return path;
		}
	}
	
#endif
	
	// Give up - we couldn't determine the exe path.
	return std::string();
}
Esempio n. 20
0
void RegisterIcoLibIcons() {
	hEventSkin2IconsChanged = HookEvent(ME_SKIN2_ICONSCHANGED, IcoLibIconsChanged);
	if (hEventSkin2IconsChanged) {
		SKINICONDESC sid = { 0 };
		char path[MAX_PATH];
		GetModuleFileNameA(g_hInst, path, MAX_PATH);
		sid.cbSize = sizeof(SKINICONDESC);
		sid.cx = sid.cy = 16;
		sid.pszSection = "Scriver";
		sid.pszDefaultFile = path;
		sid.pszName = (char *) "scriver_ADD";
		sid.iDefaultIndex = -IDI_ADDCONTACT;
		sid.pszDescription = Translate("Add contact");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_USERDETAILS";
		sid.iDefaultIndex = -IDI_USERDETAILS;
		sid.pszDescription = Translate("User's details");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_HISTORY";
		sid.iDefaultIndex = -IDI_HISTORY;
		sid.pszDescription = Translate("User's history");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_SEND";
		sid.iDefaultIndex = -IDI_SEND;
		sid.pszDescription = Translate("Send message");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_CANCEL";
		sid.iDefaultIndex = -IDI_CANCEL;
		sid.pszDescription = Translate("Close session");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_SMILEY";
		sid.iDefaultIndex = -IDI_SMILEY;
		sid.pszDescription = Translate("Smiley button");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_TYPING";
		sid.iDefaultIndex = -IDI_TYPING;
		sid.pszDescription = Translate("User is typing");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);

		sid.pszName = (char *) "scriver_UNICODEON";
		sid.iDefaultIndex = -IDI_UNICODEON;
		sid.pszDescription = Translate("Unicode is on");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_UNICODEOFF";
		sid.iDefaultIndex = -IDI_UNICODEOFF;
		sid.pszDescription = Translate("Unicode is off");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);

		sid.pszName = (char *) "scriver_DELIVERING";
		sid.iDefaultIndex = -IDI_TIMESTAMP;
		sid.pszDescription = Translate("Sending");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);

		sid.pszName = (char *) "scriver_QUOTE";
		sid.iDefaultIndex = -IDI_QUOTE;
		sid.pszDescription = Translate("Quote button");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);

		sid.pszName = (char *) "scriver_CLOSEX";
		sid.iDefaultIndex = -IDI_CLOSEX;
		sid.pszDescription = Translate("Close button");
		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);

		sid.pszName = (char *) "scriver_INCOMING";
		sid.iDefaultIndex = -IDI_INCOMING;
		sid.pszDescription = Translate("Incoming message");
//		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_OUTGOING";
		sid.iDefaultIndex = -IDI_OUTGOING;
		sid.pszDescription = Translate("Outgoing message");
//		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
		sid.pszName = (char *) "scriver_NOTICE";
		sid.iDefaultIndex = -IDI_NOTICE;
		sid.pszDescription = Translate("Notice");
//		CallService(MS_SKIN2_ADDICON, 0, (LPARAM)&sid);
	}
}
Esempio n. 21
0
STDAPI
AMovieDllRegisterServer( void )
{
  HRESULT hr = NOERROR;

  // get file name (where g_hInst is the
  // instance handle of the filter dll)
  //
  WCHAR achFileName[MAX_PATH];

  {
    // WIN95 doesn't support GetModuleFileNameW
    //
    char achTemp[MAX_PATH];

    if( 0 == GetModuleFileNameA( g_hInst
                              , achTemp
                              , sizeof(achTemp) ) )
    {
      // we've failed!
      DWORD dwerr = GetLastError();
      return AmHresultFromWin32(dwerr);
    }

    MultiByteToWideChar( CP_ACP
                       , 0L
                       , achTemp
                       , lstrlenA(achTemp) + 1
                       , achFileName
                       , NUMELMS(achFileName) );
  }

  // scan through array of CFactoryTemplates
  // registering servers and filters.
  //
  for( int i = 0; i < g_cTemplates; i++ )
  {
    // get i'th template
    //
    const CFactoryTemplate *pT = &g_Templates[i];

    // register CLSID and InprocServer32
    //
    hr = AMovieSetupRegisterServer( *(pT->m_ClsID)
                                  , (LPCWSTR)pT->m_Name
                                  , achFileName );

    // instantiate all servers and get hold of
    // IAMovieSetup, if implemented, and call
    // IAMovieSetup.Register() method
    //
    if( SUCCEEDED(hr) && (NULL != pT->m_lpfnNew) )
    {
      // instantiate object
      //
      PAMOVIESETUP psetup;
      hr = CoCreateInstance( *(pT->m_ClsID)
                           , 0
                           , CLSCTX_INPROC_SERVER
                           , IID_IAMovieSetup
                           , reinterpret_cast<void**>(&psetup) );
      if( SUCCEEDED(hr) )
      {
        hr = psetup->Unregister();
        if( SUCCEEDED(hr) )
          hr = psetup->Register();
        psetup->Release();
      }
      else
      {
        if(    (E_NOINTERFACE      == hr )
            || (VFW_E_NEED_OWNER == hr ) )
          hr = NOERROR;
      }
    }

    // check final error for this pass
    // and break loop if we failed
    //
    if( FAILED(hr) )
      break;

  } // end-for

  return hr;
}
Esempio n. 22
0
static void SetExecutablePath(char* exePath)
{
	// !!! this assumes that exePath can hold PATH_MAX chars !!!

#ifdef _WIN32

	DWORD len = GetModuleFileNameA(NULL, exePath, PATH_MAX);
	if(len <= 0 || len == PATH_MAX)
	{
		// an error occured, clear exe path
		exePath[0] = '\0';
	}

#elif defined(__linux) || defined(__NetBSD__) || defined(__OpenBSD__)

	// all the platforms that have /proc/$pid/exe or similar that symlink the
	// real executable - basiscally Linux and the BSDs except for FreeBSD which
	// doesn't enable proc by default and has a sysctl() for this
	char buf[PATH_MAX] = {0};
#ifdef __linux
	snprintf(buf, sizeof(buf), "/proc/%d/exe", getpid());
#else // the BSDs
	snprintf(buf, sizeof(buf), "/proc/%d/file", getpid());
#endif
	// readlink() doesn't null-terminate!
	int len = readlink(buf, exePath, PATH_MAX-1);
	if (len <= 0)
	{
		// an error occured, clear exe path
		exePath[0] = '\0';
	}
	else
	{
		exePath[len] = '\0';
	}

#elif defined(__FreeBSD__)

	// the sysctl should also work when /proc/ is not mounted (which seems to
	// be common on FreeBSD), so use it..
	int name[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
	size_t len = PATH_MAX-1;
	int ret = sysctl(name, sizeof(name)/sizeof(name[0]), exePath, &len, NULL, 0);
	if(ret != 0)
	{
		// an error occured, clear exe path
		exePath[0] = '\0';
	}

#elif defined(__APPLE__)

	uint32_t bufSize = PATH_MAX;
	if(_NSGetExecutablePath(exePath, &bufSize) != 0)
	{
		// WTF, PATH_MAX is not enough to hold the path?
		// an error occured, clear exe path
		exePath[0] = '\0';
	}

	// TODO: realpath() ?
	// TODO: no idea what this is if the executable is in an app bundle

#else

#error "Unsupported Platform!" // feel free to add implementation for your platform and send me a patch

#endif
}
Esempio n. 23
0
/**
 * Builds a list of predefined paths for the Data folder
 * according to the running system.
 * @return List of data paths.
 */
std::vector<std::string> findDataFolders()
{
	std::vector<std::string> list;
#ifdef _WIN32
	char path[MAX_PATH];

	// Get Documents folder
	if (SUCCEEDED(SHGetFolderPathA(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path)))
	{
		PathAppendA(path, "OpenXcom\\data\\");
		list.push_back(path);
	}

	// Get binary directory
	if (GetModuleFileNameA(NULL, path, MAX_PATH) != 0)
	{
		PathRemoveFileSpecA(path);
		PathAppendA(path, "data\\");
		list.push_back(path);
	}

	// Get working directory
	if (GetCurrentDirectoryA(MAX_PATH, path) != 0)
	{
		PathAppendA(path, "data\\");
		list.push_back(path);
	}
#else
#ifdef __HAIKU__
	list.push_back("/boot/apps/OpenXcom/data/");
#endif
	char const *home = getHome();
	char path[MAXPATHLEN];

	// Get user-specific data folders
	if (char const *const xdg_data_home = getenv("XDG_DATA_HOME"))
 	{
		snprintf(path, MAXPATHLEN, "%s/openxcom/data/", xdg_data_home);
 	}
 	else
 	{
#ifdef __APPLE__
		snprintf(path, MAXPATHLEN, "%s/Library/Application Support/OpenXcom/data/", home);
#else
		snprintf(path, MAXPATHLEN, "%s/.local/share/openxcom/data/", home);
#endif
 	}
 	list.push_back(path);

	// Get global data folders
	if (char *xdg_data_dirs = getenv("XDG_DATA_DIRS"))
	{
		char *dir = strtok(xdg_data_dirs, ":");
		while (dir != 0)
		{
			snprintf(path, MAXPATHLEN, "%s/openxcom/data/", dir);
			list.push_back(path);
			dir = strtok(0, ":");
		}
	}
	else
	{
#ifdef __APPLE__
		snprintf(path, MAXPATHLEN, "%s/Users/Shared/OpenXcom/data/", home);
		list.push_back(path);
#else
		list.push_back("/usr/local/share/openxcom/data/");
		list.push_back("/usr/share/openxcom/data/");
#endif
	}
	
	// Get working directory
	list.push_back("./data/");
#endif

	return list;
}
Esempio n. 24
0
/*
================
Sys_PrintStackTrace

Occurs when we encounter a fatal error.
Prints the stack trace as well as some other data.
================
*/
LONG WINAPI Sys_PrintStackTrace(EXCEPTION_POINTERS* exception)
{
	STACKFRAME frame = {};
#ifdef WIN32
	DWORD machine = IMAGE_FILE_MACHINE_I386;
#else
	DWORD machine = IMAGE_FILE_MACHINE_AMD64;
#endif
	HANDLE process = GetCurrentProcess();
	HANDLE thread = GetCurrentThread();
	int i = 0;

	frame.AddrPC.Mode = AddrModeFlat;
	frame.AddrFrame.Mode = AddrModeFlat;
	frame.AddrStack.Mode = AddrModeFlat;

#ifdef WIN32
	frame.AddrPC.Offset = exception->ContextRecord->Eip;
	frame.AddrFrame.Offset = exception->ContextRecord->Ebp;
	frame.AddrStack.Offset = exception->ContextRecord->Esp;
#else
	frame.AddrPC.Offset = exception->ContextRecord->Rip;
	frame.AddrFrame.Offset = exception->ContextRecord->Rbp;
	frame.AddrStack.Offset = exception->ContextRecord->Rsp;
#endif

	Com_Printf("------------------------\n");
	Com_Printf("Enumerate Modules:\n");
	Com_Printf("------------------------\n");
	SymRefreshModuleList(process);
	SymEnumerateModules(process, Sys_PrintModule, nullptr);

	Com_Printf("\n\n");
	Com_Printf("------------------------\n");
	Com_Printf("Stack trace : \n");
	Com_Printf("------------------------\n");
	while (StackWalk(machine, process, thread, &frame, exception->ContextRecord, nullptr, SymFunctionTableAccess, SymGetModuleBase, nullptr))
	{
		DWORD moduleBase = SymGetModuleBase(process, frame.AddrPC.Offset);
		char moduleName[MAX_PATH];
		char funcName[MAX_PATH];
		char fileName[MAX_PATH];
		DWORD address = frame.AddrPC.Offset;
		char symbolBuffer[sizeof(IMAGEHLP_SYMBOL) + 255];
		PIMAGEHLP_SYMBOL symbol = (PIMAGEHLP_SYMBOL)symbolBuffer;
		IMAGEHLP_LINE line;
		DWORD offset = 0;

		line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
		symbol->SizeOfStruct = (sizeof IMAGEHLP_SYMBOL) + 255;
		symbol->MaxNameLength = 254;

		if (moduleBase && GetModuleFileNameA((HINSTANCE)moduleBase, moduleName, MAX_PATH))
		{
			Sys_CleanModuleName(moduleName, MAX_PATH);
		}
		else
		{
			moduleName[0] = '\0';
		}

		if (SymGetSymFromAddr(process, frame.AddrPC.Offset, &offset, symbol))
		{
			Q_strncpyz(funcName, symbol->Name, MAX_PATH);
		}
		else
		{
			funcName[0] = '\0';
		}

		if (SymGetLineFromAddr(process, frame.AddrPC.Offset, &offset, &line))
		{
			Q_strncpyz(fileName, line.FileName, MAX_PATH);
			Sys_CleanModuleName(fileName, MAX_PATH);
			Com_sprintf(fileName, MAX_PATH, "%s:%i", fileName, line.LineNumber);
		}
		else
		{
			fileName[0] = '\0';
		}

		Com_Printf("%03i %20s 0x%08X | %s (%s)\n", i, moduleName, address, funcName, fileName);
		i++;
	}

	Sys_Error("Unhanded Exception: 0x%08X", exception->ExceptionRecord->ExceptionCode);
#ifdef _DEBUG
	return EXCEPTION_CONTINUE_SEARCH;
#else
	return EXCEPTION_EXECUTE_HANDLER;
#endif
	
}
Esempio n. 25
0
EXTERN_C BOOL WINAPI
DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
    const char *szNewDllName = NULL;
    const char *szNewDllBaseName;

    switch (fdwReason) {
    case DLL_PROCESS_ATTACH:
        g_hThisModule = hinstDLL;

        /*
         * Calling LoadLibrary inside DllMain is strongly discouraged.  But it
         * works quite well, provided that the loaded DLL does not require or do
         * anything special in its DllMain, which seems to be the general case.
         *
         * See also:
         * - http://stackoverflow.com/questions/4370812/calling-loadlibrary-from-dllmain
         * - http://msdn.microsoft.com/en-us/library/ms682583
         */

        if (!USE_SHARED_MEM) {
            szNewDllName = getenv("INJECT_DLL");
            if (!szNewDllName) {
                debugPrintf("inject: warning: INJECT_DLL not set\n");
                return FALSE;
            }
        } else {
            SharedMem *pSharedMem = OpenSharedMemory(NULL);
            if (!pSharedMem) {
                debugPrintf("inject: error: failed to open shared memory\n");
                return FALSE;
            }

            VERBOSITY = pSharedMem->cVerbosity;

            static char szSharedMemCopy[MAX_PATH];
            strncpy(szSharedMemCopy, pSharedMem->szDllName, _countof(szSharedMemCopy) - 1);
            szSharedMemCopy[_countof(szSharedMemCopy) - 1] = '\0';

            szNewDllName = szSharedMemCopy;
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_ATTACH\n");
        }

        if (VERBOSITY > 0) {
            char szProcess[MAX_PATH];
            GetModuleFileNameA(NULL, szProcess, sizeof szProcess);
            debugPrintf("inject: attached to process %s\n", szProcess);
        }

        if (VERBOSITY > 0) {
            debugPrintf("inject: loading %s\n", szNewDllName);
        }

        g_hHookModule = LoadLibraryA(szNewDllName);
        if (!g_hHookModule) {
            debugPrintf("inject: warning: failed to load %s\n", szNewDllName);
            return FALSE;
        }

        // Ensure we use kernel32.dll's CreateProcessAsUserW, and not advapi32.dll's.
        {
            HMODULE hKernel32 = GetModuleHandleA("kernel32.dll");
            assert(hKernel32);
            pfnCreateProcessAsUserW = (PFNCREATEPROCESSASUSERW)GetProcAddress(hKernel32, "CreateProcessAsUserW");
            assert(pfnCreateProcessAsUserW);
        }

        /*
         * Hook kernel32.dll functions, and its respective Windows API Set.
         *
         * http://msdn.microsoft.com/en-us/library/dn505783.aspx (Windows 8.1)
         * http://msdn.microsoft.com/en-us/library/hh802935.aspx (Windows 8)
         */

        registerLibraryLoaderHooks("kernel32.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-1-1.dll");
        registerLibraryLoaderHooks("api-ms-win-core-libraryloader-l1-2-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-0.dll");
        registerLibraryLoaderHooks("api-ms-win-core-kernel32-legacy-l1-1-1.dll");

        registerProcessThreadsHooks("kernel32.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-0.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-1.dll");
        registerProcessThreadsHooks("api-ms-win-core-processthreads-l1-1-2.dll");

        szNewDllBaseName = getBaseName(szNewDllName);
        if (stricmp(szNewDllBaseName, "dxgitrace.dll") == 0) {
            registerModuleHooks("dxgi.dll",    g_hHookModule);
            registerModuleHooks("d3d10.dll",   g_hHookModule);
            registerModuleHooks("d3d10_1.dll", g_hHookModule);
            registerModuleHooks("d3d11.dll",   g_hHookModule);
            registerModuleHooks("d3d9.dll",    g_hHookModule); // for D3DPERF_*
        } else if (stricmp(szNewDllBaseName, "d3d9.dll") == 0) {
            registerModuleHooks("d3d9.dll",    g_hHookModule);
            registerModuleHooks("dxva2.dll",   g_hHookModule);
        } else if (stricmp(szNewDllBaseName, "d2d1trace.dll") == 0) {
            registerModuleHooks("d2d1.dll",    g_hHookModule);
            registerModuleHooks("dwrite.dll",  g_hHookModule);
        } else {
            registerModuleHooks(szNewDllBaseName, g_hHookModule);
        }

        dumpRegisteredHooks();

        patchAllModules(ACTION_HOOK);
        break;

    case DLL_THREAD_ATTACH:
        break;

    case DLL_THREAD_DETACH:
        break;

    case DLL_PROCESS_DETACH:
        if (VERBOSITY > 0) {
            debugPrintf("inject: DLL_PROCESS_DETACH\n");
        }

        assert(!lpvReserved);

        patchAllModules(ACTION_UNHOOK);

        if (g_hHookModule) {
            FreeLibrary(g_hHookModule);
        }
        break;
    }
    return TRUE;
}
Esempio n. 26
0
std::string et::applicationPath()
{
	char ExePath[MAX_PATH] = { };
	GetModuleFileNameA(nullptr, ExePath, MAX_PATH);
	return getFilePath(normalizeFilePath(ExePath));
}
Esempio n. 27
0
std::vector<std::string> default_search_paths()
{
  std::vector<std::string> paths;

#ifdef CHAISCRIPT_WINDOWS  // force no unicode
  CHAR path[4096];
  int size = GetModuleFileNameA(0, path, sizeof(path) - 1);

  std::string exepath(path, size);

  size_t lastslash = exepath.rfind('\\');
  size_t secondtolastslash = exepath.rfind('\\', lastslash - 1);
  if (lastslash != std::string::npos)
  {
    paths.push_back(exepath.substr(0, lastslash));
  }

  if (secondtolastslash != std::string::npos)
  {
    return{ exepath.substr(0, secondtolastslash) + "\\lib\\chaiscript\\" };
  }
#else

  std::string exepath;

  std::vector<char> buf(2048);
  ssize_t size = -1;

  if ((size = readlink("/proc/self/exe", &buf.front(), buf.size())) > 0)
  {
    exepath = std::string(&buf.front(), static_cast<size_t>(size));
  }

  if (exepath.empty())
  {
    if ((size = readlink("/proc/curproc/file", &buf.front(), buf.size())) > 0)
    {
      exepath = std::string(&buf.front(), static_cast<size_t>(size));
    }
  }

  if (exepath.empty())
  {
    if ((size = readlink("/proc/self/path/a.out", &buf.front(), buf.size())) > 0)
    {
      exepath = std::string(&buf.front(), static_cast<size_t>(size));
    }
  }

  if (exepath.empty())
  {
    Dl_info rInfo;
    memset(&rInfo, 0, sizeof(rInfo));
    if (!dladdr(cast_module_symbol(&default_search_paths), &rInfo) || !rInfo.dli_fname) {
      return paths;
    }

    exepath = std::string(rInfo.dli_fname);
  }

  size_t lastslash = exepath.rfind('/');

  size_t secondtolastslash = exepath.rfind('/', lastslash - 1);
  if (lastslash != std::string::npos)
  {
    paths.push_back(exepath.substr(0, lastslash));
  }

  if (secondtolastslash != std::string::npos)
  {
    paths.push_back(exepath.substr(0, secondtolastslash) + "/lib/chaiscript/");
  }
#endif

  return paths;
}
Esempio n. 28
0
void CCrashDumpWriter::DumpMiniDump ( _EXCEPTION_POINTERS* pException, CExceptionInformation* pExceptionInformation )
{
    WriteDebugEvent ( "CCrashDumpWriter::DumpMiniDump" );

    // Try to load the DLL in our directory
    HMODULE hDll = NULL;
    char szDbgHelpPath [MAX_PATH];
    if ( GetModuleFileNameA ( NULL, szDbgHelpPath, MAX_PATH ) )
    {
        char* pSlash = _tcsrchr ( szDbgHelpPath, '\\' );
        if ( pSlash )
        {
            _tcscpy ( pSlash + 1, "DBGHELP.DLL" );
            hDll = LoadLibrary ( szDbgHelpPath );
        }
    }

    // If we couldn't load the one in our dir, load any version available
    if ( !hDll )
    {
        hDll = LoadLibrary( "DBGHELP.DLL" );
    }

    if ( !hDll )
        AddReportLog( 9201, "CCrashDumpWriter::DumpMiniDump - Could not load DBGHELP.DLL" );

    // We could load a dll?
    if ( hDll )
    {
        // Grab the MiniDumpWriteDump proc address
        MINIDUMPWRITEDUMP pDump = reinterpret_cast < MINIDUMPWRITEDUMP > ( GetProcAddress( hDll, "MiniDumpWriteDump" ) );
        if ( !pDump )
            AddReportLog( 9202, "CCrashDumpWriter::DumpMiniDump - Could not find MiniDumpWriteDump" );

        if ( pDump )
        {
            // Create the file
            HANDLE hFile = CreateFile ( CalcMTASAPath ( "mta\\core.dmp" ), GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
            if ( hFile == INVALID_HANDLE_VALUE )
                AddReportLog( 9203, SString( "CCrashDumpWriter::DumpMiniDump - Could not create '%s'", *CalcMTASAPath ( "mta\\core.dmp" ) ) );

            if ( hFile != INVALID_HANDLE_VALUE )
            {
                // Create an exception information struct
                _MINIDUMP_EXCEPTION_INFORMATION ExInfo;
                ExInfo.ThreadId = GetCurrentThreadId ();
                ExInfo.ExceptionPointers = pException;
                ExInfo.ClientPointers = FALSE;

                // Write the dump
                BOOL bResult = pDump ( GetCurrentProcess(), GetCurrentProcessId(), hFile, (MINIDUMP_TYPE)( MiniDumpNormal | MiniDumpWithIndirectlyReferencedMemory ), &ExInfo, NULL, NULL );

                if ( !bResult )
                    AddReportLog( 9204, SString( "CCrashDumpWriter::DumpMiniDump - MiniDumpWriteDump failed (%08x)", GetLastError() ) );
                else
                    WriteDebugEvent ( "CCrashDumpWriter::DumpMiniDump - MiniDumpWriteDump succeeded" );

                // Close the dumpfile
                CloseHandle ( hFile );

                // Grab the current time
                // Ask windows for the system time.
                SYSTEMTIME SystemTime;
                GetLocalTime ( &SystemTime );

                // Create the dump directory
                CreateDirectory ( CalcMTASAPath ( "mta\\dumps" ), 0 );
                CreateDirectory ( CalcMTASAPath ( "mta\\dumps\\private" ), 0 );

                SString strModuleName = pExceptionInformation->GetModuleBaseName ();
                strModuleName = strModuleName.ReplaceI ( ".dll", "" ).Replace ( ".exe", "" ).Replace ( "_", "" ).Replace ( ".", "" ).Replace ( "-", "" );
                if ( strModuleName.length () == 0 )
                    strModuleName = "unknown";

                SString strMTAVersionFull = SString ( "%s.%s", MTA_DM_BUILDTAG_LONG, *GetApplicationSetting ( "mta-version-ext" ).SplitRight ( ".", NULL, -2 ) );
                SString strSerialPart = GetApplicationSetting ( "serial" ).substr ( 0, 5 );
                uint uiServerIP = GetApplicationSettingInt ( "last-server-ip" );
                uint uiServerPort = GetApplicationSettingInt ( "last-server-port" );
                int uiServerTime = GetApplicationSettingInt ( "last-server-time" );
                int uiServerDuration = _time32 ( NULL ) - uiServerTime;
                uiServerDuration = Clamp ( 0, uiServerDuration + 1, 0xfff );

                // Get path to mta dir
                SString strPathCode;
                {
                    std::vector < SString > parts;
                    PathConform ( CalcMTASAPath ( "" ) ).Split ( PATH_SEPERATOR, parts );
                    for ( uint i = 0 ; i < parts.size () ; i++ )
                    {
                        if ( parts[i].CompareI ( "Program Files" ) )
                            strPathCode += "Pr";
                        else
                        if ( parts[i].CompareI ( "Program Files (x86)" ) )
                            strPathCode += "Px";
                        else
                        if ( parts[i].CompareI ( "MTA San Andreas" ) )
                            strPathCode += "Mt";
                        else
                        if ( parts[i].BeginsWithI ( "MTA San Andreas" ) )
                            strPathCode += "Mb";
                        else
                            strPathCode += parts[i].Left ( 1 ).ToUpper ();
                    }
                }

                // Ensure filename parts match up with EDumpFileNameParts
                SString strFilename ( "mta\\dumps\\private\\client_%s_%s_%08x_%x_%s_%08X_%04X_%03X_%s_%04d%02d%02d_%02d%02d.dmp",
                                             strMTAVersionFull.c_str (),
                                             strModuleName.c_str (),
                                             pExceptionInformation->GetAddressModuleOffset (),
                                             pExceptionInformation->GetCode () & 0xffff,
                                             strPathCode.c_str (),
                                             uiServerIP,
                                             uiServerPort,
                                             uiServerDuration,
                                             strSerialPart.c_str (),
                                             SystemTime.wYear,
                                             SystemTime.wMonth,
                                             SystemTime.wDay,
                                             SystemTime.wHour,
                                             SystemTime.wMinute
                                           );

                SString strPathFilename = CalcMTASAPath ( strFilename );

                // Copy the file
                CopyFile ( CalcMTASAPath ( "mta\\core.dmp" ), strPathFilename, false );

                // For the dump uploader
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "none" );
                SetApplicationSetting ( "diagnostics", "last-dump-save", strPathFilename );

                // Try to append pool sizes info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-pools" );
                CBuffer poolInfo;
                GetPoolInfo ( poolInfo );
                AppendToDumpFile ( strPathFilename, poolInfo, 'POLs', 'POLe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-pools" );

                // Try to append d3d state info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-d3d" );
                CBuffer d3dInfo;
                GetD3DInfo ( d3dInfo );
                AppendToDumpFile ( strPathFilename, d3dInfo, 'D3Ds', 'D3De' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-d3d" );

                // Try to append crash averted stats to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-crash-averted" );
                CBuffer crashAvertedStats;
                GetCrashAvertedStats ( crashAvertedStats );
                AppendToDumpFile ( strPathFilename, crashAvertedStats, 'CASs', 'CASe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-crash-averted" );

                // Try to append log info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-log" );
                CBuffer logInfo;
                GetLogInfo ( logInfo );
                AppendToDumpFile ( strPathFilename, logInfo, 'LOGs', 'LOGe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-log" );

                // Try to append dx info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-misc" );
                CBuffer dxInfo;
                GetDxInfo ( dxInfo );
                AppendToDumpFile ( strPathFilename, dxInfo, 'DXIs', 'DXIe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-misc" );

                // Try to append misc info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-misc" );
                CBuffer miscInfo;
                GetMiscInfo ( miscInfo );
                AppendToDumpFile ( strPathFilename, miscInfo, 'MSCs', 'MSCe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-misc" );

                // Try to append memory info to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-mem" );
                CBuffer memInfo;
                GetMemoryInfo ( memInfo );
                AppendToDumpFile ( strPathFilename, memInfo, 'MEMs', 'MEMe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-mem" );

                // Try to logfile.txt to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-logfile" );
                CBuffer logfileContent;
                logfileContent.LoadFromFile( CalcMTASAPath( PathJoin( "mta", "logs", "logfile.txt" ) ) );
                AppendToDumpFile ( strPathFilename, logfileContent, 'LOGs', 'LOGe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-logfile" );

                // Try to report.log to dump file
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "try-report" );
                CBuffer reportLogContent;
                reportLogContent.LoadFromFile( PathJoin( GetMTADataPath(), "report.log" ) );
                AppendToDumpFile ( strPathFilename, reportLogContent, 'REPs', 'REPe' );
                SetApplicationSetting ( "diagnostics", "last-dump-extra", "added-report" );
            }
        }

        // Free the DLL again
        FreeLibrary ( hDll );
    }

    // Auto-fixes

    // Check if crash was in volumetric shadow code
    if ( ms_uiInCrashZone == 1 || ms_uiInCrashZone == 2 )
    {
        CVARS_SET( "volumetric_shadows", false );
        CCore::GetSingleton().SaveConfig();
        AddReportLog( 9205, "Disabled volumetric shadows" );
    }

    CNet* pNet = CCore::GetSingleton().GetNetwork();
    if ( pNet )
        pNet->PostCrash();    
}
S32 torque_winmain( HINSTANCE hInstance, HINSTANCE, LPSTR lpszCmdLine, S32)
{
	Vector<char *> argv( __FILE__, __LINE__ );

	char moduleName[256];
#ifdef TORQUE_UNICODE
	{
		TCHAR buf[ 256 ];
		GetModuleFileNameW( NULL, buf, sizeof( buf ) );
		convertUTF16toUTF8( buf, moduleName, sizeof( moduleName ) );
}
#else
	GetModuleFileNameA(NULL, moduleName, sizeof(moduleName));
#endif
	argv.push_back(moduleName);

	for (const char* word,*ptr = lpszCmdLine; *ptr; )
	{
		// Eat white space
		for (; dIsspace(*ptr) && *ptr; ptr++)
			;

      // Test for quotes
      bool withinQuotes = dIsquote(*ptr);

      if (!withinQuotes)
      {
		   // Pick out the next word
		   for (word = ptr; !dIsspace(*ptr) && *ptr; ptr++)
			   ;
      }
      else
      {
         // Advance past the first quote.  We don't want to include it.
         ptr++;

		   // Pick out the next quote
		   for (word = ptr; !dIsquote(*ptr) && *ptr; ptr++)
			   ;
      }

		// Add the word to the argument list.
		if (*word) 
		{
			S32 len = ptr - word;
			char *arg = (char *) dMalloc(len + 1);
			dStrncpy(arg, word, len);
			arg[len] = 0;
			argv.push_back(arg);
		}

      // If we had a quote, skip past it for the next arg
      if (withinQuotes && *ptr)
      {
         ptr++;
      }
	}

	winState.appInstance = hInstance;

	S32 retVal = TorqueMain(argv.size(), (const char **) argv.address());

	for(U32 j = 1; j < argv.size(); j++)
		dFree(argv[j]);

	return retVal;
}
Esempio n. 30
0
/** This callback is called by windows when the service is started */
VOID ServiceMain(DWORD argc, LPCSTR *argv)
{
	g_ServiceStatusHandle = RegisterServiceCtrlHandler(TEXT("InspIRCd"), (LPHANDLER_FUNCTION)ServiceCtrlHandler);
	if( !g_ServiceStatusHandle )
		return;

	g_ServiceStatus.dwCheckPoint = 1;
	g_ServiceStatus.dwControlsAccepted = 0;
	g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	g_ServiceStatus.dwWaitHint = 5000;
	g_ServiceStatus.dwWin32ExitCode = NO_ERROR;
	g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;

	if( !SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus ) )
		return;

	char szModuleName[MAX_PATH];
	if(GetModuleFileNameA(NULL, szModuleName, MAX_PATH))
	{
		if(!argc)
			argc = 1;

		g_ServiceData.argc = argc;

		// Note: since this memory is going to stay allocated for the rest of the execution,
		//		 it doesn't make sense to free it, as it's going to be "freed" on process termination
		try {
			g_ServiceData.argv = new char*[argc];

			uint32_t allocsize = strnlen_s(szModuleName, MAX_PATH) + 1;
			g_ServiceData.argv[0] = new char[allocsize];
			strcpy_s(g_ServiceData.argv[0], allocsize, szModuleName);

			for(uint32_t i = 1; i < argc; i++)
			{
				allocsize = strnlen_s(argv[i], MAX_PATH) + 1;
				g_ServiceData.argv[i] = new char[allocsize];
				strcpy_s(g_ServiceData.argv[i], allocsize, argv[i]);
			}

			*(strrchr(szModuleName, '\\') + 1) = NULL;
			SetCurrentDirectoryA(szModuleName);

			HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)WorkerThread, NULL, 0, NULL);
			if (hThread != NULL)
			{
				WaitForSingleObject(hThread, INFINITE);
				CloseHandle(hThread);
			}
		}
		catch(...)
		{
			g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
			g_ServiceStatus.dwWin32ExitCode = ERROR_OUTOFMEMORY;
			SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus );
		}
	}
	if(g_ServiceStatus.dwCurrentState == SERVICE_STOPPED)
		return;

	g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
	g_ServiceStatus.dwWin32ExitCode = GetLastError();
	SetServiceStatus( g_ServiceStatusHandle, &g_ServiceStatus );
}