您当前的位置:首页 > IT编程 > C++
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:C++ GetModuleFileNameW函数代码示例

51自学网 2021-06-01 21:11:10
  C++
这篇教程C++ GetModuleFileNameW函数代码示例写得很实用,希望能帮到您。

本文整理汇总了C++中GetModuleFileNameW函数的典型用法代码示例。如果您正苦于以下问题:C++ GetModuleFileNameW函数的具体用法?C++ GetModuleFileNameW怎么用?C++ GetModuleFileNameW使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。

在下文中一共展示了GetModuleFileNameW函数的30个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: GetModuleFileNameA

/*** Implementation of GetModuleFileNameA - requires wide to sbcs char conversion*/RTEXP	DWORD GetModuleFileNameA( HMODULE hModule, char* lpFilename, DWORD nSize ) {	GetModuleFileNameW(hModule, wbuffer, BUFSIZ);	return(WideCharToMultiByte(CP_ACP, (DWORD)NULL, wbuffer, -1, lpFilename, nSize, NULL, NULL));}
开发者ID:luaforge,项目名称:lua4wince,代码行数:7,


示例2: MyAssertDumpToFile

void MyAssertDumpToFile(const wchar_t* pszFile, int nLine, const wchar_t* pszTest){	wchar_t dmpfile[MAX_PATH+64] = L"", szVer4[8] = L"", szLine[64];	typedef HRESULT (WINAPI* SHGetFolderPath_t)(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);	HMODULE hShell = LoadLibrary(L"shell32.dll");	SHGetFolderPath_t shGetFolderPath = hShell ? (SHGetFolderPath_t)GetProcAddress(hShell, "SHGetFolderPathW") : NULL;	HRESULT hrc = shGetFolderPath ? shGetFolderPath(NULL, CSIDL_DESKTOPDIRECTORY, NULL, 0/*SHGFP_TYPE_CURRENT*/, dmpfile) : E_FAIL;	if (hShell) FreeLibrary(hShell);	if (FAILED(hrc))	{		memset(dmpfile, 0, sizeof(dmpfile));		if (!GetTempPath(MAX_PATH, dmpfile) || !*dmpfile)		{			//pszError = L"CreateDumpForReport called, get desktop or temp folder failed";			return;		}	}	wcscat_c(dmpfile, (*dmpfile && dmpfile[lstrlen(dmpfile)-1] != L'//') ? L"//ConEmuTrap" : L"ConEmuTrap");	CreateDirectory(dmpfile, NULL);	int nLen = lstrlen(dmpfile);	lstrcpyn(szVer4, _T(MVV_4a), countof(szVer4));	static LONG snAutoIndex = 0;	LONG nAutoIndex = InterlockedIncrement(&snAutoIndex);	msprintf(dmpfile+nLen, countof(dmpfile)-nLen, L"//Assert-%02u%02u%02u%s-%u-%u.txt", MVV_1, MVV_2, MVV_3, szVer4, GetCurrentProcessId(), nAutoIndex);	HANDLE hFile = CreateFile(dmpfile, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);	if (hFile == INVALID_HANDLE_VALUE)	{		//pszError = L"Failed to create dump file";		return;	}	DWORD nWrite;	msprintf(szLine, countof(szLine), L"CEAssert PID=%u TID=%u/r/nAssertion in ", GetCurrentProcessId(), GetCurrentThreadId());	nWrite = lstrlen(szLine)*2;	WriteFile(hFile, szLine, nWrite, &nWrite, NULL);	if (!GetModuleFileNameW(NULL, dmpfile, countof(dmpfile)-2))		lstrcpyn(dmpfile, L"<unknown>/r/n", countof(dmpfile));	else		wcscat_c(dmpfile, L"/r/n");	nWrite = lstrlen(dmpfile)*2;	WriteFile(hFile, dmpfile, nWrite, &nWrite, NULL);	// File.cpp: 123/r/n	if (pszFile)	{		nWrite = lstrlen(pszFile)*2;		WriteFile(hFile, pszFile, nWrite, &nWrite, NULL);		msprintf(szLine, countof(szLine), L": %i/r/n/r/n", nLine);		nWrite = lstrlen(szLine)*2;		WriteFile(hFile, szLine, nWrite, &nWrite, NULL);	}	if (pszTest)	{		nWrite = lstrlen(pszTest)*2;		WriteFile(hFile, pszTest, nWrite, &nWrite, NULL);		WriteFile(hFile, L"/r/n", 4, &nWrite, NULL);	}	CloseHandle(hFile);}
开发者ID:BigVal71,项目名称:ConEmu,代码行数:66,


示例3: _dbg_dbginit

extern "C" DLL_EXPORT const char* _dbg_dbginit(){    if(!EngineCheckStructAlignment(UE_STRUCT_TITAN_ENGINE_CONTEXT, sizeof(TITAN_ENGINE_CONTEXT_t)))        return "Invalid TITAN_ENGINE_CONTEXT_t alignment!";    if(sizeof(TITAN_ENGINE_CONTEXT_t) != sizeof(REGISTERCONTEXT))        return "Invalid REGISTERCONTEXT alignment!";    dputs("Initializing wait objects...");    waitinitialize();    dputs("Initializing debugger...");    dbginit();    dputs("Initializing debugger functions...");    dbgfunctionsinit();    dputs("Setting JSON memory management functions...");    json_set_alloc_funcs(json_malloc, json_free);    dputs("Initializing capstone...");    Capstone::GlobalInitialize();    dputs("Initializing Yara...");    if(yr_initialize() != ERROR_SUCCESS)        return "Failed to initialize Yara!";    dputs("Getting directory information...");    wchar_t wszDir[deflen] = L"";    if(!GetModuleFileNameW(hInst, wszDir, deflen))        return "GetModuleFileNameW failed!";    char dir[deflen] = "";    strcpy_s(dir, StringUtils::Utf16ToUtf8(wszDir).c_str());    int len = (int)strlen(dir);    while(dir[len] != '//')        len--;    dir[len] = 0;    strcpy_s(alloctrace, dir);    strcat_s(alloctrace, "//alloctrace.txt");    DeleteFileW(StringUtils::Utf8ToUtf16(alloctrace).c_str());    setalloctrace(alloctrace);    strcpy_s(dbbasepath, dir); //debug directory    strcat_s(dbbasepath, "//db");    CreateDirectoryW(StringUtils::Utf8ToUtf16(dbbasepath).c_str(), 0); //create database directory    char szLocalSymbolPath[MAX_PATH] = "";    strcpy_s(szLocalSymbolPath, dir);    strcat_s(szLocalSymbolPath, "//symbols");    char cachePath[MAX_SETTING_SIZE];    if(!BridgeSettingGet("Symbols", "CachePath", cachePath) || !*cachePath)    {        strcpy_s(szSymbolCachePath, szLocalSymbolPath);        BridgeSettingSet("Symbols", "CachePath", ".//symbols");    }    else    {        if (_strnicmp(cachePath, ".//", 2) == 0)        {            strncpy_s(szSymbolCachePath, dir, _TRUNCATE);            strncat_s(szSymbolCachePath, cachePath + 1, _TRUNCATE);        }        else        {            // Trim the buffer to fit inside MAX_PATH            strncpy_s(szSymbolCachePath, cachePath, _TRUNCATE);        }        if(strstr(szSymbolCachePath, "http://") || strstr(szSymbolCachePath, "https://"))        {            if(Script::Gui::MessageYesNo("It is strongly discouraged to use symbol servers in your path directly (use the store option instead)./n/nDo you want me to fix this?"))            {                strcpy_s(szSymbolCachePath, szLocalSymbolPath);                BridgeSettingSet("Symbols", "CachePath", ".//symbols");            }        }    }    dputs(szSymbolCachePath);    SetCurrentDirectoryW(StringUtils::Utf8ToUtf16(dir).c_str());    dputs("Allocating message stack...");    gMsgStack = MsgAllocStack();    if(!gMsgStack)        return "Could not allocate message stack!";    dputs("Initializing global script variables...");    varinit();    dputs("Registering debugger commands...");    registercommands();    dputs("Starting command loop...");    hCommandLoopThread = CreateThread(0, 0, DbgCommandLoopThread, 0, 0, 0);    char plugindir[deflen] = "";    strcpy_s(plugindir, dir);    strcat_s(plugindir, "//plugins");    CreateDirectoryW(StringUtils::Utf8ToUtf16(plugindir).c_str(), 0);    dputs("Loading plugins...");    pluginload(plugindir);    dputs("Handling command line...");    //handle command line    int argc = 0;    wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc);    if(argc == 2) //we have an argument    {        String str = "init /"";        str += StringUtils::Utf16ToUtf8(argv[1]);        str += "/"";        DbgCmdExec(str.c_str());    }    else if(argc == 5) //4 arguments (JIT)    {        if(_wcsicmp(argv[1], L"-a") == 0 && !_wcsicmp(argv[3], L"-e"))//.........这里部分代码省略.........
开发者ID:songzhaochun,项目名称:x64dbg,代码行数:101,


示例4: Perl_set_caret_X

voidPerl_set_caret_X(pTHX) {    GV* tmpgv = gv_fetchpvs("/030", GV_ADD|GV_NOTQUAL, SVt_PV); /* $^X */    SV *const caret_x = GvSV(tmpgv);#if defined(OS2)    sv_setpv(caret_x, os2_execname(aTHX));#elif defined(USE_KERN_PROC_PATHNAME)    size_t size = 0;    int mib[4];    mib[0] = CTL_KERN;    mib[1] = KERN_PROC;    mib[2] = KERN_PROC_PATHNAME;    mib[3] = -1;    if (sysctl(mib, 4, NULL, &size, NULL, 0) == 0        && size > 0 && size < MAXPATHLEN * MAXPATHLEN) {        sv_grow(caret_x, size);        if (sysctl(mib, 4, SvPVX(caret_x), &size, NULL, 0) == 0            && size > 2) {            SvPOK_only(caret_x);            SvCUR_set(caret_x, size - 1);            SvTAINT(caret_x);            return;        }    }#elif defined(USE_NSGETEXECUTABLEPATH)    char buf[1];    uint32_t size = sizeof(buf);    _NSGetExecutablePath(buf, &size);    if (size < MAXPATHLEN * MAXPATHLEN) {        sv_grow(caret_x, size);        if (_NSGetExecutablePath(SvPVX(caret_x), &size) == 0) {            char *const tidied = realpath(SvPVX(caret_x), NULL);            if (tidied) {                sv_setpv(caret_x, tidied);                free(tidied);            } else {                SvPOK_only(caret_x);                SvCUR_set(caret_x, size);            }            return;        }    }#elif defined(HAS_PROCSELFEXE)    char buf[MAXPATHLEN];    SSize_t len = readlink(PROCSELFEXE_PATH, buf, sizeof(buf) - 1);    /* NOTE: if the length returned by readlink() is sizeof(buf) - 1,     * it is impossible to know whether the result was truncated. */    if (len != -1) {        buf[len] = '/0';    }    /* On Playstation2 Linux V1.0 (kernel 2.2.1) readlink(/proc/self/exe)       includes a spurious NUL which will cause $^X to fail in system       or backticks (this will prevent extensions from being built and       many tests from working). readlink is not meant to add a NUL.       Normal readlink works fine.    */    if (len > 0 && buf[len-1] == '/0') {        len--;    }    /* FreeBSD's implementation is acknowledged to be imperfect, sometimes       returning the text "unknown" from the readlink rather than the path       to the executable (or returning an error from the readlink). Any       valid path has a '/' in it somewhere, so use that to validate the       result. See http://www.freebsd.org/cgi/query-pr.cgi?pr=35703    */    if (len > 0 && memchr(buf, '/', len)) {        sv_setpvn(caret_x, buf, len);        return;    }#elif defined(WIN32)    char *ansi;    WCHAR widename[MAX_PATH];    GetModuleFileNameW(NULL, widename, sizeof(widename)/sizeof(WCHAR));    ansi = win32_ansipath(widename);    sv_setpv(caret_x, ansi);    win32_free(ansi);    return;#else    /* Fallback to this:  */    sv_setpv(caret_x, PL_origargv[0]);#endif}
开发者ID:rurban,项目名称:perl,代码行数:88,


示例5: main

int main(int argc, char* argv[]) {#ifdef _WIN32	wchar_t exepath[MAX_PATH];	GetModuleFileNameW(NULL, exepath, MAX_PATH);	wchar_t* p = wcsrchr(exepath, '//');	*p = '/0';	SetCurrentDirectoryW(exepath);#endif //_WIN32#ifdef _WIN32	WORD wVersionRequested;	WSADATA wsaData;	wVersionRequested = MAKEWORD(2, 2);	WSAStartup(wVersionRequested, &wsaData);	evthread_use_windows_threads();#else	evthread_use_pthreads();#endif //_WIN32	ygo::Game _game;	ygo::mainGame = &_game;	if(!ygo::mainGame->Initialize())		return 0;	bool keep_on_return = false;	for(int i = 1; i < argc; ++i) {		if(argv[i][0] == '-' && argv[i][1] == 'e') {			char param[128];			GetParameter(param, &argv[i][2]);			ygo::dataManager.LoadDB(param);		}		if(!strcmp(argv[i], "-e")) { // extra database			++i;			char param[128];			GetParameter(param, &argv[i][0]);			ygo::dataManager.LoadDB(param);			continue;		} else if(!strcmp(argv[i], "-n")) { // nickName			++i;			wchar_t param[128];			GetParameterW(param, &argv[i][0]);			ygo::mainGame->ebNickName->setText(param);			continue;		} else if(!strcmp(argv[i], "-h")) { // Host address			++i;			wchar_t param[128];			GetParameterW(param, &argv[i][0]);			ygo::mainGame->ebJoinHost->setText(param);			continue;		} else if(!strcmp(argv[i], "-p")) { // host Port			++i;			wchar_t param[128];			GetParameterW(param, &argv[i][0]);			ygo::mainGame->ebJoinPort->setText(param);			continue;		} else if(!strcmp(argv[i], "-w")) { // host passWord			++i;			wchar_t param[128];			GetParameterW(param, &argv[i][0]);			ygo::mainGame->ebJoinPass->setText(param);			continue;		} else if(!strcmp(argv[i], "-k")) { // Keep on return			exit_on_return = false;			keep_on_return = true;		} else if(!strcmp(argv[i], "-j")) { // Join host			exit_on_return = !keep_on_return;			ClickButton(ygo::mainGame->btnLanMode);			ClickButton(ygo::mainGame->btnJoinHost);			break;		} else if(!strcmp(argv[i], "-d")) { // Deck			exit_on_return = !keep_on_return;			if(i < argc) {				open_file = true;				GetParameterW(open_file_name, &argv[i + 1][0]);			}			ClickButton(ygo::mainGame->btnDeckEdit);			break;		} else if(!strcmp(argv[i], "-r")) { // Replay			exit_on_return = !keep_on_return;			if(i < argc) {				open_file = true;				GetParameterW(open_file_name, &argv[i + 1][0]);			}			ClickButton(ygo::mainGame->btnReplayMode);			if(open_file)				ClickButton(ygo::mainGame->btnLoadReplay);			break;		} else if(!strcmp(argv[i], "-s")) { // Single			exit_on_return = !keep_on_return;			if(i < argc) {				open_file = true;				GetParameterW(open_file_name, &argv[i + 1][0]);			}			ClickButton(ygo::mainGame->btnServerMode);			if(open_file)				ClickButton(ygo::mainGame->btnLoadSinglePlay);			break;		}	}	ygo::mainGame->MainLoop();#ifdef _WIN32	WSACleanup();//.........这里部分代码省略.........
开发者ID:HuangYuNan,项目名称:ygopro,代码行数:101,


示例6: set_windows_hook

/*********************************************************************** *		set_windows_hook * * Implementation of SetWindowsHookExA and SetWindowsHookExW. */static HHOOK set_windows_hook( INT id, HOOKPROC proc, HINSTANCE inst, DWORD tid, BOOL unicode ){    HHOOK handle = 0;    WCHAR module[MAX_PATH];    DWORD len;    if (!proc)    {        SetLastError( ERROR_INVALID_FILTER_PROC );        return 0;    }    if (tid)  /* thread-local hook */    {        if (id == WH_JOURNALRECORD ||            id == WH_JOURNALPLAYBACK ||            id == WH_KEYBOARD_LL ||            id == WH_MOUSE_LL ||            id == WH_SYSMSGFILTER)        {            /* these can only be global */            SetLastError( ERROR_INVALID_PARAMETER );            return 0;        }    }    else  /* system-global hook */    {        if (id == WH_KEYBOARD_LL || id == WH_MOUSE_LL) inst = 0;        else if (!inst)        {            SetLastError( ERROR_HOOK_NEEDS_HMOD );            return 0;        }    }    if (inst && (!(len = GetModuleFileNameW( inst, module, MAX_PATH )) || len >= MAX_PATH))    {        SetLastError( ERROR_INVALID_PARAMETER );        return 0;    }    SERVER_START_REQ( set_hook )    {        req->id        = id;        req->pid       = 0;        req->tid       = tid;        req->event_min = EVENT_MIN;        req->event_max = EVENT_MAX;        req->flags     = WINEVENT_INCONTEXT;        req->unicode   = unicode;        if (inst) /* make proc relative to the module base */        {            req->proc = wine_server_client_ptr( (void *)((char *)proc - (char *)inst) );            wine_server_add_data( req, module, strlenW(module) * sizeof(WCHAR) );        }        else req->proc = wine_server_client_ptr( proc );        if (!wine_server_call_err( req ))        {            handle = wine_server_ptr_handle( reply->handle );            get_user_thread_info()->active_hooks = reply->active_hooks;        }    }    SERVER_END_REQ;    TRACE( "%s %p %x -> %p/n", hook_names[id-WH_MINHOOK], proc, tid, handle );    return handle;}
开发者ID:VOID001,项目名称:wine-void,代码行数:73,


示例7: DbgAllocReport

//.........这里部分代码省略.........                 (unsigned)(g_TopAllocators[i].m_TotalBytes / g_TopAllocators[i].m_Count)));        }    }    // Print out info for all leaked packets.    if (g_DetectLeaks) {        DbgAllocHeader *h = g_AllocListFirst;        int fHaveLeaks = (h!=NULL);        if (h) {            // Tell the Log we had memory leaks            LOG((LF_DBGALLOC, LL_ALWAYS, "/n"));            LOG((LF_DBGALLOC, LL_ALWAYS, "Detected memory leaks!/n"));            LOG((LF_DBGALLOC, LL_ALWAYS, "Leaked packets :/n"));            // Tell the console we had memory leaks            if (fDoPrintf)            {                printf("Detected memory leaks!/n");                if (pString != NULL)                    printf("%s/n", pString);                                    printf("Leaked packets :/n");            }        }        while (h) {            char buffer1[132];            char buffer2[32];            sprintf(buffer1, "#%u %08X:%u ", h->m_SN, CDA_HEADER_TO_DATA(h), h->m_Length);            unsigned i;            for (i = 0; i < 16; i++) {                if (i < h->m_Length)                    sprintf(buffer2, "%02X", (BYTE)CDA_DATA(h, i));                else                    strcpy(buffer2, "  ");                if ((i % 4) == 3)                    strcat(buffer2, " ");                strcat(buffer1, buffer2);            }            for (i = 0; i < min(16, h->m_Length); i++) {                sprintf(buffer2, "%c", (CDA_DATA(h, i) < 32) || (CDA_DATA(h, i) > 127) ? '.' : CDA_DATA(h, i));                strcat(buffer1, buffer2);            }            LOG((LF_DBGALLOC, LL_ALWAYS, "%s/n", buffer1));            if (fDoPrintf)                printf("%s/n", buffer1);                        if (g_CallStackDepth == 1) {                LOG((LF_DBGALLOC, LL_ALWAYS, " Allocated at %08X %s/n",                     CDA_ALLOC_STACK(h, 0), DbgSymbolize(CDA_ALLOC_STACK(h, 0))));            if (fDoPrintf)                printf(" Allocated at %08X %s/n",                     CDA_ALLOC_STACK(h, 0), DbgSymbolize(CDA_ALLOC_STACK(h, 0)));            } else {                LOG((LF_DBGALLOC, LL_ALWAYS, " Allocation call stack:/n"));                if (fDoPrintf)                    printf(" Allocation call stack:/n");                for (unsigned i = 0; i < g_CallStackDepth; i++) {                    if (CDA_ALLOC_STACK(h, i) == NULL)                        break;                    LOG((LF_DBGALLOC, LL_ALWAYS, "  %08X %s/n",                         CDA_ALLOC_STACK(h, i), DbgSymbolize(CDA_ALLOC_STACK(h, i))));                    if (fDoPrintf)                        printf("  %08X %s/n",                             CDA_ALLOC_STACK(h, i), DbgSymbolize(CDA_ALLOC_STACK(h, i)));                }            }            wchar_t buf[256];            GetModuleFileNameW(h->m_hmod, buf, 256);            LOG((LF_DBGALLOC, LL_ALWAYS, " Base, name: %08X %S/n/n", h->m_hmod, buf));            if (fDoPrintf)                printf(" Base, name: %08X %S/n/n", h->m_hmod, buf);            h = h->m_Next;        }        if (fDoPrintf)            fflush(stdout);        if (fHaveLeaks && g_AssertOnLeaks)            _ASSERTE(!"Detected memory leaks!");    }    if (g_LogStats || g_LogDist || g_DetectLeaks || g_UsageByAllocator) {        LOG((LF_DBGALLOC, LL_ALWAYS, "/n"));        LOG((LF_DBGALLOC, LL_ALWAYS, "------------------------------/n"));    }    if (fDone)    {        DbgUnloadSymbols();        DeleteCriticalSection(&g_AllocMutex);        // We won't be doing any more of our debug allocation stuff        g_DbgEnabled=0;    }}
开发者ID:ArildF,项目名称:masters,代码行数:101,


示例8: RuntimeHost_GetDefaultDomain

static HRESULT RuntimeHost_GetDefaultDomain(RuntimeHost *This, const WCHAR *config_path, MonoDomain **result){    WCHAR config_dir[MAX_PATH];    WCHAR base_dir[MAX_PATH];    char *base_dirA, *config_pathA, *slash;    HRESULT res=S_OK;    EnterCriticalSection(&This->lock);    if (This->default_domain) goto end;    res = RuntimeHost_AddDefaultDomain(This, &This->default_domain);    if (!config_path)    {        DWORD len = ARRAY_SIZE(config_dir);        static const WCHAR machine_configW[] = {'//','C','O','N','F','I','G','//','m','a','c','h','i','n','e','.','c','o','n','f','i','g',0};        res = ICLRRuntimeInfo_GetRuntimeDirectory(&This->version->ICLRRuntimeInfo_iface,                config_dir, &len);        if (FAILED(res))            goto end;        lstrcatW(config_dir, machine_configW);        config_path = config_dir;    }    config_pathA = WtoA(config_path);    if (!config_pathA)    {        res = E_OUTOFMEMORY;        goto end;    }    GetModuleFileNameW(NULL, base_dir, ARRAY_SIZE(base_dir));    base_dirA = WtoA(base_dir);    if (!base_dirA)    {        HeapFree(GetProcessHeap(), 0, config_pathA);        res = E_OUTOFMEMORY;        goto end;    }    slash = strrchr(base_dirA, '//');    if (slash)        *(slash + 1) = 0;    TRACE("setting base_dir: %s, config_path: %s/n", base_dirA, config_pathA);    mono_domain_set_config(This->default_domain, base_dirA, config_pathA);    HeapFree(GetProcessHeap(), 0, config_pathA);    HeapFree(GetProcessHeap(), 0, base_dirA);end:    *result = This->default_domain;    LeaveCriticalSection(&This->lock);    return res;}
开发者ID:iXit,项目名称:wine,代码行数:62,


示例9: ATLTRACE

HRESULT CCodeCoverage::OpenCoverInitialise(IUnknown *pICorProfilerInfoUnk){	ATLTRACE(_T("::OpenCoverInitialise"));    OLECHAR szGuid[40]={0};    int nCount = ::StringFromGUID2(CLSID_CodeCoverage, szGuid, 40);    RELTRACE(L"    ::Initialize(...) => CLSID == %s", szGuid);    //::OutputDebugStringW(szGuid);    WCHAR szExeName[MAX_PATH];    GetModuleFileNameW(NULL, szExeName, MAX_PATH);    RELTRACE(L"    ::Initialize(...) => EXE = %s", szExeName);    WCHAR szModuleName[MAX_PATH];    GetModuleFileNameW(_AtlModule.m_hModule, szModuleName, MAX_PATH);    RELTRACE(L"    ::Initialize(...) => PROFILER = %s", szModuleName);    //::OutputDebugStringW(szModuleName);    if (g_pProfiler!=NULL)         RELTRACE(_T("Another instance of the profiler is running under this process..."));    m_profilerInfo = pICorProfilerInfoUnk;    if (m_profilerInfo != NULL) ATLTRACE(_T("    ::Initialize (m_profilerInfo OK)"));    if (m_profilerInfo == NULL) return E_FAIL;    m_profilerInfo2 = pICorProfilerInfoUnk;    if (m_profilerInfo2 != NULL) ATLTRACE(_T("    ::Initialize (m_profilerInfo2 OK)"));    if (m_profilerInfo2 == NULL) return E_FAIL;    m_profilerInfo3 = pICorProfilerInfoUnk;#ifndef _TOOLSETV71    m_profilerInfo4 = pICorProfilerInfoUnk;#endif    ZeroMemory(&m_runtimeVersion, sizeof(m_runtimeVersion));    if (m_profilerInfo3 != NULL)     {        ATLTRACE(_T("    ::Initialize (m_profilerInfo3 OK)"));                ZeroMemory(&m_runtimeVersion, sizeof(m_runtimeVersion));        m_profilerInfo3->GetRuntimeInformation(NULL, &m_runtimeType,             &m_runtimeVersion.usMajorVersion,             &m_runtimeVersion.usMinorVersion,             &m_runtimeVersion.usBuildNumber,             &m_runtimeVersion.usRevisionNumber, 0, NULL, NULL);         ATLTRACE(_T("    ::Initialize (Runtime %d)"), m_runtimeType);    }    TCHAR key[1024] = {0};    ::GetEnvironmentVariable(_T("OpenCover_Profiler_Key"), key, 1024);    RELTRACE(_T("    ::Initialize(...) => key = %s"), key);    TCHAR ns[1024] = {0};    ::GetEnvironmentVariable(_T("OpenCover_Profiler_Namespace"), ns, 1024);    ATLTRACE(_T("    ::Initialize(...) => ns = %s"), ns);    TCHAR instrumentation[1024] = {0};    ::GetEnvironmentVariable(_T("OpenCover_Profiler_Instrumentation"), instrumentation, 1024);    ATLTRACE(_T("    ::Initialize(...) => instrumentation = %s"), instrumentation);    TCHAR threshold[1024] = {0};    ::GetEnvironmentVariable(_T("OpenCover_Profiler_Threshold"), threshold, 1024);    m_threshold = _tcstoul(threshold, NULL, 10);    ATLTRACE(_T("    ::Initialize(...) => threshold = %ul"), m_threshold);    TCHAR tracebyTest[1024] = {0};    ::GetEnvironmentVariable(_T("OpenCover_Profiler_TraceByTest"), tracebyTest, 1024);    m_tracingEnabled = _tcslen(tracebyTest) != 0;	ATLTRACE(_T("    ::Initialize(...) => tracingEnabled = %s (%s)"), m_tracingEnabled ? _T("true") : _T("false"), tracebyTest);    m_useOldStyle = (tstring(instrumentation) == _T("oldSchool"));    if (!m_host.Initialise(key, ns))    {        RELTRACE(_T("    ::Initialize => Failed to initialise the profiler communications -> GetLastError() => %d"), ::GetLastError());        return E_FAIL;    }    OpenCoverSupportInitialize(pICorProfilerInfoUnk);	if (m_chainedProfiler == NULL){		DWORD dwMask = AppendProfilerEventMask(0); 		COM_FAIL_MSG_RETURN_ERROR(m_profilerInfo2->SetEventMask(dwMask),			_T("    ::Initialize(...) => SetEventMask => 0x%X"));	}    if(m_profilerInfo3 != NULL)    {        COM_FAIL_MSG_RETURN_ERROR(m_profilerInfo3->SetFunctionIDMapper2(FunctionMapper2, this),             _T("    ::Initialize(...) => SetFunctionIDMapper2 => 0x%X"));    }    else    {        COM_FAIL_MSG_RETURN_ERROR(m_profilerInfo2->SetFunctionIDMapper(FunctionMapper),             _T("    ::Initialize(...) => SetFunctionIDMapper => 0x%X"));    }    g_pProfiler = this;#ifndef _TOOLSETV71//.........这里部分代码省略.........
开发者ID:vaidhy,项目名称:opencover,代码行数:101,


示例10: GetCurrentDir

// Returns the current directorystd::string GetCurrentDir(){    // Get the current working directory (getcwd uses malloc)#ifdef _WIN32    wchar_t *dir;    if (!(dir = _wgetcwd(nullptr, 0))) {#else    char *dir;    if (!(dir = getcwd(nullptr, 0))) {#endif        LOG_ERROR(Common_Filesystem, "GetCurrentDirectory failed: %s",                GetLastErrorMsg());        return nullptr;    }#ifdef _WIN32    std::string strDir = Common::UTF16ToUTF8(dir);#else    std::string strDir = dir;#endif    free(dir);    return strDir;}// Sets the current directory to the given directorybool SetCurrentDir(const std::string &directory){#ifdef _WIN32    return _wchdir(Common::UTF8ToUTF16W(directory).c_str()) == 0;#else    return chdir(directory.c_str()) == 0;#endif}#if defined(__APPLE__)std::string GetBundleDirectory(){    CFURLRef BundleRef;    char AppBundlePath[MAXPATHLEN];    // Get the main bundle for the app    BundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());    CFStringRef BundlePath = CFURLCopyFileSystemPath(BundleRef, kCFURLPOSIXPathStyle);    CFStringGetFileSystemRepresentation(BundlePath, AppBundlePath, sizeof(AppBundlePath));    CFRelease(BundleRef);    CFRelease(BundlePath);    return AppBundlePath;}#endif#ifdef _WIN32std::string& GetExeDirectory(){    static std::string exe_path;    if (exe_path.empty())    {        wchar_t wchar_exe_path[2048];        GetModuleFileNameW(nullptr, wchar_exe_path, 2048);        exe_path = Common::UTF16ToUTF8(wchar_exe_path);        exe_path = exe_path.substr(0, exe_path.find_last_of('//'));    }    return exe_path;}#else/** * @return The user’s home directory on POSIX systems */static const std::string& GetHomeDirectory() {    static std::string home_path;    if (home_path.empty()) {        const char* envvar = getenv("HOME");        if (envvar) {            home_path = envvar;        } else {            auto pw = getpwuid(getuid());            ASSERT_MSG(pw, "$HOME isn’t defined, and the current user can’t be found in /etc/passwd.");            home_path = pw->pw_dir;        }    }    return home_path;}/** * Follows the XDG Base Directory Specification to get a directory path * @param envvar The XDG environment variable to get the value from * @return The directory path * @sa http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html */static const std::string GetUserDirectory(const std::string& envvar) {    const char* directory = getenv(envvar.c_str());    std::string user_dir;    if (directory) {        user_dir = directory;    } else {        std::string subdirectory;        if (envvar == "XDG_DATA_HOME")            subdirectory = DIR_SEP ".local" DIR_SEP "share";        else if (envvar == "XDG_CONFIG_HOME")            subdirectory = DIR_SEP ".config";//.........这里部分代码省略.........
开发者ID:Gabrielbeck,项目名称:citra,代码行数:101,


示例11: fill_pathname_application_path

void fill_pathname_application_path(char *s, size_t len){   size_t i;#ifdef __APPLE__  CFBundleRef bundle = CFBundleGetMainBundle();#endif#ifdef _WIN32   DWORD ret;   wchar_t wstr[PATH_MAX_LENGTH] = {0};#endif#ifdef __HAIKU__   image_info info;   int32_t cookie = 0;#endif   (void)i;   if (!len)      return;#ifdef _WIN32#ifdef LEGACY_WIN32   ret    = GetModuleFileNameA(GetModuleHandle(NULL), s, len);#else   ret    = GetModuleFileNameW(GetModuleHandle(NULL), wstr, ARRAY_SIZE(wstr));   if (*wstr)   {      char *str = utf16_to_utf8_string_alloc(wstr);      if (str)      {         strlcpy(s, str, len);         free(str);      }   }#endif   s[ret] = '/0';#elif defined(__APPLE__)   if (bundle)   {      CFURLRef bundle_url = CFBundleCopyBundleURL(bundle);      CFStringRef bundle_path = CFURLCopyPath(bundle_url);      CFStringGetCString(bundle_path, s, len, kCFStringEncodingUTF8);      CFRelease(bundle_path);      CFRelease(bundle_url);      retro_assert(strlcat(s, "nobin", len) < len);      return;   }#elif defined(__HAIKU__)   while (get_next_image_info(0, &cookie, &info) == B_OK)   {      if (info.type == B_APP_IMAGE)      {         strlcpy(s, info.name, len);         return;      }   }#elif defined(__QNX__)   char *buff = malloc(len);   if(_cmdname(buff))      strlcpy(s, buff, len);   free(buff);#else   {      pid_t pid;      static const char *exts[] = { "exe", "file", "path/a.out" };      char link_path[255];      link_path[0] = *s = '/0';      pid       = getpid();      /* Linux, BSD and Solaris paths. Not standardized. */      for (i = 0; i < ARRAY_SIZE(exts); i++)      {         ssize_t ret;         snprintf(link_path, sizeof(link_path), "/proc/%u/%s",               (unsigned)pid, exts[i]);         ret = readlink(link_path, s, len - 1);         if (ret >= 0)         {            s[ret] = '/0';            return;         }      }   }#endif}
开发者ID:gouchi,项目名称:RetroArch,代码行数:92,


示例12: DllMain

/// <summary>/// Main entry point for the dll./// </summary>/// <param name="hModule">Handle to the DLL module.</param>/// <param name="ul_reason_for_call">Reason for calling function.</param>/// <param name="lpReserved">Reserved.</param>/// <returns>TRUE if it succeeds or FALSE if initialization fails.</returns>BOOL APIENTRY DllMain( HANDLE hModule,                       DWORD  ul_reason_for_call,                       LPVOID lpReserved                     ){    DWORD nchars;    wchar_t* last;    BOOL ret;    ret = TRUE;    switch (ul_reason_for_call)    {        case DLL_PROCESS_ATTACH:        {            // hModule - The value is the base address of the DLL.            // The HINSTANCE of a DLL is the same as the HMODULE of the DLL,            // so hinstDLL can be used in calls to functions that require a module handle.            nchars = GetModuleFileNameW ((HINSTANCE)hModule, module, MAX_PATH);            if (0 == nchars)                ret = FALSE;            else            {                // scan the string for the last occurrence of a slash                wcscpy (home_dir, module);                last = wcsrchr (home_dir, L'//');                if (NULL == last)                    ret = FALSE;                else                {                    last++; // move past the slash                    *last = L'/0'; // null terminate it there                    wcscpy (com_dir, home_dir);                    wcscat (com_dir, L"com//");                }#ifdef _DEBUG                // Look for a "debug.images" file in $HOME for debug message control.				char* cmodule;				wide_to_multibyte(cmodule, module);                char * argv[] = { cmodule, 0 };                int argc = 1;                debug_init(&argc, argv);#endif            }            tlsIndex = TlsAlloc();            ut_thread_mutex_init();            break;        }        case DLL_THREAD_ATTACH:            break;        case DLL_THREAD_DETACH:            break;        case DLL_PROCESS_DETACH:            TlsFree(tlsIndex);            ut_thread_mutex_destroy();            break;    }    return (ret);}
开发者ID:johanvdw,项目名称:fdo-git-mirror,代码行数:77,


示例13: memset

BOOL CYYManager::InitFactory(){	WCHAR wzSelfPath[MAX_PATH]; 	memset( wzSelfPath, 0, sizeof(wzSelfPath) );	GetModuleFileNameW( NULL, wzSelfPath, sizeof(wzSelfPath) );	LPWSTR lpInsertPos = wcsrchr( wzSelfPath, L'//' );	*lpInsertPos = L'/0';	lstrcatW( wzSelfPath, L"//pipFactory.dll" );	m_hFactory = LoadLibraryW( wzSelfPath );	if( m_hFactory == NULL ) return FALSE;	m_pfnInitInterface = (PFN_INITYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_InitInterface" );	if( m_pfnInitInterface == NULL ) return FALSE;	m_pfnGetInterface = (PFN_GETYYINTERFACE)GetProcAddress( m_hFactory, "YYPIP_GetInterface" );	if( m_pfnGetInterface == NULL ) return FALSE;	//call factory init func	if( m_pfnInitInterface() == -1 ) return FALSE;	/////////////////////////////////////////////////////////////////////////	//all game must be call this func to show yy window	m_pfnRunService = (PFN_RUNSERVICE)m_pfnGetInterface( "YYPIP_RunService" );	if( m_pfnRunService == NULL ) return FALSE;	m_pfnLoadInGame = (PFN_LOADINGAME)m_pfnGetInterface( "YYPIP_LoadInGame" );	if( m_pfnLoadInGame == NULL ) return FALSE;	m_pfnFreeGame = (PFN_FREEINGAME)m_pfnGetInterface( "YYPIP_FreeInGame" );	if( m_pfnFreeGame == NULL ) return FALSE;	m_pfnCheckClient = (PFN_CHECKCLIENT)m_pfnGetInterface( "YYPIP_CheckYYClient" );	if( m_pfnCheckClient == NULL ) return FALSE;	m_pfnIsPipSuccess = (PFN_ISPIPSUCCESS)m_pfnGetInterface( "YYPIP_IsPipRunSuccess" );	if( m_pfnIsPipSuccess == NULL ) return FALSE;	/////////////////////////////////////////////////////////////////////////	//sometimes call this func to show yy window	m_pfnMouseInput = (PFN_MOUSEINPUT)m_pfnGetInterface( "YYPIP_MouseInput" );	if( m_pfnMouseInput == NULL ) return FALSE;	m_pfnSetMainWnd = (PFN_SETMAINWND)m_pfnGetInterface( "YYPIP_SetMainWnd" );	if( m_pfnSetMainWnd == NULL ) return FALSE;	m_pfnCreateUI = (PFN_CREATEUI)m_pfnGetInterface( "YYPIP_CreateUI" );	if( m_pfnCreateUI == NULL ) return FALSE;	m_pfnDestoryUI = (PFN_DESTORYUI)m_pfnGetInterface( "YYPIP_DestoryUI" );	if( m_pfnDestoryUI == NULL ) return FALSE;	m_pfnRenderGUI = (PFN_RENDERGUI)m_pfnGetInterface( "YYPIP_RenderGUI" );	if( m_pfnRenderGUI == NULL ) return FALSE;	m_pfnGameWndMsg = (PFN_GAMEWNDMSG)m_pfnGetInterface( "YYPIP_GameWndMessage" );	if( m_pfnGameWndMsg == NULL ) return FALSE;	/////////////////////////////////////////////////////////////////////////	//game used yy voice channel	m_pfnJoinChannel = (PFN_JOINCHANNEL)m_pfnGetInterface( "YYPIP_JoinChannel" );	if( m_pfnJoinChannel == NULL ) return FALSE;	m_pfnSetTeamAdmin = (PFN_SETTEAMADMIN)m_pfnGetInterface( "YYPIP_SetTeamAdmin" );	if( m_pfnSetTeamAdmin == NULL ) return FALSE;	m_pfnSetUserName = (PFN_SETUSERNAME)m_pfnGetInterface( "YYPIP_SetUserName" );	if( m_pfnSetUserName == NULL ) return FALSE;	m_pfnJoinTeam = (PFN_JOINTEAM)m_pfnGetInterface( "YYPIP_JoinTeam" );	if( m_pfnJoinTeam == NULL ) return FALSE;	m_pfnSetTeamDevice = (PFN_SETTEAMDEVICE)m_pfnGetInterface( "YYPIP_SetTeamDevice" );	if( m_pfnSetTeamDevice == NULL ) return FALSE;	m_pfnSetTeamVoice = (PFN_SETTEAMVOICE)m_pfnGetInterface( "YYPIP_SetTeamVoice" );	if( m_pfnSetTeamVoice == NULL ) return FALSE;	m_pfnLockTeamVoice = (PFN_LOCKTEAMVOICE)m_pfnGetInterface( "YYPIP_LockTeamVoice" );	if( m_pfnLockTeamVoice == NULL ) return FALSE;	/////////////////////////////////////////////////////////////////////////	//game to channel yy voice window	m_pfnGetPipShow = (PFN_GETPIPSHOW)m_pfnGetInterface( "YYPIP_GetPipShow" );	if( m_pfnGetPipShow == NULL ) return FALSE;	m_pfnSetPipShow = (PFN_SETPIPSHOW)m_pfnGetInterface( "YYPIP_SetPipShow" );	if( m_pfnSetPipShow == NULL ) return FALSE;	m_pfnSetMsgShow = (PFN_SETMSGSHOW)m_pfnGetInterface( "YYPIP_SetMsgShow" );	if( m_pfnSetMsgShow == NULL ) return FALSE;	m_pfnMouseShow = (PFN_SETMOUSESHOW)m_pfnGetInterface( "YYPIP_SetMouseShow" );	if( m_pfnMouseShow == NULL ) return FALSE;	m_pfnLockWnd = (PFN_LOCKWINDOW)m_pfnGetInterface( "YYPIP_LockWindow" );	if( m_pfnLockWnd == NULL ) return FALSE;	m_pfnMoveWnd = (PFN_MOVEWINDOW)m_pfnGetInterface( "YYPIP_MoveWindow" );//.........这里部分代码省略.........
开发者ID:LaoZhongGu,项目名称:RushGame,代码行数:101,


示例14: DllRegisterServer

//------------------------------------------------------------------------------// DllRegisterServer//------------------------------------------------------------------------------STDAPI DllRegisterServer(){	HKEY    hKey = NULL;	HMODULE hModule = NULL;	HRESULT hr = S_OK;	LONG    lResult = ERROR_SUCCESS;	WCHAR   szFilename[MAX_PATH] = { 0 };	WCHAR   szKey[MAX_PATH] = { 0 };	WCHAR   szCLSID[OLEGUID_LEN_CCH] = { 0 };	//	// Grab the fully qualified path to this dll	//	hModule = GetModuleHandleW(L"PrinterServiceFuncDiscovery");	if (NULL == hModule)	{		hr = HRESULT_FROM_WIN32(GetLastError());	}	else if (0 == GetModuleFileNameW(hModule, szFilename, ARRAYSIZE(szFilename)))	{		hr = HRESULT_FROM_WIN32(GetLastError());	}	//	// Register the COM object in the registry	//	if (S_OK == hr &&		0 == StringFromGUID2(CLSID_SsysPrinterSvcProxy, szCLSID, ARRAYSIZE(szCLSID)))	{		hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);	}	if (S_OK == hr)	{		hr = StringCchPrintfW(szKey, ARRAYSIZE(szKey), L"CLSID//%s", szCLSID);	}	if (S_OK == hr)	{		lResult = RegCreateKeyExW(			HKEY_CLASSES_ROOT,			szKey,			0,			NULL,			REG_OPTION_NON_VOLATILE,			KEY_SET_VALUE,			NULL,			&hKey,			NULL			);		hr = HRESULT_FROM_WIN32(lResult);	}	if (S_OK == hr)	{		lResult = RegSetValueExW(			hKey,			NULL,			0,			REG_SZ,			(BYTE*)OBJECT_NAME,			(static_cast<DWORD>(wcslen(OBJECT_NAME)) + 1)*sizeof(WCHAR)			);		hr = HRESULT_FROM_WIN32(lResult);	}	RegCloseKey(hKey);	if (S_OK == hr)	{		hr = StringCchPrintfW(			szKey,			ARRAYSIZE(szKey),			L"CLSID//%s//InProcServer32",			szCLSID			);	}	if (S_OK == hr)	{		lResult = RegCreateKeyExW(			HKEY_CLASSES_ROOT,			szKey,			0,			NULL,			REG_OPTION_NON_VOLATILE,			KEY_SET_VALUE,			NULL,			&hKey,			NULL			);		hr = HRESULT_FROM_WIN32(lResult);	}	if (S_OK == hr)	{		lResult = RegSetValueExW(			hKey,//.........这里部分代码省略.........
开发者ID:felihea,项目名称:stratasys,代码行数:101,


示例15: UpdateServiceDescription

/** * Updates the service description with what is stored in updater.ini * at the same path as the currently executing module binary. * * @param serviceHandle A handle to an opened service with  *                      SERVICE_CHANGE_CONFIG access right * @param TRUE on succcess.*/BOOLUpdateServiceDescription(SC_HANDLE serviceHandle){  WCHAR updaterINIPath[MAX_PATH + 1];  if (!GetModuleFileNameW(NULL, updaterINIPath,                           sizeof(updaterINIPath) /                          sizeof(updaterINIPath[0]))) {    LOG(("Could not obtain module filename when attempting to "         "modify service description. (%d)/n", GetLastError()));    return FALSE;  }  if (!PathRemoveFileSpecW(updaterINIPath)) {    LOG(("Could not remove file spec when attempting to "         "modify service description. (%d)/n", GetLastError()));    return FALSE;  }  if (!PathAppendSafe(updaterINIPath, L"updater.ini")) {    LOG(("Could not append updater.ini filename when attempting to "         "modify service description. (%d)/n", GetLastError()));    return FALSE;  }  if (GetFileAttributesW(updaterINIPath) == INVALID_FILE_ATTRIBUTES) {    LOG(("updater.ini file does not exist, will not modify "         "service description. (%d)/n", GetLastError()));    return FALSE;  }    MaintenanceServiceStringTable serviceStrings;  int rv = ReadMaintenanceServiceStrings(updaterINIPath, &serviceStrings);  if (rv != OK || !strlen(serviceStrings.serviceDescription)) {    LOG(("updater.ini file does not contain a maintenance "         "service description./n"));    return FALSE;  }  WCHAR serviceDescription[MAX_TEXT_LEN];  if (!MultiByteToWideChar(CP_UTF8, 0,                            serviceStrings.serviceDescription, -1,                           serviceDescription,                           sizeof(serviceDescription) /                            sizeof(serviceDescription[0]))) {    LOG(("Could not convert description to wide string format (%d)/n",          GetLastError()));    return FALSE;  }  SERVICE_DESCRIPTIONW descriptionConfig;  descriptionConfig.lpDescription = serviceDescription;  if (!ChangeServiceConfig2W(serviceHandle,                              SERVICE_CONFIG_DESCRIPTION,                              &descriptionConfig)) {    LOG(("Could not change service config (%d)/n", GetLastError()));    return FALSE;  }  LOG(("The service description was updated successfully./n"));  return TRUE;}
开发者ID:Type-of-Tool,项目名称:ExMail,代码行数:69,


示例16: IntegrityCheckModule

bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation){	std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC());	unsigned int macSize = mac->DigestSize();	SecByteBlock tempMac;	SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac;	actualMac.resize(macSize);	unsigned long tempLocation;	unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation;	macFileLocation = 0;	MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size())));//	MeterFilter verifier(new FileSink("c://dt.tmp"));	std::ifstream moduleStream;#ifdef CRYPTOPP_WIN32_AVAILABLE	HMODULE h;	{	char moduleFilenameBuf[MAX_PATH] = "";	if (moduleFilename == NULL)	{#if (_MSC_VER >= 1400 && !defined(_STLPORT_VERSION))	// ifstream doesn't support wide filename on other compilers		wchar_t wideModuleFilename[MAX_PATH];		if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0)		{			moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary);			h = GetModuleHandleW(wideModuleFilename);		}		else#endif		{			GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH);			moduleFilename = moduleFilenameBuf;		}	}#endif	if (moduleFilename != NULL)	{			moduleStream.open(moduleFilename, std::ios::in | std::ios::binary);#ifdef CRYPTOPP_WIN32_AVAILABLE			h = GetModuleHandleA(moduleFilename);			moduleFilename = NULL;	}#endif	}	if (!moduleStream)	{#ifdef CRYPTOPP_WIN32_AVAILABLE		OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading.");#endif		return false;	}	FileStore file(moduleStream);#ifdef CRYPTOPP_WIN32_AVAILABLE	// try to hash from memory first	const byte *memBase = (const byte *)h;	const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase;	const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew);	const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt);	DWORD nSections = phnt->FileHeader.NumberOfSections;	size_t currentFilePos = 0;	size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase;	size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum);	size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase;	size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]);	size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress;	size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size;	verifier.AddRangeToSkip(0, checksumPos, checksumSize);	verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize);	verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize);	while (nSections--)	{		switch (phs->Characteristics)		{		default:			break;		case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ:		case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ:			unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize);			const byte *sectionMemStart = memBase + phs->VirtualAddress;			unsigned int sectionFileStart = phs->PointerToRawData;			size_t subSectionStart = 0, nextSubSectionStart;			do			{				const byte *subSectionMemStart = sectionMemStart + subSectionStart;				size_t subSectionFileStart = sectionFileStart + subSectionStart;				size_t subSectionSize = sectionSize - subSectionStart;				nextSubSectionStart = 0;				unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT};				for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++)				{//.........这里部分代码省略.........
开发者ID:Dangr8,项目名称:Cities3D,代码行数:101,


示例17: SvcInstall

/** * Installs or upgrades the SVC_NAME service. * If an existing service is already installed, we replace it with the * currently running process. * * @param  action The action to perform. * @return TRUE if the service was installed/upgraded */BOOLSvcInstall(SvcInstallAction action){  // Get a handle to the local computer SCM database with full access rights.  nsAutoServiceHandle schSCManager(OpenSCManager(NULL, NULL,                                                  SC_MANAGER_ALL_ACCESS));  if (!schSCManager) {    LOG(("Could not open service manager.  (%d)/n", GetLastError()));    return FALSE;  }  WCHAR newServiceBinaryPath[MAX_PATH + 1];  if (!GetModuleFileNameW(NULL, newServiceBinaryPath,                           sizeof(newServiceBinaryPath) /                           sizeof(newServiceBinaryPath[0]))) {    LOG(("Could not obtain module filename when attempting to "         "install service. (%d)/n",         GetLastError()));    return FALSE;  }  // Check if we already have the service installed.  nsAutoServiceHandle schService(OpenServiceW(schSCManager,                                               SVC_NAME,                                               SERVICE_ALL_ACCESS));  DWORD lastError = GetLastError();  if (!schService && ERROR_SERVICE_DOES_NOT_EXIST != lastError) {    // The service exists but we couldn't open it    LOG(("Could not open service.  (%d)/n", GetLastError()));    return FALSE;  }    if (schService) {    // The service exists but it may not have the correct permissions.    // This could happen if the permissions were not set correctly originally    // or have been changed after the installation.  This will reset the     // permissions back to allow limited user accounts.    if (!SetUserAccessServiceDACL(schService)) {      LOG(("Could not reset security ACE on service handle. It might not be "           "possible to start the service. This error should never "           "happen.  (%d)/n", GetLastError()));    }    // The service exists and we opened it    DWORD bytesNeeded;    if (!QueryServiceConfigW(schService, NULL, 0, &bytesNeeded) &&         GetLastError() != ERROR_INSUFFICIENT_BUFFER) {      LOG(("Could not determine buffer size for query service config.  (%d)/n",            GetLastError()));      return FALSE;    }    // Get the service config information, in particular we want the binary     // path of the service.    nsAutoArrayPtr<char> serviceConfigBuffer = new char[bytesNeeded];    if (!QueryServiceConfigW(schService,         reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get()),         bytesNeeded, &bytesNeeded)) {      LOG(("Could open service but could not query service config.  (%d)/n",            GetLastError()));      return FALSE;    }    QUERY_SERVICE_CONFIGW &serviceConfig =       *reinterpret_cast<QUERY_SERVICE_CONFIGW*>(serviceConfigBuffer.get());    // Check if we need to fix the service path    BOOL servicePathWasWrong;    static BOOL alreadyCheckedFixServicePath = FALSE;    if (!alreadyCheckedFixServicePath) {      if (!FixServicePath(schService, serviceConfig.lpBinaryPathName,                          servicePathWasWrong)) {        LOG(("Could not fix service path. This should never happen. (%d)/n",              GetLastError()));        // True is returned because the service is pointing to        // maintenanceservice_tmp.exe so it actually was upgraded to the        // newest installed service.        return TRUE;      } else if (servicePathWasWrong) {        // Now that the path is fixed we should re-attempt the install.        // This current process' image path is maintenanceservice_tmp.exe.        // The service used to point to maintenanceservice_tmp.exe.        // The service was just fixed to point to maintenanceservice.exe.        // Re-attempting an install from scratch will work as normal.        alreadyCheckedFixServicePath = TRUE;        LOG(("Restarting install action: %d/n", action));        return SvcInstall(action);      }    }    // Ensure the service path is not quoted. We own this memory and know it to    // be large enough for the quoted path, so it is large enough for the    // unquoted path.  This function cannot fail.//.........这里部分代码省略.........
开发者ID:Type-of-Tool,项目名称:ExMail,代码行数:101,


示例18: WinMain

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){    RT_NOREF(hInstance, hPrevInstance, lpCmdLine, nCmdShow);    /*     * Gather the parameters of the real installer program.     */    SetLastError(NO_ERROR);    WCHAR wszCurDir[_MAX_PATH] = { 0 };    DWORD cchCurDir = GetCurrentDirectoryW(sizeof(wszCurDir), wszCurDir);    if (cchCurDir == 0 || cchCurDir >= sizeof(wszCurDir))    {        fwprintf(stderr, L"ERROR: GetCurrentDirectoryW failed: %u (ret %u)/n", GetLastError(), cchCurDir);        return 12;    }    SetLastError(NO_ERROR);    WCHAR wszModule[_MAX_PATH] = { 0 };    DWORD cchModule = GetModuleFileNameW(NULL, wszModule, sizeof(wszModule));    if (cchModule == 0 || cchModule >= sizeof(wszModule))    {        fwprintf(stderr, L"ERROR: GetModuleFileNameW failed: %u (ret %u)/n", GetLastError(), cchModule);        return 13;    }    /* Strip the extension off the module name and construct the arch specific       one of the real installer program. */    DWORD off = cchModule - 1;    while (   off > 0           && (   wszModule[off] != '/'               && wszModule[off] != '//'               && wszModule[off] != ':'))    {        if (wszModule[off] == '.')        {            wszModule[off] = '/0';            cchModule = off;            break;        }        off--;    }    WCHAR const  *pwszSuff = IsWow64() ? L"-amd64.exe" : L"-x86.exe";    size_t        cchSuff  = wcslen(pwszSuff);    if (cchSuff + cchModule >= sizeof(wszModule))    {        fwprintf(stderr, L"ERROR: Real installer name is too long (%u chars)/n", cchSuff + cchModule);        return 14;    }    wcscpy(&wszModule[cchModule], pwszSuff);    cchModule += cchSuff;    /* Replace the first argument of the argument list. */    PWCHAR  pwszNewCmdLine = NULL;    LPCWSTR pwszOrgCmdLine = GetCommandLineW();    if (pwszOrgCmdLine) /* Dunno if this can be NULL, but whatever. */    {        /* Skip the first argument in the original. */        /** @todo Is there some ISBLANK or ISSPACE macro/function in Win32 that we could         *        use here, if it's correct wrt. command line conventions? */        WCHAR wch;        while ((wch = *pwszOrgCmdLine) == L' ' || wch == L'/t')            pwszOrgCmdLine++;        if (wch == L'"')        {            pwszOrgCmdLine++;            while ((wch = *pwszOrgCmdLine) != L'/0')            {                pwszOrgCmdLine++;                if (wch == L'"')                    break;            }        }        else        {            while ((wch = *pwszOrgCmdLine) != L'/0')            {                pwszOrgCmdLine++;                if (wch == L' ' || wch == L'/t')                    break;            }        }        while ((wch = *pwszOrgCmdLine) == L' ' || wch == L'/t')            pwszOrgCmdLine++;        /* Join up "szModule" with the remainder of the original command line. */        size_t cchOrgCmdLine = wcslen(pwszOrgCmdLine);        size_t cchNewCmdLine = 1 + cchModule + 1 + 1 + cchOrgCmdLine + 1;        PWCHAR pwsz = pwszNewCmdLine = (PWCHAR)LocalAlloc(LPTR, cchNewCmdLine * sizeof(WCHAR));        if (!pwsz)        {            fwprintf(stderr, L"ERROR: Out of memory (%u bytes)/n", (unsigned)cchNewCmdLine);            return 15;        }        *pwsz++ = L'"';        wcscpy(pwsz, wszModule);        pwsz += cchModule;        *pwsz++ = L'"';        if (cchOrgCmdLine)//.........这里部分代码省略.........
开发者ID:tonado,项目名称:vbox,代码行数:101,


示例19: main

int main(int argc, char *argv[]){#ifdef _UNIX  setlocale(LC_ALL,"");#endif#if defined(_EMX) && !defined(_DJGPP)  uni_init(0);#endif#if !defined(_SFX_RTL_) && !defined(_WIN_ALL)  setbuf(stdout,NULL);#endif#if !defined(SFX_MODULE) && defined(_EMX)  EnumConfigPaths(argv[0],-1);#endif  ErrHandler.SetSignalHandlers(true);  RARInitData();#ifdef SFX_MODULE  char ModuleNameA[NM];  wchar ModuleNameW[NM];#ifdef _WIN_ALL  GetModuleFileNameW(NULL,ModuleNameW,ASIZE(ModuleNameW));  WideToChar(ModuleNameW,ModuleNameA);#else  strcpy(ModuleNameA,argv[0]);  *ModuleNameW=0;#endif#endif#ifdef _WIN_ALL  SetErrorMode(SEM_NOALIGNMENTFAULTEXCEPT|SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX);#endif#if defined(_WIN_ALL) && !defined(SFX_MODULE) && !defined(SHELL_EXT)  bool ShutdownOnClose;#endif#ifdef ALLOW_EXCEPTIONS  try #endif  {      CommandData Cmd;#ifdef SFX_MODULE    strcpy(Cmd.Command,"X");    char *Switch=NULL;#ifdef _SFX_RTL_    char *CmdLine=GetCommandLineA();    if (CmdLine!=NULL && *CmdLine=='/"')      CmdLine=strchr(CmdLine+1,'/"');    if (CmdLine!=NULL && (CmdLine=strpbrk(CmdLine," /"))!=NULL)    {      while (IsSpace(*CmdLine))        CmdLine++;      Switch=CmdLine;    }#else    Switch=argc>1 ? argv[1]:NULL;#endif    if (Switch!=NULL && Cmd.IsSwitch(Switch[0]))    {      int UpperCmd=etoupper(Switch[1]);      switch(UpperCmd)      {        case 'T':        case 'V':          Cmd.Command[0]=UpperCmd;          break;        case '?':          Cmd.OutHelp();          break;      }    }    Cmd.AddArcName(ModuleNameA,ModuleNameW);    Cmd.ParseDone();#else // !SFX_MODULE    Cmd.PreprocessCommandLine(argc,argv);    if (!Cmd.ConfigDisabled)    {      Cmd.ReadConfig();      Cmd.ParseEnvVar();    }    Cmd.ParseCommandLine(argc,argv);#endif#if defined(_WIN_ALL) && !defined(SFX_MODULE) && !defined(SHELL_EXT)    ShutdownOnClose=Cmd.Shutdown;#endif    InitConsoleOptions(Cmd.MsgStream,Cmd.Sound);    InitLogOptions(Cmd.LogName);    ErrHandler.SetSilent(Cmd.AllYes || Cmd.MsgStream==MSG_NULL);//.........这里部分代码省略.........
开发者ID:Bootz,项目名称:nzbm,代码行数:101,


示例20: WinMain

int APIENTRY WinMain(HINSTANCE hInstance,                     HINSTANCE hPrevInstance,                     LPSTR     lpCmdLine,                     int       nCmdShow){    CRLog::setFileLogger( "crengine.log", true );    CRLog::setLogLevel( CRLog::LL_TRACE );    //InitCREngineLog("/root/abook/crengine/crlog.ini");#if 0	MMapTest();#endif    lString8 exe_dir;    char exe_fn[MAX_PATH+1];    GetModuleFileNameA( NULL, exe_fn, MAX_PATH );    lChar16 exe_fn16[MAX_PATH+1];    GetModuleFileNameW( NULL, exe_fn16, MAX_PATH );	lString16 exedir = LVExtractPath(lString16(exe_fn16));		lString8 exedir8 = UnicodeToUtf8( exedir );	CRMoFileTranslator * translator = new CRMoFileTranslator();	translator->openMoFile(exedir + L"/po/ru.mo");	CRI18NTranslator::setTranslator( translator );	lChar16 sysdir[MAX_PATH+1];	GetWindowsDirectoryW(sysdir, MAX_PATH);	lString16 fontdir( sysdir );	fontdir << L"//Fonts//";	lString8 fontdir8( UnicodeToUtf8(fontdir) );	lString8 fd = UnicodeToLocal(exedir);	lString16Collection fontDirs;	//fontDirs.add( fontdir );    fontDirs.add( exedir + L"fonts" );	InitCREngine( exe_fn, fontDirs );    const char * fontnames[] = {#if 1        "arial.ttf",        "ariali.ttf",        "arialb.ttf",        "arialbi.ttf",#endif        "arialn.ttf",        "arialni.ttf",        "arialnb.ttf",        "arialnbi.ttf",        "cour.ttf",        "couri.ttf",        "courbd.ttf",        "courbi.ttf",        "times.ttf",        "timesi.ttf",        "timesb.ttf",        "timesbi.ttf",        "comic.ttf",        "comicbd.ttf",        "verdana.ttf",        "verdanai.ttf",        "verdanab.ttf",        "verdanaz.ttf",        "bookos.ttf",        "bookosi.ttf",        "bookosb.ttf",        "bookosbi.ttf",#if 1        "calibri.ttf",        "calibrii.ttf",        "calibrib.ttf",        "calibriz.ttf",        "cambria.ttf",        "cambriai.ttf",        "cambriab.ttf",        "cambriaz.ttf",        "georgia.ttf",        "georgiai.ttf",        "georgiab.ttf",        "georgiaz.ttf",#endif        NULL    };    for ( int fi = 0; fontnames[fi]; fi++ ) {        fontMan->RegisterFont( fontdir8 + fontnames[fi] );    }    //LVCHECKPOINT("WinMain start");    if (!fontMan->GetFontCount())    {        //error        char str[1000];#if (USE_FREETYPE==1)        sprintf(str, "Cannot open font file(s) fonts/*.ttf /nCannot work without font/nPlace some TTF files to font// directory" );#else        sprintf(str, "Cannot open font file(s) font#.lbf /nCannot work without font/nUse FontConv utility to generate .lbf fonts from TTF" );#endif        MessageBoxA( NULL, str, "CR Engine :: Fb2Test -- fatal error!", MB_OK);        return 1;    }//.........这里部分代码省略.........
开发者ID:lunohod-1,项目名称:boox-opensource,代码行数:101,


示例21: defined

FileResolver::FileResolver() {	/* Try to detect the base path of the Mitsuba installation */	fs::path basePath;#if defined(__LINUX__)	Dl_info info;	dladdr((const void *) &dummySymbol, &info);	if (info.dli_fname) {		/* Try to detect a few default setups */		if (boost::starts_with(info.dli_fname, "/usr/lib") ||			boost::starts_with(info.dli_fname, "/lib")) {			basePath = fs::path("/usr/share/mitsuba");		} else if (boost::starts_with(info.dli_fname, "/usr/local/lib")) {			basePath = fs::path("/usr/local/share/mitsuba");		} else {			/* This is a locally-compiled repository */			basePath = fs::path(info.dli_fname).parent_path();		}	}#elif defined(__OSX__)	MTS_AUTORELEASE_BEGIN()	uint32_t imageCount = _dyld_image_count();	for (uint32_t i=0; i<imageCount; ++i) {		const char *imageName = _dyld_get_image_name(i);		if (boost::ends_with(imageName, "libmitsuba-core.dylib")) {			basePath = fs::canonical(imageName).parent_path().parent_path().parent_path();			break;		}	}	MTS_AUTORELEASE_END()	if (basePath.empty())		Log(EError, "Could not detect the executable path!");#elif defined(__WINDOWS__)	std::vector<WCHAR> lpFilename(MAX_PATH);	// Module handle to this DLL. If the function fails it sets handle to NULL.	// In that case GetModuleFileName will get the name of the executable which	// is acceptable soft-failure behavior.	HMODULE handle;	GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS	                 | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,          reinterpret_cast<LPCWSTR>(&dummySymbol), &handle);	// Try to get the path with the default MAX_PATH length (260 chars)	DWORD nSize = GetModuleFileNameW(handle, &lpFilename[0], MAX_PATH);	// Adjust the buffer size in case if was too short	while (nSize != 0 && nSize == lpFilename.size()) {		lpFilename.resize(nSize * 2);		nSize = GetModuleFileNameW(handle, &lpFilename[0],			static_cast<DWORD>(lpFilename.size()));	}	// There is an error if and only if the function returns 0	if (nSize != 0)		basePath = fs::path(lpFilename).parent_path();	else		Log(EError, "Could not detect the executable path! (%s)", lastErrorText().c_str());#endif	#if BOOST_VERSION >= 104800		m_paths.push_back(fs::canonical(basePath));	#else		m_paths.push_back(fs::absolute(basePath));	#endif	m_paths.push_back(fs::current_path());}
开发者ID:AdrianJohnston,项目名称:ShapeNetRender,代码行数:66,


示例22: wWinMain

int APIENTRY wWinMain(_In_ HINSTANCE hInstance,                      _In_opt_ HINSTANCE hPrevInstance,                      _In_ LPWSTR lpCmdLine,                      _In_ int nCmdShow){	// Attempt to mitigate http://textslashplain.com/2015/12/18/dll-hijacking-just-wont-die	HMODULE hKernel32 = LoadLibrary(L"kernel32.dll");	ATLASSERT(hKernel32 != NULL);	SetDefaultDllDirectoriesFunction pfn = (SetDefaultDllDirectoriesFunction) GetProcAddress(hKernel32, "SetDefaultDllDirectories");	if (pfn) { (*pfn)(LOAD_LIBRARY_SEARCH_SYSTEM32); }	int exitCode = -1;	CString cmdLine(lpCmdLine);	if (cmdLine.Find(L"--checkInstall") >= 0) {		// If we're already installed, exit as fast as possible		if (!MachineInstaller::ShouldSilentInstall()) {			exitCode = 0;			goto out;		}		// Make sure update.exe gets silent		wcscat(lpCmdLine, L" --silent");	}	HRESULT hr = ::CoInitialize(NULL);	ATLASSERT(SUCCEEDED(hr));	AtlInitCommonControls(ICC_COOL_CLASSES | ICC_BAR_CLASSES);	hr = _Module.Init(NULL, hInstance);	bool isQuiet = (cmdLine.Find(L"-s") >= 0);	bool weAreUACElevated = CUpdateRunner::AreWeUACElevated() == S_OK;	bool attemptingToRerun = (cmdLine.Find(L"--rerunningWithoutUAC") >= 0);	if (weAreUACElevated && attemptingToRerun) {		CUpdateRunner::DisplayErrorMessage(CString(L"Please re-run this installer as a normal user instead of /"Run as Administrator/"."), NULL);		exitCode = E_FAIL;		goto out;	}	if (!CFxHelper::CanInstallDotNet4_5()) {		// Explain this as nicely as possible and give up.		MessageBox(0L, L"This program cannot run on Windows XP or before; it requires a later version of Windows.", L"Incompatible Operating System", 0);		exitCode = E_FAIL;		goto out;	}	if (!CFxHelper::IsDotNet45OrHigherInstalled()) {		hr = CFxHelper::InstallDotNetFramework(isQuiet);		if (FAILED(hr)) {			exitCode = hr; // #yolo			CUpdateRunner::DisplayErrorMessage(CString(L"Failed to install the .NET Framework, try installing .NET 4.5 or higher manually"), NULL);			goto out;		}			// S_FALSE isn't failure, but we still shouldn't try to install		if (hr != S_OK) {			exitCode = 0;			goto out;		}	}	// If we're UAC-elevated, we shouldn't be because it will give us permissions	// problems later. Just silently rerun ourselves.	if (weAreUACElevated) {		wchar_t buf[4096];		HMODULE hMod = GetModuleHandle(NULL);		GetModuleFileNameW(hMod, buf, 4096);		wcscat(lpCmdLine, L" --rerunningWithoutUAC");		CUpdateRunner::ShellExecuteFromExplorer(buf, lpCmdLine);		exitCode = 0;		goto out;	}	exitCode = CUpdateRunner::ExtractUpdaterAndRun(lpCmdLine, false);out:	_Module.Term();	::CoUninitialize();	return exitCode;}
开发者ID:Andrew-Hanlon,项目名称:Squirrel.Windows,代码行数:84,


示例23: launch_server

int launch_server(const std::string& socket_spec) {#if defined(_WIN32)    /* we need to start the server in the background                    */    /* we create a PIPE that will be used to wait for the server's "OK" */    /* message since the pipe handles must be inheritable, we use a     */    /* security attribute                                               */    SECURITY_ATTRIBUTES   sa;    sa.nLength = sizeof(sa);    sa.lpSecurityDescriptor = NULL;    sa.bInheritHandle = TRUE;    // Redirect stdin to Windows /dev/null. If we instead pass an original    // stdin/stdout/stderr handle and it is a console handle, when the adb    // server starts up, the C Runtime will see a console handle for a process    // that isn't connected to a console and it will configure    // stdin/stdout/stderr to be closed. At that point, freopen() could be used    // to reopen stderr/out, but it would take more massaging to fixup the file    // descriptor number that freopen() uses. It's simplest to avoid all of this    // complexity by just redirecting stdin to `nul' and then the C Runtime acts    // as expected.    unique_handle   nul_read(CreateFileW(L"nul", GENERIC_READ,            FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING,            FILE_ATTRIBUTE_NORMAL, NULL));    if (nul_read.get() == INVALID_HANDLE_VALUE) {        fprintf(stderr, "Cannot open 'nul': %s/n",                android::base::SystemErrorCodeToString(GetLastError()).c_str());        return -1;    }    // Create pipes with non-inheritable read handle, inheritable write handle. We need to connect    // the subprocess to pipes instead of just letting the subprocess inherit our existing    // stdout/stderr handles because a DETACHED_PROCESS cannot write to a console that it is not    // attached to.    unique_handle   ack_read, ack_write;    if (!_create_anonymous_pipe(&ack_read, &ack_write, &sa)) {        return -1;    }    unique_handle   stdout_read, stdout_write;    if (!_create_anonymous_pipe(&stdout_read, &stdout_write, &sa)) {        return -1;    }    unique_handle   stderr_read, stderr_write;    if (!_create_anonymous_pipe(&stderr_read, &stderr_write, &sa)) {        return -1;    }    /* Some programs want to launch an adb command and collect its output by     * calling CreateProcess with inheritable stdout/stderr handles, then     * using read() to get its output. When this happens, the stdout/stderr     * handles passed to the adb client process will also be inheritable.     * When starting the adb server here, care must be taken to reset them     * to non-inheritable.     * Otherwise, something bad happens: even if the adb command completes,     * the calling process is stuck while read()-ing from the stdout/stderr     * descriptors, because they're connected to corresponding handles in the     * adb server process (even if the latter never uses/writes to them).     * Note that even if we don't pass these handles in the STARTUPINFO struct,     * if they're marked inheritable, they're still inherited, requiring us to     * deal with this.     *     * If we're still having problems with inheriting random handles in the     * future, consider using PROC_THREAD_ATTRIBUTE_HANDLE_LIST to explicitly     * specify which handles should be inherited: http://blogs.msdn.com/b/oldnewthing/archive/2011/12/16/10248328.aspx     *     * Older versions of Windows return console pseudo-handles that cannot be     * made non-inheritable, so ignore those failures.     */    _try_make_handle_noninheritable(GetStdHandle(STD_INPUT_HANDLE));    _try_make_handle_noninheritable(GetStdHandle(STD_OUTPUT_HANDLE));    _try_make_handle_noninheritable(GetStdHandle(STD_ERROR_HANDLE));    STARTUPINFOW    startup;    ZeroMemory( &startup, sizeof(startup) );    startup.cb = sizeof(startup);    startup.hStdInput  = nul_read.get();    startup.hStdOutput = stdout_write.get();    startup.hStdError  = stderr_write.get();    startup.dwFlags    = STARTF_USESTDHANDLES;    // Verify that the pipe_write handle value can be passed on the command line    // as %d and that the rest of adb code can pass it around in an int.    const int ack_write_as_int = cast_handle_to_int(ack_write.get());    if (cast_int_to_handle(ack_write_as_int) != ack_write.get()) {        // If this fires, either handle values are larger than 32-bits or else        // there is a bug in our casting.        // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx        fprintf(stderr, "Cannot fit pipe handle value into 32-bits: 0x%p/n",                ack_write.get());        return -1;    }    // get path of current program    WCHAR       program_path[MAX_PATH];    const DWORD module_result = GetModuleFileNameW(NULL, program_path,                                                   arraysize(program_path));    if ((module_result >= arraysize(program_path)) || (module_result == 0)) {        // String truncation or some other error.        fprintf(stderr, "Cannot get executable path: %s/n",                android::base::SystemErrorCodeToString(GetLastError()).c_str());        return -1;//.........这里部分代码省略.........
开发者ID:mnemonyc,项目名称:platform_system_core,代码行数:101,


示例24: if

struct val *get_appended_data(void) {    FILE *fp = NULL;    static char buf[MAX_APPENDED+1];    wchar_t exe_name[MAX_PATH+1];    wchar_t *wp;    size_t n;    int i;    char *p;    char *end;    char *found;    char *current_key;    char *current_value;    static struct val vals[100];    /* Read the last MAX_APPENDED bytes from the exe */    if (!GetModuleFileNameW(NULL, exe_name, MAX_PATH))        terminate(L"Cannot get executable name: %d", GetLastError());    if ((fp = _wfopen(exe_name, L"rb")) == NULL)        terminate(L"Open failed: %d", GetLastError());    if (fseek(fp, -MAX_APPENDED, SEEK_END))        terminate(L"Seek failed");    n = fread(buf, 1, MAX_APPENDED, fp);    buf[n] = '/0';    /* Get the executable's directory */    wp = exe_name + wcslen(exe_name);    while (wp > exe_name) {        --wp;        if (*wp == '//') {            *wp = '/0';            break;        }    }    exe_dir = wcsdup(exe_name);    /* Find the start of the appended data */    p = buf;    found = 0;    end = buf + n;    db("Starting", p);    while (p < end) {        char *next = memchr(p, MARKER[0], end-p);        db("Next", next);        if (next == 0)            break;        if (memcmp(next, MARKER, sizeof(MARKER) - 1) == 0) {            db("Found", next);            found = next + sizeof(MARKER) - 1;            while (*found == '/r' || *found == '/n')                ++found;        }        p = next + 1;    }    if (!found)        terminate(L"Appended shim data not found");    wprintf(L"Appended data: %S/n", found);    /* The appended data has the form:     *     key=value/nkey=value/n.../0     * Split into key, value pairs.     * We modify the buffer to do this, by inserting nulls as needed.     */    p = found;    i = 0;    current_key = p;    current_value = 0;    while (p < end) {        if (!current_value && (*p == '=')) {            *p++ = '/0';            current_value = p;        }        else if (*p == '/n' || *p == '/r') {            *p++ = '/0';            if (!current_value)                terminate(L"Invalid data: %S has no value", current_key);            vals[i].key = current_key;            vals[i].value = current_value;            ++i;            /* Skip blank lines */            while (p < end && (*p == '/n' || *p == '/r'))                ++p;            current_key = p;            current_value = 0;        }        else {            ++p;        }    }    vals[i].key = 0;    vals[i].value = 0;    return vals;}
开发者ID:pfmoore,项目名称:shimmy,代码行数:94,


示例25: apr_initialize

//.........这里部分代码省略.........         (and other modules). */      apr_allocator_max_free_set(allocator, 1);    }  svn_utf_initialize2(FALSE, g_pool); /* Optimize character conversions */  svn_fs_initialize(g_pool); /* Avoid some theoretical issues */  svn_ra_initialize(g_pool);  /* We shouldn't fill the JVMs memory with FS cache data unless explictly     requested. */  {    svn_cache_config_t settings = *svn_cache_config_get();    settings.cache_size = 0;    settings.file_handle_count = 0;    settings.single_threaded = FALSE;    svn_cache_config_set(&settings);  }#ifdef ENABLE_NLS#ifdef WIN32  {    WCHAR ucs2_path[MAX_PATH];    char *utf8_path;    const char *internal_path;    apr_pool_t *pool;    apr_status_t apr_err;    apr_size_t inwords, outbytes;    unsigned int outlength;    pool = svn_pool_create(g_pool);    /* get dll name - our locale info will be in '../share/locale' */    inwords = sizeof(ucs2_path) / sizeof(ucs2_path[0]);    HINSTANCE moduleHandle = GetModuleHandle("libsvnjavahl-1");    GetModuleFileNameW(moduleHandle, ucs2_path, inwords);    inwords = lstrlenW(ucs2_path);    outbytes = outlength = 3 * (inwords + 1);    utf8_path = reinterpret_cast<char *>(apr_palloc(pool, outlength));    apr_err = apr_conv_ucs2_to_utf8((const apr_wchar_t *) ucs2_path,                                    &inwords, utf8_path, &outbytes);    if (!apr_err && (inwords > 0 || outbytes == 0))      apr_err = APR_INCOMPLETE;    if (apr_err)      {        if (stderr)          fprintf(stderr, "Can't convert module path to UTF-8");        return FALSE;      }    utf8_path[outlength - outbytes] = '/0';    internal_path = svn_dirent_internal_style(utf8_path, pool);    /* get base path name */    internal_path = svn_dirent_dirname(internal_path, pool);    internal_path = svn_dirent_join(internal_path, SVN_LOCALE_RELATIVE_PATH,                                  pool);    bindtextdomain(PACKAGE_NAME, internal_path);    svn_pool_destroy(pool);  }#else  bindtextdomain(PACKAGE_NAME, SVN_LOCALE_DIR);#endif#endif#if defined(WIN32) || defined(__CYGWIN__)  /* See http://svn.apache.org/repos/asf/subversion/trunk/notes/asp-dot-net-hack.txt */  /* ### This code really only needs to be invoked by consumers of     ### the libsvn_wc library, which basically means SVNClient. */  if (getenv("SVN_ASP_DOT_NET_HACK"))
开发者ID:Ranga123,项目名称:test1,代码行数:67,


示例26: InitLogs

VOIDInitLogs(VOID){    WCHAR szBuf[MAX_PATH] = L"SYSTEM//CurrentControlSet//Services//EventLog//Application//ReactOS Application Manager";    WCHAR szPath[MAX_PATH];    DWORD dwCategoryNum = 1;    DWORD dwDisp, dwData;    HKEY hKey;    if (!SettingsInfo.bLogEnabled) return;    if (RegCreateKeyExW(HKEY_LOCAL_MACHINE,                        szBuf, 0, NULL,                        REG_OPTION_NON_VOLATILE,                        KEY_WRITE, NULL, &hKey, &dwDisp) != ERROR_SUCCESS)    {        return;    }    if (!GetModuleFileNameW(NULL, szPath, _countof(szPath)))        return;    if (RegSetValueExW(hKey,                       L"EventMessageFile",                       0,                       REG_EXPAND_SZ,                       (LPBYTE)szPath,                       (DWORD)(wcslen(szPath) + 1) * sizeof(WCHAR)) != ERROR_SUCCESS)    {        RegCloseKey(hKey);        return;    }    dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE |             EVENTLOG_INFORMATION_TYPE;    if (RegSetValueExW(hKey,                       L"TypesSupported",                       0,                       REG_DWORD,                       (LPBYTE)&dwData,                       sizeof(DWORD)) != ERROR_SUCCESS)    {        RegCloseKey(hKey);        return;    }    if (RegSetValueExW(hKey,                       L"CategoryMessageFile",                       0,                       REG_EXPAND_SZ,                       (LPBYTE)szPath,                       (DWORD)(wcslen(szPath) + 1) * sizeof(WCHAR)) != ERROR_SUCCESS)    {        RegCloseKey(hKey);        return;    }    if (RegSetValueExW(hKey,                       L"CategoryCount",                       0,                       REG_DWORD,                       (LPBYTE)&dwCategoryNum,                       sizeof(DWORD)) != ERROR_SUCCESS)    {        RegCloseKey(hKey);        return;    }    RegCloseKey(hKey);    hLog = RegisterEventSourceW(NULL, L"ReactOS Application Manager");}
开发者ID:reactos,项目名称:reactos,代码行数:73,


示例27: MyAssertProc

int MyAssertProc(const wchar_t* pszFile, int nLine, const wchar_t* pszTest, bool abNoPipe){	HooksUnlocker;	#ifdef _DEBUG	if (MyAssertSkip(pszFile, nLine, pszTest, abNoPipe))		return 1;	#endif	MyAssertDumpToFile(pszFile, nLine, pszTest);	HANDLE hHeap = GetProcessHeap();	MyAssertInfo* pa = (MyAssertInfo*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, sizeof(MyAssertInfo));	if (!pa)		return -1;	wchar_t *szExeName = (wchar_t*)HeapAlloc(hHeap, HEAP_ZERO_MEMORY, (MAX_PATH+1)*sizeof(wchar_t));	if (szExeName && !GetModuleFileNameW(NULL, szExeName, MAX_PATH+1)) szExeName[0] = 0;	pa->bNoPipe = abNoPipe;	msprintf(pa->szTitle, countof(pa->szTitle), L"CEAssert PID=%u TID=%u", GetCurrentProcessId(), GetCurrentThreadId());	wchar_t szVer4[2] = WSTRING(MVV_4a);	msprintf(pa->szDebugInfo, countof(pa->szDebugInfo), L"Assertion in %s [%02u%02u%02u%s]/n%s/n/n%s: %i/n/nPress 'Retry' to trap.",	                szExeName ? szExeName : L"<HeapAllocFailed>",					MVV_1, MVV_2, MVV_3, szVer4,					pszTest ? pszTest : L"", pszFile, nLine);	DWORD dwCode = 0;	if (gAllowAssertThread == am_Thread)	{		DWORD dwTID;		HANDLE hThread = apiCreateThread(MyAssertThread, pa, &dwTID, "MyAssertThread");		if (hThread == NULL)		{			dwCode = IDRETRY;			goto wrap;		}		WaitForSingleObject(hThread, INFINITE);		GetExitCodeThread(hThread, &dwCode);		CloseHandle(hThread);		goto wrap;	}	#ifdef ASSERT_PIPE_ALLOWED#ifdef _DEBUG	if (!abNoPipe && (gAllowAssertThread == am_Pipe))	{		HWND hConWnd = GetConEmuHWND(2);		HWND hGuiWnd = ghConEmuWnd;		// -- искать - нельзя. Если мы НЕ в ConEmu - нельзя стучаться в другие копии!!!		//#ifndef CONEMU_MINIMAL		//if (hGuiWnd == NULL)		//{		//	hGuiWnd = FindWindowEx(NULL, NULL, VirtualConsoleClassMain, NULL);		//}		//#endif		if (hGuiWnd && gnInMyAssertTrap <= 0)		{			InterlockedIncrement(&gnInMyAssertTrap);			InterlockedIncrement(&gnInMyAssertPipe);			gnInMyAssertThread = GetCurrentThreadId();			ResetEvent(ghInMyAssertTrap);						dwCode = GuiMessageBox(abNoPipe ? NULL : hGuiWnd, pa->szDebugInfo, pa->szTitle, MB_SETFOREGROUND|MB_SYSTEMMODAL|MB_RETRYCANCEL);			InterlockedDecrement(&gnInMyAssertTrap);			InterlockedDecrement(&gnInMyAssertPipe);			SetEvent(ghInMyAssertTrap);			gnInMyAssertThread = 0;			goto wrap;		}	}	while (gnInMyAssertPipe>0 && (gnInMyAssertThread != GetCurrentThreadId()))	{		Sleep(250);	}#endif#endif	// В консольных приложениях попытка запустить CreateThread(MyAssertThread) может зависать	dwCode = MyAssertThread(pa);wrap:	if (pa)		HeapFree(hHeap, 0, pa);	if (szExeName)		HeapFree(hHeap, 0, szExeName);	return (dwCode == IDRETRY) ? -1 : 1;}
开发者ID:BigVal71,项目名称:ConEmu,代码行数:91,


示例28: CommandLineToArgvW

/************************************************************************* * CommandLineToArgvW            [[email
C++ GetModuleHandle函数代码示例
C++ GetModuleFileNameEx函数代码示例
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。