当前位置: 首页>>代码示例>>C++>>正文


C++ CloseHandle函数代码示例

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


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

示例1: CloseHandle

gcore::Condition::~Condition() {
  details::COND_WIN32 *cond = (details::COND_WIN32*)(&mData[0]);
  CloseHandle(cond->notifyOne);
  CloseHandle(cond->notifyAll);
  DeleteCriticalSection(&(cond->blockedLock));
}
开发者ID:gatgui,项目名称:gcore,代码行数:6,代码来源:threads.cpp

示例2: is_gui

static int is_gui(const char *exename)
{
	HANDLE hImage;

	DWORD  bytes;
	DWORD  SectionOffset;
	DWORD  CoffHeaderOffset;
	DWORD  MoreDosHeader[16];
	ULONG  ntSignature;
	IMAGE_DOS_HEADER      image_dos_header;
	IMAGE_FILE_HEADER     image_file_header;
	IMAGE_OPTIONAL_HEADER image_optional_header;

	hImage = CreateFile(exename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (INVALID_HANDLE_VALUE == hImage) {
		return 0;
	}

	/*
	 *  Read the MS-DOS image header.
	 */
	if (!ReadFile(hImage, &image_dos_header, sizeof(IMAGE_DOS_HEADER), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	if (IMAGE_DOS_SIGNATURE != image_dos_header.e_magic) {
		CloseHandle(hImage);
		return 0;
	}

	/* Read more MS-DOS header */
	if (!ReadFile(hImage, MoreDosHeader, sizeof(MoreDosHeader), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	/* Get actual COFF header. */
	CoffHeaderOffset = SetFilePointer(hImage, image_dos_header.e_lfanew, NULL, FILE_BEGIN);

	if (CoffHeaderOffset == (DWORD)(-1)) {
		CloseHandle(hImage);
		return 0;
	}

	CoffHeaderOffset += sizeof(ULONG);

	if (!ReadFile (hImage, &ntSignature, sizeof(ULONG), &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	if (IMAGE_NT_SIGNATURE != ntSignature) {
		CloseHandle(hImage);
		return 0;
	}

	SectionOffset = CoffHeaderOffset + IMAGE_SIZEOF_FILE_HEADER + IMAGE_SIZEOF_NT_OPTIONAL_HEADER;

	if (!ReadFile(hImage, &image_file_header, IMAGE_SIZEOF_FILE_HEADER, &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	/* Read optional header. */
	if (!ReadFile(hImage, &image_optional_header, IMAGE_SIZEOF_NT_OPTIONAL_HEADER, &bytes, NULL)) {
		CloseHandle(hImage);
		return 0;
	}

	CloseHandle(hImage);

	if (image_optional_header.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
		return 1;
	return 0;
}
开发者ID:oldfaber,项目名称:wzsh,代码行数:76,代码来源:nt_execve.c

示例3: process_shebang

static int process_shebang(char *argv0, const char *const *cmdstr, size_t *cmdlen, char **cmdend, unsigned int *cmdsize)
{
	HANDLE hfile;
	char buf[512];
	unsigned int nn, t0;
	char *ptr, *ptr2;
	char *newargv[4];
	char pbuffer[MAX_PATH];
	char *filepart;
	static const char *shellnames[] = {"/bin/sh", "/bin/zsh", "/bin/ksh"};
	static const char usrbinenv[] = "/usr/bin/env";
	static const char usrbinpython[] = "/usr/bin/python";
	static const char usrbinperl[] = "/usr/bin/perl";
	static const char usrbintcl[] = "/usr/bin/tcl";

	hfile = CreateFile(argv0, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
			   NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if (hfile == INVALID_HANDLE_VALUE)
		return (-1);
	if (!ReadFile(hfile, buf, (DWORD)sizeof(buf), (DWORD *)&nn, NULL)) {
		CloseHandle(hfile);
		return (-1);
	}
	CloseHandle(hfile);
	if (!((nn >= 3) && (buf[0] == '#') && (buf[1] == '!')))
		return (0);

	/* this code is more or less what zexecve() does */
	for (t0 = 0; t0 != nn; t0++)
		if ((buf[t0] == '\n') || (buf[t0] == '\r'))
			break;
	while (isspace(buf[t0]))
		buf[t0--] = '\0';
	buf[sizeof(buf)-1] = '\0';
	/* @@@@ fails for "/b/s p/pgm" !!! */
	for (ptr = buf + 2; *ptr && *ptr == ' '; ptr++)
		;
	for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++)
		;
	/* ptr2 is the program name, ptr points to the args */
	dbgprintf(PR_VERBOSE, "%s(): found \"!#\" program=[%s] arg ptr=[%s]\n", __FUNCTION__, ptr2, *ptr ? ptr + 1 : "NULL");
	/* append to the cmdstr
	   should have argv0 ('/' or '\' format ?) */
	if (*ptr) {
		*ptr = '\0';
		newargv[0] = ptr2;
		newargv[1] = ptr + 1;
		newargv[2] = argv0;
	} else {
		newargv[0] = ptr2;
		newargv[1] = argv0;
		newargv[2] = NULL;
	}
	newargv[3] = NULL;
	concat_args_and_quote((const char *const *)newargv, (char **)cmdstr, cmdlen, cmdend, cmdsize);
	*cmdend = '\0';
	/* if ptr2 is a "well known" shell name set argv0 to our module name */
	for (nn = 0; nn < LENGTH_OF(shellnames); nn++) {
		if (strcmp(ptr2, shellnames[nn]) == 0) {
			strcpy(argv0, gModuleName);
			return (1);
		}
	}
	if (strcmp(ptr2, usrbinenv) == 0) {
		SearchPath(NULL, "env.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbinpython) == 0) {
		SearchPath(NULL, "python.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbinperl) == 0) {
		SearchPath(NULL, "perl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else if (strcmp(ptr2, usrbintcl) == 0) {
		SearchPath(NULL, "tcl.exe", NULL, sizeof(pbuffer), pbuffer, &filepart);
		strcpy(argv0, pbuffer);
	} else {
		char *exeptr;
		path_to_backslash(ptr2);
		strcpy(argv0, ptr2);
		/* if argv0 does not end with ".exe" add ".exe" */
		exeptr = StrStrI(argv0, ".exe");
		if ((exeptr == NULL) || (exeptr != strrchr(argv0, '.'))) {
			strcat(argv0, ".exe");
			dbgprintf(PR_VERBOSE, "%s(): argv0 modified to [%s]\n", __FUNCTION__, argv0);
		}
	}
	return (1);
}
开发者ID:oldfaber,项目名称:wzsh,代码行数:88,代码来源:nt_execve.c

示例4: execute

bool execute(const char* command, std::string currentDir, DWORD& retCode, std::string& output) {
	HANDLE outWR;

	SECURITY_ATTRIBUTES sa;
	sa.nLength = sizeof(SECURITY_ATTRIBUTES);
	sa.lpSecurityDescriptor = NULL;
	sa.bInheritHandle = TRUE;

	TCHAR lpTempPathBuffer[BUFSIZE];
	TCHAR szTempFileName[MAX_PATH];
	DWORD ret = GetTempPath(BUFSIZE, lpTempPathBuffer);
	if (ret > BUFSIZE || ret == 0) {
		MessageBox(	NULL, "Error GetTempPath", "Error", MB_OK );
		return false;
	}

	ret = GetTempFileName(lpTempPathBuffer, "svn", 0, szTempFileName);
	if (ret == 0) {
		MessageBox(	NULL, "Error GetTempFileName", "Error", MB_OK );
		return false;
	}

	outWR = CreateFile(szTempFileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if (outWR == INVALID_HANDLE_VALUE) {
		MessageBox(	NULL, "Error create file", "Error", MB_OK );
		return false;
	}

	PROCESS_INFORMATION processInfomation;
	STARTUPINFO startupInfo;
	memset(&processInfomation, 0, sizeof(processInfomation));
	memset(&startupInfo, 0, sizeof(startupInfo));
	startupInfo.cb = sizeof(startupInfo);
	startupInfo.hStdError = outWR;
	startupInfo.hStdOutput = outWR;
	startupInfo.dwFlags |= STARTF_USESTDHANDLES;
	startupInfo.wShowWindow = SW_HIDE;

	BOOL result = CreateProcess(
		NULL,
		(char*) command,
		NULL,
		NULL,
		TRUE,
		0,
		NULL,
		currentDir.c_str(),
		&startupInfo,
		&processInfomation);

	if (!result) {
		MessageBox(	NULL, "Can't CreateProcess", "Error", MB_OK );
		CloseHandle(outWR);
		return false;
	} else {
		WaitForSingleObject(processInfomation.hProcess, INFINITE);
		GetExitCodeProcess(processInfomation.hProcess, &retCode);
		CloseHandle(processInfomation.hProcess);
		CloseHandle(processInfomation.hThread);

		// read from stdout
		if (!CloseHandle(outWR)) {
			MessageBox(	NULL, "Can't CloseHandle", "Error", MB_OK );
			return false;
		}

		outWR = CreateFile(szTempFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (outWR == INVALID_HANDLE_VALUE) {
			MessageBox(	NULL, "Error open file", "Error", MB_OK );
			return false;
		}

		CHAR buf[BUFSIZE];
		DWORD dwRead;
		DWORD totalSize = 0;
		std::vector<char*> allBufs;
		std::vector<DWORD> lens;
		while (true) {
			result = ReadFile(outWR, buf, BUFSIZE, &dwRead, NULL);
			if (!result || dwRead == 0) break;
			totalSize += dwRead;
			char* content = new char[dwRead];
			memcpy(content, buf, dwRead);
			allBufs.push_back(content);
			lens.push_back(dwRead);
		}
		char* content = new char[totalSize + 1];
		char* currentPtr = content;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			memcpy(currentPtr, allBufs[i], lens[i]);
			currentPtr += lens[i];
		}
		content[totalSize] = 0;
		for (std::size_t i = 0; i < allBufs.size(); i++) {
			delete[] allBufs[i];
		}
		output.swap(std::string(content));
		delete[] content;

		CloseHandle(outWR);
//.........这里部分代码省略.........
开发者ID:flexme,项目名称:svnplugin,代码行数:101,代码来源:fileutil.cpp

示例5: replace

/* makes the replace */
INT replace(TCHAR source[MAX_PATH], TCHAR dest[MAX_PATH], DWORD dwFlags, BOOL *doMore)
{
    TCHAR d[MAX_PATH];
    TCHAR s[MAX_PATH];
    HANDLE hFileSrc, hFileDest;
    DWORD  dwAttrib, dwRead, dwWritten;
    LPBYTE buffer;
    BOOL   bEof = FALSE;
    FILETIME srcCreationTime, destCreationTime, srcLastAccessTime, destLastAccessTime;
    FILETIME srcLastWriteTime, destLastWriteTime;
    GetPathCase(source, s);
    GetPathCase(dest, d);
    s[0] = _totupper(s[0]);
    d[0] = _totupper(d[0]);
    // ConOutPrintf(_T("old-src:  %s\n"), s);
    // ConOutPrintf(_T("old-dest: %s\n"), d);
    // ConOutPrintf(_T("src:  %s\n"), source);
    // ConOutPrintf(_T("dest: %s\n"), dest);

    /* Open up the sourcefile */
    hFileSrc = CreateFile (source, GENERIC_READ, FILE_SHARE_READ,NULL, OPEN_EXISTING, 0, NULL);
    if (hFileSrc == INVALID_HANDLE_VALUE)
    {
        ConOutResPrintf(STRING_COPY_ERROR1, source);
        return 0;
    }

    /*
     * Get the time from source file to be used in the comparison
     * with dest time if update switch is set.
     */
    GetFileTime (hFileSrc, &srcCreationTime, &srcLastAccessTime, &srcLastWriteTime);

    /*
     * Retrieve the source attributes so that they later on
     * can be inserted in to the destination.
     */
    dwAttrib = GetFileAttributes (source);

    if (IsExistingFile (dest))
    {
        /*
         * Resets the attributes to avoid probles with read only files,
         * checks for read only has been made earlier.
         */
        SetFileAttributes(dest,FILE_ATTRIBUTE_NORMAL);
        /*
         * Is the update flas set? The time has to be controled so that
         * only older files are replaced.
         */
        if (dwFlags & REPLACE_UPDATE)
        {
            /* Read destination time */
            hFileDest = CreateFile(dest, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
                0, NULL);

            if (hFileSrc == INVALID_HANDLE_VALUE)
            {
                ConOutResPrintf(STRING_COPY_ERROR1, dest);
                return 0;
            }

            /* Compare time */
            GetFileTime (hFileDest, &destCreationTime, &destLastAccessTime, &destLastWriteTime);
            if (!((srcLastWriteTime.dwHighDateTime > destLastWriteTime.dwHighDateTime) ||
                    (srcLastWriteTime.dwHighDateTime == destLastWriteTime.dwHighDateTime &&
                     srcLastWriteTime.dwLowDateTime > destLastWriteTime.dwLowDateTime)))
            {
                CloseHandle (hFileSrc);
                CloseHandle (hFileDest);
                return 0;
            }
            CloseHandle (hFileDest);
        }
        /* Delete the old file */
        DeleteFile (dest);
    }

    /* Check confirm flag, and take appropriate action */
    if (dwFlags & REPLACE_CONFIRM)
    {
        /* Output depending on add flag */
        if (dwFlags & REPLACE_ADD)
            ConOutResPrintf(STRING_REPLACE_HELP9, dest);
        else
            ConOutResPrintf(STRING_REPLACE_HELP10, dest);
        if ( !FilePromptYNA (0))
        {
            CloseHandle (hFileSrc);
            return 0;
        }
    }

    /* Output depending on add flag */
    if (dwFlags & REPLACE_ADD)
        ConOutResPrintf(STRING_REPLACE_HELP11, dest);
    else
        ConOutResPrintf(STRING_REPLACE_HELP5, dest);

//.........这里部分代码省略.........
开发者ID:hoangduit,项目名称:reactos,代码行数:101,代码来源:replace.c

示例6: WinMain

int WINAPI
WinMain (
         _In_ HINSTANCE hInstance,
         _In_opt_ HINSTANCE hPrevInstance,
         _In_ PSTR szCmdLine,
         _In_ int iCmdShow)
/*++

Routine Description:

    Entry point for app. Registers class, creates window.

--*/
{
    CHAR        szAppClassName[] = "w1394_AppClass";
    CHAR        szTitleBar[] = "WDF 1394 Hybrid Test Application";
    MSG         Msg;
    WNDCLASSEX  WndClassEx;
    HWND        hWnd;

    UNREFERENCED_PARAMETER (hPrevInstance);
    UNREFERENCED_PARAMETER (szCmdLine);


    g_hInstance = hInstance;

    // main window app...
    WndClassEx.cbSize = sizeof(WNDCLASSEX);
    WndClassEx.style = CS_DBLCLKS | CS_BYTEALIGNWINDOW | CS_GLOBALCLASS;
    WndClassEx.lpfnWndProc = w1394_AppWndProc;
    WndClassEx.cbClsExtra = 0;
    WndClassEx.cbWndExtra = 0;
    WndClassEx.hInstance = g_hInstance;
    WndClassEx.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
    WndClassEx.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
    WndClassEx.hCursor = NULL;
    WndClassEx.hbrBackground = (HBRUSH)COLOR_BACKGROUND;
    WndClassEx.lpszMenuName = "AppMenu";
    WndClassEx.lpszClassName = szAppClassName;

    RegisterClassEx( &WndClassEx );

    hWnd = CreateWindowEx ( 
        WS_EX_WINDOWEDGE | WS_EX_ACCEPTFILES,
        szAppClassName,
        szTitleBar,
        WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        NULL,
        NULL,
        g_hInstance,
        NULL);

    ShowWindow(hWnd, iCmdShow);

    while (GetMessage(&Msg, NULL, 0, 0)) 
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }

    if (g_hTestDevice)
    {
        CloseHandle (g_hTestDevice);
    }

    return (int)(Msg.wParam);
} // WinMain
开发者ID:Realhram,项目名称:wdk81,代码行数:71,代码来源:wdf1394.c

示例7: shgfi_get_exe_type

static DWORD shgfi_get_exe_type(LPCWSTR szFullPath)
{
    BOOL status = FALSE;
    HANDLE hfile;
    DWORD BinaryType;
    IMAGE_DOS_HEADER mz_header;
    IMAGE_NT_HEADERS nt;
    DWORD len;
    char magic[4];

    status = GetBinaryTypeW (szFullPath, &BinaryType);
    if (!status)
        return 0;
    if (BinaryType == SCS_DOS_BINARY || BinaryType == SCS_PIF_BINARY)
        return 0x4d5a;

    hfile = CreateFileW( szFullPath, GENERIC_READ, FILE_SHARE_READ,
                         NULL, OPEN_EXISTING, 0, 0 );
    if ( hfile == INVALID_HANDLE_VALUE )
        return 0;

    /*
     * The next section is adapted from MODULE_GetBinaryType, as we need
     * to examine the image header to get OS and version information. We
     * know from calling GetBinaryTypeA that the image is valid and either
     * an NE or PE, so much error handling can be omitted.
     * Seek to the start of the file and read the header information.
     */

    SetFilePointer( hfile, 0, NULL, SEEK_SET );
    ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL );

    SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
    ReadFile( hfile, magic, sizeof(magic), &len, NULL );
    if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
    {
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &nt, sizeof(nt), &len, NULL );
        CloseHandle( hfile );
        /* DLL files are not executable and should return 0 */
        if (nt.FileHeader.Characteristics & IMAGE_FILE_DLL)
            return 0;
        if (nt.OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI)
        {
             return IMAGE_NT_SIGNATURE | 
                   (nt.OptionalHeader.MajorSubsystemVersion << 24) |
                   (nt.OptionalHeader.MinorSubsystemVersion << 16);
        }
        return IMAGE_NT_SIGNATURE;
    }
    else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
    {
        IMAGE_OS2_HEADER ne;
        SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET );
        ReadFile( hfile, &ne, sizeof(ne), &len, NULL );
        CloseHandle( hfile );
        if (ne.ne_exetyp == 2)
            return IMAGE_OS2_SIGNATURE | (ne.ne_expver << 16);
        return 0;
    }
    CloseHandle( hfile );
    return 0;
}
开发者ID:carlosbislip,项目名称:wine,代码行数:63,代码来源:shell32_main.c

示例8: _tiffCloseProc

static int
_tiffCloseProc(thandle_t fd)
{
	return (CloseHandle(fd) ? 0 : -1);
}
开发者ID:etlegacy,项目名称:EasyGen,代码行数:5,代码来源:tif_win32.c

示例9: SFileCreateArchiveEx


//.........这里部分代码省略.........
            nError = ERROR_NOT_ENOUGH_MEMORY;
    }

    // Fill the MPQ archive handle structure and create the header,
    // block buffer, hash table and block table
    if(nError == ERROR_SUCCESS)
    {
        memset(ha, 0, sizeof(TMPQArchive));
        strcpy(ha->szFileName, szMpqName);
        ha->hFile          = hFile;
        ha->dwBlockSize    = 0x200 << DEFAULT_BLOCK_SIZE;
        ha->MpqPos         = MpqPos;
        ha->FilePointer    = MpqPos;
        ha->pHeader        = &ha->Header;
        ha->pHashTable     = ALLOCMEM(TMPQHash, dwHashTableSize);
        ha->pBlockTable    = ALLOCMEM(TMPQBlock, dwHashTableSize);
        ha->pExtBlockTable = ALLOCMEM(TMPQBlockEx, dwHashTableSize);
        ha->pbBlockBuffer  = ALLOCMEM(BYTE, ha->dwBlockSize);
        ha->pListFile      = NULL;
        ha->dwFlags       |= MPQ_FLAG_CHANGED;

        if(!ha->pHashTable || !ha->pBlockTable || !ha->pExtBlockTable || !ha->pbBlockBuffer)
            nError = GetLastError();
        hFile = INVALID_HANDLE_VALUE;
    }

    // Fill the MPQ header and all buffers
    if(nError == ERROR_SUCCESS)
    {
        LARGE_INTEGER TempPos;
        TMPQHeader2 * pHeader = ha->pHeader;
        DWORD dwHeaderSize = (wFormatVersion == MPQ_FORMAT_VERSION_2) ? sizeof(TMPQHeader2) : sizeof(TMPQHeader);

        memset(pHeader, 0, sizeof(TMPQHeader2));
        pHeader->dwID            = ID_MPQ;
        pHeader->dwHeaderSize    = dwHeaderSize;
        pHeader->dwArchiveSize   = pHeader->dwHeaderSize + dwHashTableSize * sizeof(TMPQHash);
        pHeader->wFormatVersion  = wFormatVersion;
        pHeader->wBlockSize      = 3;               // 0x1000 bytes per block
        pHeader->dwHashTableSize = dwHashTableSize;

        // Set proper hash table positions
        ha->HashTablePos.QuadPart = ha->MpqPos.QuadPart + pHeader->dwHeaderSize;
        ha->pHeader->dwHashTablePos = pHeader->dwHeaderSize;
        ha->pHeader->wHashTablePosHigh = 0;

        // Set proper block table positions
        ha->BlockTablePos.QuadPart = ha->HashTablePos.QuadPart +
                                     (ha->pHeader->dwHashTableSize * sizeof(TMPQHash));
        TempPos.QuadPart = ha->BlockTablePos.QuadPart - ha->MpqPos.QuadPart;
        ha->pHeader->dwBlockTablePos = TempPos.LowPart;
        ha->pHeader->wBlockTablePosHigh = (USHORT)TempPos.HighPart;

        // For now, we set extended block table positioon top zero unless we add enough
        // files to cause the archive size exceed 4 GB
        ha->ExtBlockTablePos.QuadPart = 0;

        // Clear all tables
        memset(ha->pBlockTable, 0, sizeof(TMPQBlock) * dwHashTableSize);
        memset(ha->pExtBlockTable, 0, sizeof(TMPQBlockEx) * dwHashTableSize);
        memset(ha->pHashTable, 0xFF, sizeof(TMPQHash) * dwHashTableSize);
    }

    // Write the MPQ header to the file
    if(nError == ERROR_SUCCESS)
    {
        DWORD dwHeaderSize = ha->pHeader->dwHeaderSize;

        BSWAP_TMPQHEADER(ha->pHeader);
        WriteFile(ha->hFile, ha->pHeader, dwHeaderSize, &dwTransferred, NULL);
        BSWAP_TMPQHEADER(ha->pHeader);
        
        if(dwTransferred != ha->pHeader->dwHeaderSize)
            nError = ERROR_DISK_FULL;

        ha->FilePointer.QuadPart = ha->MpqPos.QuadPart + dwTransferred;
        ha->MpqSize.QuadPart += dwTransferred;
    }

    // Create the internal listfile
    if(nError == ERROR_SUCCESS)
        nError = SListFileCreateListFile(ha);

    // Try to add the internal listfile
    if(nError == ERROR_SUCCESS)
        SFileAddListFile((HANDLE)ha, NULL);

    // Cleanup : If an error, delete all buffers and return
    if(nError != ERROR_SUCCESS)
    {
        FreeMPQArchive(ha);
        if(hFile != INVALID_HANDLE_VALUE)
            CloseHandle(hFile);
        SetLastError(nError);
    }
    
    // Return the values
    *phMPQ = (HANDLE)ha;
    return (nError == ERROR_SUCCESS);
}
开发者ID:1ATOM,项目名称:mangos,代码行数:101,代码来源:SFileCreateArchiveEx.cpp

示例10: pipe_read_line

/*
 * The runtime library's popen() on win32 does not work when being
 * called from a service when running on windows <= 2000, because
 * there is no stdin/stdout/stderr.
 *
 * Executing a command in a pipe and reading the first line from it
 * is all we need.
 */
static char *
pipe_read_line(char *cmd, char *line, int maxsize)
{
#ifndef WIN32
	FILE	   *pgver;

	/* flush output buffers in case popen does not... */
	fflush(stdout);
	fflush(stderr);

	errno = 0;
	if ((pgver = popen(cmd, "r")) == NULL)
	{
		perror("popen failure");
		return NULL;
	}

	errno = 0;
	if (fgets(line, maxsize, pgver) == NULL)
	{
		if (feof(pgver))
			fprintf(stderr, "no data was returned by command \"%s\"\n", cmd);
		else
			perror("fgets failure");
		pclose(pgver);			/* no error checking */
		return NULL;
	}

	if (pclose_check(pgver))
		return NULL;

	return line;
#else							/* WIN32 */

	SECURITY_ATTRIBUTES sattr;
	HANDLE		childstdoutrd,
				childstdoutwr,
				childstdoutrddup;
	PROCESS_INFORMATION pi;
	STARTUPINFO si;
	char	   *retval = NULL;

	sattr.nLength = sizeof(SECURITY_ATTRIBUTES);
	sattr.bInheritHandle = TRUE;
	sattr.lpSecurityDescriptor = NULL;

	if (!CreatePipe(&childstdoutrd, &childstdoutwr, &sattr, 0))
		return NULL;

	if (!DuplicateHandle(GetCurrentProcess(),
						 childstdoutrd,
						 GetCurrentProcess(),
						 &childstdoutrddup,
						 0,
						 FALSE,
						 DUPLICATE_SAME_ACCESS))
	{
		CloseHandle(childstdoutrd);
		CloseHandle(childstdoutwr);
		return NULL;
	}

	CloseHandle(childstdoutrd);

	ZeroMemory(&pi, sizeof(pi));
	ZeroMemory(&si, sizeof(si));
	si.cb = sizeof(si);
	si.dwFlags = STARTF_USESTDHANDLES;
	si.hStdError = childstdoutwr;
	si.hStdOutput = childstdoutwr;
	si.hStdInput = INVALID_HANDLE_VALUE;

	if (CreateProcess(NULL,
					  cmd,
					  NULL,
					  NULL,
					  TRUE,
					  0,
					  NULL,
					  NULL,
					  &si,
					  &pi))
	{
		/* Successfully started the process */
		char	   *lineptr;

		ZeroMemory(line, maxsize);

		/* Try to read at least one line from the pipe */
		/* This may require more than one wait/read attempt */
		for (lineptr = line; lineptr < line + maxsize - 1;)
		{
//.........这里部分代码省略.........
开发者ID:42penguins,项目名称:postgres,代码行数:101,代码来源:exec.c

示例11: goodB2GSink

/* goodB2G uses the BadSource with the GoodSink */
void goodB2GSink(vector<wchar_t *> dataVector)
{
    wchar_t * data = dataVector[2];
    {
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        char hashData[100] = HASH_INPUT;
        HCRYPTPROV hCryptProv = 0;
        HCRYPTHASH hHash = 0;
        HCRYPTKEY hKey = 0;
        do
        {
            BYTE payload[(100 - 1) * sizeof(wchar_t)]; /* same size as data except for NUL terminator */
            DWORD payloadBytes;
            /* Hex-decode the input string into raw bytes */
            payloadBytes = decodeHexWChars(payload, sizeof(payload), data);
            /* Wipe the hex string, to prevent it from being given to LogonUserW if
             * any of the crypto calls fail. */
            SecureZeroMemory(data, 100 * sizeof(wchar_t));
            /* Aquire a Context */
            if(!CryptAcquireContext(&hCryptProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, 0))
            {
                break;
            }
            /* Create hash handle */
            if(!CryptCreateHash(hCryptProv, CALG_SHA_256, 0, 0, &hHash))
            {
                break;
            }
            /* Hash the input string */
            if(!CryptHashData(hHash, (BYTE*)hashData, strlen(hashData), 0))
            {
                break;
            }
            /* Derive an AES key from the hash */
            if(!CryptDeriveKey(hCryptProv, CALG_AES_256, hHash, 0, &hKey))
            {
                break;
            }
            if(!CryptDecrypt(hKey, 0, 1, 0, payload, &payloadBytes))
            {
                break;
            }
            /* Copy back into data and NUL-terminate */
            memcpy(data, payload, payloadBytes);
            data[payloadBytes / sizeof(wchar_t)] = L'\0';
        }
        while (0);
        if (hKey)
        {
            CryptDestroyKey(hKey);
        }
        if (hHash)
        {
            CryptDestroyHash(hHash);
        }
        if (hCryptProv)
        {
            CryptReleaseContext(hCryptProv, 0);
        }
        /* FIX: Decrypt the password before using it for authentication  */
        if (LogonUserW(
                    username,
                    domain,
                    data,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}
开发者ID:gpwi970725,项目名称:testJuliet2,代码行数:80,代码来源:CWE256_Plaintext_Storage_of_Password__w32_wchar_t_72b.cpp

示例12: OBSExceptionHandler


//.........这里部分代码省略.........
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                frame.Params[0],
                frame.Params[1],
                frame.Params[2],
                frame.Params[3],
                p,
                frame.AddrPC.Offset));
        }
#else
        if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT))
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                symInfo->Name,
                fnOffset));
        }
        else
        {
            crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"),
                frame.AddrStack.Offset,
                frame.AddrPC.Offset,
                (DWORD)frame.Params[0],
                (DWORD)frame.Params[1],
                (DWORD)frame.Params[2],
                (DWORD)frame.Params[3],
                p,
                frame.AddrPC.Offset
                ));
        }
#endif

        crashDumpLog.FlushFileBuffers();
    }

    //generate a minidump if possible
    if (fnMiniDumpWriteDump)
    {
        HANDLE    hFile;

        tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s\\crashDumps\\OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i);

        hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (hFile != INVALID_HANDLE_VALUE)
        {
            miniInfo.ClientPointers = TRUE;
            miniInfo.ExceptionPointers = exceptionInfo;
            miniInfo.ThreadId = GetCurrentThreadId ();

            if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, MiniDumpWithIndirectlyReferencedMemory, &miniInfo, NULL, NULL))
            {
                crashDumpLog.WriteStr(FormattedString(TEXT("\r\nA minidump was saved to %s.\r\nPlease include this file when posting a crash report.\r\n"), dumpPath));
            }
            else
            {
                CloseHandle (hFile);
                DeleteFile (dumpPath);
            }
        }
    }
    else
    {
        crashDumpLog.WriteStr(TEXT("\r\nA minidump could not be created. Please check dbghelp.dll is present.\r\n"));
    }

    crashDumpLog.WriteStr("\r\nList of loaded modules:\r\n");
#ifdef _WIN64
    crashDumpLog.WriteStr("Base Address                      Module\r\n");
#else
    crashDumpLog.WriteStr("Base Address      Module\r\n");
#endif
    crashDumpLog.WriteStr(strModuleInfo);

    crashDumpLog.Close();

    LocalFree (symInfo);

    fnSymCleanup (hProcess);

    if (MessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES)
        ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT);

    FreeLibrary (hDbgHelp);

    //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash
    //and if we return we could end up invoking a second crash handler or other weird / annoying things
    //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode);
    return EXCEPTION_CONTINUE_SEARCH;
}
开发者ID:magicpriest,项目名称:OBS,代码行数:101,代码来源:CrashDumpHandler.cpp

示例13: ReadFromExeFile

int ReadFromExeFile(BYTE *filename) 
{
/* Reads data attached to the exe file and calls
   ProcessData(pointertodata, datasize).
   Return values:
	  * ERR_READFAILED - read from exe file had failed;
	  * ERR_BADFORMAT  - invalid format of the exe file;
	  * ERR_NOINFO     - no info was attached.
   If the data were read OK, it returns the return value of ProcessData.
*/
	printf("file= %s\n", filename);
#define ErrIf(a) if(a) goto HANDLE_BADFORMAT;
	BYTE buff[4096]; 
	DWORD read; BYTE* data;

	// Open exe file
	//GetModuleFileNameA(NULL, (CHAR*)buff, sizeof(buff));
	HANDLE hFile = CreateFileA((CHAR*)filename, GENERIC_READ, FILE_SHARE_READ,
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
	if(INVALID_HANDLE_VALUE == hFile) return ERR_READFAILED;
	if(!ReadFile(hFile, buff, sizeof(buff), &read, NULL)) goto HANDLE_READFAILED;
	IMAGE_DOS_HEADER* dosheader = (IMAGE_DOS_HEADER*)buff;
	ErrIf(dosheader->e_magic != IMAGE_DOS_SIGNATURE);
	ErrIf(ULONG(dosheader->e_lfanew) >= ULONG(sizeof(buff) - sizeof(IMAGE_NT_HEADERS32)));

	// Locate PE header
	IMAGE_NT_HEADERS32* header = (IMAGE_NT_HEADERS32*)(buff + dosheader->e_lfanew);
	ErrIf(header->Signature != IMAGE_NT_SIGNATURE);
	IMAGE_SECTION_HEADER* sectiontable =
		(IMAGE_SECTION_HEADER*)((BYTE*)header + sizeof(IMAGE_NT_HEADERS32));
	ErrIf((BYTE*)sectiontable >= buff + sizeof(buff));
	DWORD maxpointer = 0, exesize = 0;

	// For each section
	for(int i = 0; i < header->FileHeader.NumberOfSections; ++i) {
		if(sectiontable->PointerToRawData > maxpointer) {
			maxpointer = sectiontable->PointerToRawData;
			exesize = sectiontable->PointerToRawData + sectiontable->SizeOfRawData;
		}
		sectiontable++;
	}

	// Seek to the overlay
	DWORD filesize = GetFileSize(hFile, NULL);
	if(exesize == filesize) goto HANDLE_NOINFO;
	ErrIf(filesize == INVALID_FILE_SIZE || exesize > filesize);
	if(SetFilePointer(hFile, exesize, NULL, FILE_BEGIN) ==
		INVALID_SET_FILE_POINTER) goto HANDLE_READFAILED;
	data = (BYTE*)malloc(filesize - exesize + 8);
	if(!ReadFile(hFile, data, filesize - exesize, &read, NULL)) goto HANDLE_WITHFREE;
	CloseHandle(hFile);

	// Process the data
	int result = ProcessData(data, filesize - exesize);
	free(data);
	return result;
HANDLE_WITHFREE:
	free(data);
HANDLE_READFAILED:
	CloseHandle(hFile);
	return ERR_READFAILED;
HANDLE_BADFORMAT:
	CloseHandle(hFile);
	return ERR_BADFORMAT;
HANDLE_NOINFO:
	CloseHandle(hFile);
	return ERR_NOINFO;
#undef ErrIf
}
开发者ID:hidd3ncod3s,项目名称:dumpoverlay,代码行数:69,代码来源:dumpoverlay.cpp

示例14: CreateFileW

void starnt::dictionary::load(const std::wstring file)
{	
	if( !dict.empty())
		if(file == dict_file)
			return;
		else
			dict.clear();
	
	char* word;
	[&file, &word]()->void
	{	
		#if defined _WIN32
			HANDLE FileIn;
			FileIn = CreateFileW( file.c_str(),GENERIC_READ ,0,NULL,OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,NULL);
			if (FileIn == INVALID_HANDLE_VALUE) 
				return;
			LARGE_INTEGER len;
			GetFileSizeEx(FileIn, &len);
			word = new char[len.LowPart + 1];
			DWORD count;
			ReadFile(FileIn, word, len.LowPart, &count, NULL);
			if(count != len.LowPart)
				return;

			word[len.LowPart] = '\0';
			CloseHandle(FileIn);
		#else
			// nix version
		#endif
	}();

	//load individual words into strings
	std::pair<std::string, std::string> dict_entry;	
	char* wordtok;
	wordtok = strtok(word, "\n");
	for(int j = 0 ; wordtok != NULL ; j++ , wordtok = strtok(NULL, "\n"))
	{
		if(type == 1)
		{	// encode
			dict_entry.first = wordtok;		// the word
			transform(j, dict_entry.second);	// code
		}
		else
		{	//decode	
			transform(j, dict_entry.first);	// code
			dict_entry.second = wordtok;		// the word
		}
		dict.insert( dict_entry );	
	}



	// replace LF with \0
/*	for(size_t i=0; i < len ; i++)
	{
		while( (word[i] != '\n') && i < len)
			i++;
		word[i] = '\0';
	}

	// then load individual words into strings
	std::pair<std::string, std::string> dict_entry;

	dict_entry.first= &word[0];
	dict_entry.second = "a";
	dict.insert( dict_entry );
	
	for(int i = 2, j = 1 ; i < len ; i++,j++)
	{
		while(word[i] != '\0')
			i++;
		i++;
		if( i <len)
		{	
			dict_entry.first = &word[i];		// the word
			dict_entry.second = transform(j);	// code

			dict.insert( dict_entry );	
		}
		else
			break;
	}
*/

	delete [] word;

}
开发者ID:ksteinhaeuser,项目名称:starnt,代码行数:87,代码来源:dictionary.cpp

示例15: main


//.........这里部分代码省略.........
#ifndef __MINGW32__
	flv = mmap(NULL, filesize, PROT_READ, MAP_NOCORE | MAP_PRIVATE, fileno(fp_infile), 0);
	if(flv == MAP_FAILED) {
		fprintf(stderr, "Couldn't load %s (%s).\n", infile, strerror(errno));
		exit(1);
	}

#else
	HANDLE h = NULL;
	h = CreateFileMapping(fh_infile, NULL, PAGE_READONLY | SEC_COMMIT, 0, filesize,  NULL);
	if(h == NULL) {
		fprintf(stderr, "Couldn't create file mapping object %s. Error code: %d\n", infile, (int)GetLastError());
		exit(1);
	}
	flv = MapViewOfFile(h, FILE_MAP_READ, 0, 0, filesize);
	if(flv == NULL) {
		fprintf(stderr, "Couldn't load %s.\n", infile);
		exit(1);
	}
#endif

	// Simple check if the filee is a flv file
	if(strncmp(flv, "FLV", 3)) {
		fprintf(stderr, "The input file is not a FLV.\n");
		exit(1);
	}

	// Metadata initialisieren
	initFLVMetaData(creator, lastsecond, lastkeyframe);

	flvfileheader = (FLVFileHeader_t *)flv;

	// Die Position des 1. Tags im FLV bestimmen (Header + PrevTagSize0)
	streampos = FLV_UI32(flvfileheader->headersize) + 4;

	// Das FLV einlesen und Informationen fuer die Metatags extrahieren
	readFLVFirstPass(flv, streampos, filesize);

#ifndef __MINGW32__
	devnull = fopen("/dev/null", "wb");
#else
	devnull = fopen("nul", "wb");
#endif

	if(devnull == NULL) {
		fprintf(stderr, "Couldn't open NULL device.\n");
		exit(1);
	}

	// Die Groessen berechnen
	metadatasize = writeFLVMetaData(devnull);
	flvmetadata.lastsecondsize = writeFLVLastSecond(devnull, 0.0);
	flvmetadata.lastkeyframesize = writeFLVLastKeyframe(devnull);	// Not fully implemented, i.e. has no effect

	fclose(devnull);

	// Falls es Keyframes hat, muss ein 2. Durchgang fuer den Keyframeindex gemacht werden
	if(flvmetadata.hasKeyframes == 1) {
		readFLVSecondPass(flv, streampos, filesize);

		// Die Filepositions korrigieren
		for(i = 0; i < flvmetadata.keyframes; i++)
			flvmetadata.filepositions[i] += (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize);

		flvmetadata.lastkeyframelocation = flvmetadata.filepositions[flvmetadata.keyframes - 1];
	}

	// filesize = FLVFileHeader + PreviousTagSize0 + MetadataSize + DataSize
	flvmetadata.filesize = (double)(sizeof(FLVFileHeader_t) + 4 + metadatasize + flvmetadata.datasize);
	if(flvmetadata.hasLastSecond == 1)
		flvmetadata.filesize += (double)flvmetadata.lastsecondsize;

	if(outfile != NULL)
		writeFLV(fp_outfile, flv, streampos, filesize);

	if(xmloutfile != NULL)
		writeXMLMetadata(fp_xmloutfile, infile, outfile);

	// Some cleanup
#ifndef __MINGW32__
	munmap(flv, filesize);
	fclose(fp_infile);
#else
	UnmapViewOfFile(flv);
	CloseHandle(h);
	CloseHandle(fh_infile);
#endif

	// Remove the input file if it is the temporary file
	if(unlink_infile == 1)
		unlink(infile);

	if(fp_outfile != NULL && fp_outfile != stdout)
		fclose(fp_outfile);

	if(fp_xmloutfile != NULL && fp_xmloutfile != stdout)
		fclose(fp_xmloutfile);

	return 0;
}
开发者ID:danielbush,项目名称:fez,代码行数:101,代码来源:yamdi.c


注:本文中的CloseHandle函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。