本文整理汇总了C++中CreateFileW函数的典型用法代码示例。如果您正苦于以下问题:C++ CreateFileW函数的具体用法?C++ CreateFileW怎么用?C++ CreateFileW使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了CreateFileW函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: RTR3DECL
RTR3DECL(int) RTPathQueryInfoEx(const char *pszPath, PRTFSOBJINFO pObjInfo, RTFSOBJATTRADD enmAdditionalAttribs, uint32_t fFlags)
{
/*
* Validate input.
*/
AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
AssertReturn(*pszPath, VERR_INVALID_PARAMETER);
AssertPtrReturn(pObjInfo, VERR_INVALID_POINTER);
AssertMsgReturn( enmAdditionalAttribs >= RTFSOBJATTRADD_NOTHING
&& enmAdditionalAttribs <= RTFSOBJATTRADD_LAST,
("Invalid enmAdditionalAttribs=%p\n", enmAdditionalAttribs),
VERR_INVALID_PARAMETER);
AssertMsgReturn(RTPATH_F_IS_VALID(fFlags, 0), ("%#x\n", fFlags), VERR_INVALID_PARAMETER);
/*
* Query file info.
*/
WIN32_FILE_ATTRIBUTE_DATA Data;
PRTUTF16 pwszPath;
int rc = RTStrToUtf16(pszPath, &pwszPath);
if (RT_FAILURE(rc))
return rc;
if (!GetFileAttributesExW(pwszPath, GetFileExInfoStandard, &Data))
{
/* Fallback to FindFileFirst in case of sharing violation. */
if (GetLastError() == ERROR_SHARING_VIOLATION)
{
WIN32_FIND_DATAW FindData;
HANDLE hDir = FindFirstFileW(pwszPath, &FindData);
if (hDir == INVALID_HANDLE_VALUE)
{
rc = RTErrConvertFromWin32(GetLastError());
RTUtf16Free(pwszPath);
return rc;
}
FindClose(hDir);
Data.dwFileAttributes = FindData.dwFileAttributes;
Data.ftCreationTime = FindData.ftCreationTime;
Data.ftLastAccessTime = FindData.ftLastAccessTime;
Data.ftLastWriteTime = FindData.ftLastWriteTime;
Data.nFileSizeHigh = FindData.nFileSizeHigh;
Data.nFileSizeLow = FindData.nFileSizeLow;
}
else
{
rc = RTErrConvertFromWin32(GetLastError());
RTUtf16Free(pwszPath);
return rc;
}
}
/*
* Getting the information for the link target is a bit annoying and
* subject to the same access violation mess as above.. :/
*/
/** @todo we're too lazy wrt to error paths here... */
if ( (fFlags & RTPATH_F_FOLLOW_LINK)
&& (Data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
{
HANDLE hFinal = CreateFileW(pwszPath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (hFinal != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION FileData;
if (GetFileInformationByHandle(hFinal, &FileData))
{
Data.dwFileAttributes = FileData.dwFileAttributes;
Data.ftCreationTime = FileData.ftCreationTime;
Data.ftLastAccessTime = FileData.ftLastAccessTime;
Data.ftLastWriteTime = FileData.ftLastWriteTime;
Data.nFileSizeHigh = FileData.nFileSizeHigh;
Data.nFileSizeLow = FileData.nFileSizeLow;
}
CloseHandle(hFinal);
}
else if (GetLastError() != ERROR_SHARING_VIOLATION)
{
rc = RTErrConvertFromWin32(GetLastError());
RTUtf16Free(pwszPath);
return rc;
}
}
RTUtf16Free(pwszPath);
/*
* Setup the returned data.
*/
pObjInfo->cbObject = ((uint64_t)Data.nFileSizeHigh << 32)
| (uint64_t)Data.nFileSizeLow;
pObjInfo->cbAllocated = pObjInfo->cbObject;
Assert(sizeof(uint64_t) == sizeof(Data.ftCreationTime));
RTTimeSpecSetNtTime(&pObjInfo->BirthTime, *(uint64_t *)&Data.ftCreationTime);
//.........这里部分代码省略.........
示例2: cop_filemap_open
int cop_filemap_open(struct cop_filemap *map, const char *filename, unsigned flags)
{
DWORD faccess;
DWORD mapprotect;
DWORD mapaccess;
LARGE_INTEGER fsz;
LPWSTR wfn;
int fnlen;
if ((flags & COP_FILEMAP_FLAG_W) == 0) {
/* read only access */
faccess = GENERIC_READ;
mapprotect = PAGE_READONLY;
mapaccess = FILE_MAP_READ;
} else if ((flags & COP_FILEMAP_SHARED)) {
/* shared write access */
faccess = GENERIC_READ | GENERIC_WRITE;
mapprotect = PAGE_READWRITE;
mapaccess = FILE_MAP_WRITE;
} else {
/* unshared write access */
faccess = GENERIC_READ;
mapprotect = PAGE_READONLY;
mapaccess = FILE_MAP_COPY;
}
fnlen = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
if (fnlen == 0)
return -1;
wfn = malloc(sizeof(*wfn) * fnlen);
if (wfn == NULL)
return -1;
if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, wfn, fnlen) != fnlen) {
free(wfn);
return -1;
}
map->filehandle = CreateFileW(wfn, faccess, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (map->filehandle == INVALID_HANDLE_VALUE) {
free(wfn);
return -1;
}
free(wfn);
if (!GetFileSizeEx(map->filehandle, &fsz)) {
CloseHandle(map->filehandle);
return -1;
}
if (fsz.QuadPart > SIZE_MAX) {
CloseHandle(map->filehandle);
return -1;
}
map->size = (size_t)fsz.QuadPart;
map->maphandle = CreateFileMapping(map->filehandle, NULL, mapprotect, 0, 0, NULL);
if (map->maphandle == INVALID_HANDLE_VALUE) {
CloseHandle(map->filehandle);
return -1;
}
map->ptr = MapViewOfFile(map->maphandle, mapaccess, 0, 0, 0);
if (map->ptr == NULL) {
CloseHandle(map->maphandle);
CloseHandle(map->filehandle);
return -1;
}
return 0;
}
示例3: 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;
}
示例4: p_readlink
/*
* Parts of the The p_readlink function are heavily inspired by the php
* readlink function in link_win32.c
*
* Copyright (c) 1999 - 2012 The PHP Group. All rights reserved.
*
* For details of the PHP license see http://www.php.net/license/3_01.txt
*/
int p_readlink(const char *link, char *target, size_t target_len)
{
typedef DWORD (WINAPI *fpath_func)(HANDLE, LPWSTR, DWORD, DWORD);
static fpath_func pGetFinalPath = NULL;
HANDLE hFile;
DWORD dwRet;
git_win32_path link_w;
wchar_t* target_w;
int error = 0;
assert(link && target && target_len > 0);
/*
* Try to load the pointer to pGetFinalPath dynamically, because
* it is not available in platforms older than Vista
*/
if (pGetFinalPath == NULL) {
HMODULE module = GetModuleHandle("kernel32");
if (module != NULL)
pGetFinalPath = (fpath_func)GetProcAddress(module, "GetFinalPathNameByHandleW");
if (pGetFinalPath == NULL) {
giterr_set(GITERR_OS,
"'GetFinalPathNameByHandleW' is not available in this platform");
return -1;
}
}
git_win32_path_from_c(link_w, link);
hFile = CreateFileW(link_w, // file to open
GENERIC_READ, // open for reading
FILE_SHARE_READ, // share for reading
NULL, // default security
OPEN_EXISTING, // existing file only
FILE_FLAG_BACKUP_SEMANTICS, // normal file
NULL); // no attr. template
if (hFile == INVALID_HANDLE_VALUE) {
giterr_set(GITERR_OS, "Cannot open '%s' for reading", link);
return -1;
}
target_w = (wchar_t*)git__malloc(target_len * sizeof(wchar_t));
GITERR_CHECK_ALLOC(target_w);
dwRet = pGetFinalPath(hFile, target_w, (DWORD)target_len, 0x0);
if (dwRet == 0 ||
dwRet >= target_len ||
!WideCharToMultiByte(CP_UTF8, 0, target_w, -1, target,
(int)(target_len * sizeof(char)), NULL, NULL))
error = -1;
git__free(target_w);
CloseHandle(hFile);
if (error)
return error;
/* Skip first 4 characters if they are "\\?\" */
if (dwRet > 4 &&
target[0] == '\\' && target[1] == '\\' &&
target[2] == '?' && target[3] == '\\')
{
unsigned int offset = 4;
dwRet -= 4;
/* \??\UNC\ */
if (dwRet > 7 &&
target[4] == 'U' && target[5] == 'N' && target[6] == 'C')
{
offset += 2;
dwRet -= 2;
target[offset] = '\\';
}
memmove(target, target + offset, dwRet);
}
target[dwRet] = '\0';
return dwRet;
}
示例5: ProcessSoftwareUpdateCommand
/**
* Processes a software update command
*
* @param argc The number of arguments in argv
* @param argv The arguments normally passed to updater.exe
* argv[0] must be the path to updater.exe
* @return TRUE if the update was successful.
*/
BOOL
ProcessSoftwareUpdateCommand(DWORD argc, LPWSTR *argv)
{
BOOL result = TRUE;
if (argc < 3) {
LOG_WARN(("Not enough command line parameters specified. "
"Updating update.status."));
// We can only update update.status if argv[1] exists. argv[1] is
// the directory where the update.status file exists.
if (argc < 2 ||
!WriteStatusFailure(argv[1],
SERVICE_NOT_ENOUGH_COMMAND_LINE_ARGS)) {
LOG_WARN(("Could not write update.status service update failure. (%d)",
GetLastError()));
}
return FALSE;
}
WCHAR installDir[MAX_PATH] = {L'\0'};
if (!GetInstallationDir(argc, argv, installDir)) {
LOG_WARN(("Could not get the installation directory"));
if (!WriteStatusFailure(argv[1],
SERVICE_INSTALLDIR_ERROR)) {
LOG_WARN(("Could not write update.status for GetInstallationDir failure."));
}
return FALSE;
}
// Make sure the path to the updater to use for the update is local.
// We do this check to make sure that file locking is available for
// race condition security checks.
BOOL isLocal = FALSE;
if (!IsLocalFile(argv[0], isLocal) || !isLocal) {
LOG_WARN(("Filesystem in path %ls is not supported (%d)",
argv[0], GetLastError()));
if (!WriteStatusFailure(argv[1],
SERVICE_UPDATER_NOT_FIXED_DRIVE)) {
LOG_WARN(("Could not write update.status service update failure. (%d)",
GetLastError()));
}
return FALSE;
}
nsAutoHandle noWriteLock(CreateFileW(argv[0], GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, 0, NULL));
if (INVALID_HANDLE_VALUE == noWriteLock) {
LOG_WARN(("Could not set no write sharing access on file. (%d)",
GetLastError()));
if (!WriteStatusFailure(argv[1],
SERVICE_COULD_NOT_LOCK_UPDATER)) {
LOG_WARN(("Could not write update.status service update failure. (%d)",
GetLastError()));
}
return FALSE;
}
// Verify that the updater.exe that we are executing is the same
// as the one in the installation directory which we are updating.
// The installation dir that we are installing to is installDir.
WCHAR installDirUpdater[MAX_PATH + 1] = {L'\0'};
wcsncpy(installDirUpdater, installDir, MAX_PATH);
if (!PathAppendSafe(installDirUpdater, L"updater.exe")) {
LOG_WARN(("Install directory updater could not be determined."));
result = FALSE;
}
BOOL updaterIsCorrect;
if (result && !VerifySameFiles(argv[0], installDirUpdater,
updaterIsCorrect)) {
LOG_WARN(("Error checking if the updaters are the same.\n"
"Path 1: %ls\nPath 2: %ls", argv[0], installDirUpdater));
result = FALSE;
}
if (result && !updaterIsCorrect) {
LOG_WARN(("The updaters do not match, udpater will not run."));
result = FALSE;
}
if (result) {
LOG(("updater.exe was compared successfully to the installation directory"
" updater.exe."));
} else {
if (!WriteStatusFailure(argv[1],
SERVICE_UPDATER_COMPARE_ERROR)) {
LOG_WARN(("Could not write update.status updater compare failure."));
}
return FALSE;
}
// Check to make sure the udpater.exe module has the unique updater identity.
//.........这里部分代码省略.........
示例6: CryptCATOpen
/***********************************************************************
* CryptCATOpen ([email protected])
*/
HANDLE WINAPI CryptCATOpen(LPWSTR pwszFileName, DWORD fdwOpenFlags, HCRYPTPROV hProv,
DWORD dwPublicVersion, DWORD dwEncodingType)
{
HANDLE file, hmsg;
BYTE *buffer = NULL;
DWORD size, flags = OPEN_EXISTING;
struct cryptcat *cc;
TRACE("%s, %x, %lx, %x, %x\n", debugstr_w(pwszFileName), fdwOpenFlags,
hProv, dwPublicVersion, dwEncodingType);
if (!pwszFileName)
{
SetLastError(ERROR_INVALID_PARAMETER);
return INVALID_HANDLE_VALUE;
}
if (!dwEncodingType) dwEncodingType = X509_ASN_ENCODING | PKCS_7_ASN_ENCODING;
if (fdwOpenFlags & CRYPTCAT_OPEN_ALWAYS) flags |= OPEN_ALWAYS;
if (fdwOpenFlags & CRYPTCAT_OPEN_CREATENEW) flags |= CREATE_NEW;
file = CreateFileW(pwszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, flags, 0, NULL);
if (file == INVALID_HANDLE_VALUE) return INVALID_HANDLE_VALUE;
size = GetFileSize(file, NULL);
if (!(buffer = HeapAlloc(GetProcessHeap(), 0, size)))
{
CloseHandle(file);
SetLastError(ERROR_OUTOFMEMORY);
return INVALID_HANDLE_VALUE;
}
if (!(hmsg = CryptMsgOpenToDecode(dwEncodingType, 0, 0, hProv, NULL, NULL)))
{
CloseHandle(file);
HeapFree(GetProcessHeap(), 0, buffer);
return INVALID_HANDLE_VALUE;
}
if (!ReadFile(file, buffer, size, &size, NULL) || !CryptMsgUpdate(hmsg, buffer, size, TRUE))
{
CloseHandle(file);
HeapFree(GetProcessHeap(), 0, buffer);
CryptMsgClose(hmsg);
return INVALID_HANDLE_VALUE;
}
HeapFree(GetProcessHeap(), 0, buffer);
CloseHandle(file);
size = sizeof(DWORD);
if (!(cc = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*cc))))
{
CryptMsgClose(hmsg);
SetLastError(ERROR_OUTOFMEMORY);
return INVALID_HANDLE_VALUE;
}
cc->msg = hmsg;
cc->encoding = dwEncodingType;
if (CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_COUNT_PARAM, 0, &cc->attr_count, &size))
{
DWORD i, sum = 0;
BYTE *p;
for (i = 0; i < cc->attr_count; i++)
{
if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
{
CryptMsgClose(hmsg);
return INVALID_HANDLE_VALUE;
}
sum += size;
}
if (!(cc->attr = HeapAlloc(GetProcessHeap(), 0, sizeof(*cc->attr) * cc->attr_count + sum)))
{
CryptMsgClose(hmsg);
SetLastError(ERROR_OUTOFMEMORY);
return INVALID_HANDLE_VALUE;
}
p = (BYTE *)(cc->attr + cc->attr_count);
for (i = 0; i < cc->attr_count; i++)
{
if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, NULL, &size))
{
CryptMsgClose(hmsg);
HeapFree(GetProcessHeap(), 0, cc->attr);
return INVALID_HANDLE_VALUE;
}
if (!CryptMsgGetParam(hmsg, CMSG_ATTR_CERT_PARAM, i, p, &size))
{
CryptMsgClose(hmsg);
HeapFree(GetProcessHeap(), 0, cc->attr);
return INVALID_HANDLE_VALUE;
}
p += size;
}
cc->inner = decode_inner_content(hmsg, dwEncodingType, &cc->inner_len);
if (!cc->inner || !CryptSIPRetrieveSubjectGuid(pwszFileName, NULL, &cc->subject))
//.........这里部分代码省略.........
示例7: loc
bool LocateConverter::LocateUpdate(const wchar_t *locate, const wchar_t *patch, const wchar_t *path, bool compress/* = false */, OnProgress progress/* = NULL */)
{
LocateReader loc(locate);
if ( !loc.IsAvailable() ) return false;
const uint8_t *diff_buffer = 0;
PDIFFHEADER diff_header = 0;
HANDLE hfile = CreateFileW(patch, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(hfile!=INVALID_HANDLE_VALUE)
{
uint32_t file_length = GetFileSize(hfile, NULL);
HANDLE hfilemap = CreateFileMapping(hfile, NULL, PAGE_READONLY, 0, 0, NULL);
CloseHandle(hfile);
diff_buffer = (const uint8_t*) MapViewOfFile(hfilemap, FILE_MAP_READ, 0, 0, 0);
CloseHandle(hfilemap);
diff_header = (PDIFFHEADER)diff_buffer;
int data_size = file_length - sizeof(DIFFHEADER) - LZMA_PROPS_SIZE;
if( data_size<0 || diff_header->magic != DIFF_MAGIC || CRC32_MEM(diff_buffer, sizeof(DIFFHEADER) - 4)!=diff_header->crc32 )
{
UnmapViewOfFile((void*)diff_buffer);
return false;
}
else
{
uint32_t lzma_buffer_len = diff_header->size;
uint8_t *lzma_buffer = (uint8_t *)malloc(sizeof(DIFFHEADER) + lzma_buffer_len);
if( LzmaUncompress(lzma_buffer + sizeof(DIFFHEADER), &lzma_buffer_len, (unsigned char*)diff_header->data + LZMA_PROPS_SIZE, (uint32_t*)&data_size, (unsigned char*)diff_header->data, LZMA_PROPS_SIZE)==SZ_OK )
{
memcpy(lzma_buffer, diff_buffer, sizeof(DIFFHEADER));
UnmapViewOfFile((void*)diff_buffer);
diff_buffer = lzma_buffer;
diff_header = (PDIFFHEADER)diff_buffer;
diff_header->table1 += (uint32_t)diff_buffer;
diff_header->table2 += (uint32_t)diff_buffer;
}
else
{
free(lzma_buffer);
UnmapViewOfFile((void*)diff_buffer);
return false;
}
}
}
else
{
return false;
}
if ( loc.GetInfo()->count!=diff_header->total1 || loc.GetInfo()->time!=diff_header->time1 ) return false;
PDIFFITEM diffitem = diff_header->data;
LocateItem *Locate = (LocateItem *)malloc( diff_header->total2 * sizeof(LocateItem) );
uint32_t last_diff = ( diff_header->table1 - sizeof(DIFFHEADER) - (uint32_t)diff_buffer ) / sizeof(DIFFITEM) - 1;
uint32_t last_line = diff_header->total2 - 1;
uint32_t i = loc.GetInfo()->count;
for(; i>0; i--)
{
LocateItem *item = loc.GetItem(i);
if(i!=diffitem[last_diff].line)
{
Locate[last_line].begin_ip = item->begin_ip;
Locate[last_line].region = item->region;
Locate[last_line].address = item->address;
last_line--;
}
else
{
switch(diffitem[last_diff].method)
{
case INSERT:
//printf("INSERT %d %d\n", i, diffitem[last_diff-1].line);
Locate[last_line].begin_ip = diffitem[last_diff].begin_ip;
Locate[last_line].region = (const char*)( diffitem[last_diff].table1 + diff_header->table1 );
Locate[last_line].address = (const char*)( diffitem[last_diff].table2 + diff_header->table2 );
last_line--;
i++;
break;
case REMOVE:
//printf("REMOVE %d %d %d\n", i, diffitem[last_diff-1].line, diffitem[last_diff-2].line);
break;
case MODIFY:
Locate[last_line].begin_ip = item->begin_ip;
Locate[last_line].region = (const char*)( diffitem[last_diff].table1 + diff_header->table1 );
Locate[last_line].address = (const char*)( diffitem[last_diff].table2 + diff_header->table2 );
//printf("MODIFY %d %s %s\n", last_line+1, Locate[last_line].region, Locate[last_line].address);
//getchar();
last_line--;
break;
}
last_diff--;
}
//.........这里部分代码省略.........
示例8: verify
void* MemoryMappedFile::map(const char *filenameIn, unsigned long long &length, int options) {
verify( fd == 0 && len == 0 ); // can't open more than once
setFilename(filenameIn);
FileAllocator::get()->allocateAsap( filenameIn, length );
/* big hack here: Babble uses db names with colons. doesn't seem to work on windows. temporary perhaps. */
char filename[256];
strncpy(filename, filenameIn, 255);
filename[255] = 0;
{
size_t len = strlen( filename );
for ( size_t i=len-1; i>=0; i-- ) {
if ( filename[i] == '/' ||
filename[i] == '\\' )
break;
if ( filename[i] == ':' )
filename[i] = '_';
}
}
updateLength( filename, length );
{
DWORD createOptions = FILE_ATTRIBUTE_NORMAL;
if ( options & SEQUENTIAL )
createOptions |= FILE_FLAG_SEQUENTIAL_SCAN;
DWORD rw = GENERIC_READ | GENERIC_WRITE;
fd = CreateFileW(
toWideString(filename).c_str(),
rw, // desired access
FILE_SHARE_WRITE | FILE_SHARE_READ, // share mode
NULL, // security
OPEN_ALWAYS, // create disposition
createOptions , // flags
NULL); // hTempl
if ( fd == INVALID_HANDLE_VALUE ) {
DWORD dosError = GetLastError();
log() << "CreateFileW for " << filename
<< " failed with " << errnoWithDescription( dosError )
<< " (file size is " << length << ")"
<< " in MemoryMappedFile::map"
<< endl;
return 0;
}
}
mapped += length;
{
DWORD flProtect = PAGE_READWRITE; //(options & READONLY)?PAGE_READONLY:PAGE_READWRITE;
maphandle = CreateFileMappingW(fd, NULL, flProtect,
length >> 32 /*maxsizehigh*/,
(unsigned) length /*maxsizelow*/,
NULL/*lpName*/);
if ( maphandle == NULL ) {
DWORD dosError = GetLastError();
log() << "CreateFileMappingW for " << filename
<< " failed with " << errnoWithDescription( dosError )
<< " (file size is " << length << ")"
<< " in MemoryMappedFile::map"
<< endl;
close();
fassertFailed( 16225 );
}
}
void *view = 0;
{
stdx::lock_guard<stdx::mutex> lk(mapViewMutex);
DWORD access = ( options & READONLY ) ? FILE_MAP_READ : FILE_MAP_ALL_ACCESS;
int current_retry = 0;
while (true) {
LPVOID thisAddress = getNextMemoryMappedFileLocation(length);
view = MapViewOfFileEx(
maphandle, // file mapping handle
access, // access
0, 0, // file offset, high and low
0, // bytes to map, 0 == all
thisAddress); // address to place file
if (view == 0) {
DWORD dosError = GetLastError();
++current_retry;
// If we failed to allocate a memory mapped file, try again in case we picked
// an address that Windows is also trying to use for some other VM allocations
if (dosError == ERROR_INVALID_ADDRESS && current_retry < 5) {
continue;
}
#ifndef _WIN64
// Warn user that if they are running a 32-bit app on 64-bit Windows
if (dosError == ERROR_NOT_ENOUGH_MEMORY) {
BOOL wow64Process;
BOOL retWow64 = IsWow64Process(GetCurrentProcess(), &wow64Process);
if (retWow64 && wow64Process) {
//.........这里部分代码省略.........
示例9: bad
void bad()
{
wchar_t * data;
wchar_t * *dataPtr1 = &data;
wchar_t * *dataPtr2 = &data;
wchar_t dataBuffer[FILENAME_MAX] = L"";
data = dataBuffer;
{
wchar_t * data = *dataPtr1;
{
#ifdef _WIN32
WSADATA wsaData;
int wsaDataInit = 0;
#endif
int recvResult;
struct sockaddr_in service;
wchar_t *replace;
SOCKET listenSocket = INVALID_SOCKET;
SOCKET acceptSocket = INVALID_SOCKET;
size_t dataLen = wcslen(data);
do
{
#ifdef _WIN32
if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
{
break;
}
wsaDataInit = 1;
#endif
/* POTENTIAL FLAW: Read data using a listen socket */
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
break;
}
memset(&service, 0, sizeof(service));
service.sin_family = AF_INET;
service.sin_addr.s_addr = INADDR_ANY;
service.sin_port = htons(TCP_PORT);
if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
{
break;
}
if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
{
break;
}
acceptSocket = accept(listenSocket, NULL, NULL);
if (acceptSocket == SOCKET_ERROR)
{
break;
}
/* Abort on error or the connection was closed */
recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (FILENAME_MAX - dataLen - 1), 0);
if (recvResult == SOCKET_ERROR || recvResult == 0)
{
break;
}
/* Append null terminator */
data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
/* Eliminate CRLF */
replace = wcschr(data, L'\r');
if (replace)
{
*replace = L'\0';
}
replace = wcschr(data, L'\n');
if (replace)
{
*replace = L'\0';
}
}
while (0);
if (listenSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(listenSocket);
}
if (acceptSocket != INVALID_SOCKET)
{
CLOSE_SOCKET(acceptSocket);
}
#ifdef _WIN32
if (wsaDataInit)
{
WSACleanup();
}
#endif
}
*dataPtr1 = data;
}
{
wchar_t * data = *dataPtr2;
{
HANDLE hFile;
/* POTENTIAL FLAW: Possibly creating and opening a file without validating the file name or path */
hFile = CreateFileW(data,
(GENERIC_WRITE|GENERIC_READ),
0,
NULL,
OPEN_ALWAYS,
//.........这里部分代码省略.........
开发者ID:maurer,项目名称:tiamat,代码行数:101,代码来源:CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_w32CreateFile_32.cpp
示例10: CheckNull
HRESULT CFileWatcher::WatchFile(PCWSTR fileName, FileModifiedCallback callback, void* data)
{
HRESULT hr;
WatchedFile* file;
WatchedDirectory* directory;
WatchedDirectory* newDirectory;
WCHAR fileOnly[_MAX_FNAME];
WCHAR ext[_MAX_EXT];
WCHAR* directoryName = NULL;
DWORD fileNameLength;
DWORD fileNameOnlyLength;
DWORD directoryLength;
WIN32_FILE_ATTRIBUTE_DATA attributes;
CheckNull(callback);
CheckNull(fileName);
fileNameLength = wcslen(fileName);
// allocate new WatchedFile, get snapshot of the last write time
ErrorIf(NULL == (file = new WatchedFile), ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(file, sizeof WatchedFile);
file->callback = callback;
file->data = data;
ErrorIf(!GetFileAttributesExW(fileName, GetFileExInfoStandard, &attributes), GetLastError());
memcpy(&file->lastWrite, &attributes.ftLastWriteTime, sizeof attributes.ftLastWriteTime);
// create and normalize a copy of directory name and file name
ErrorIf(0 != _wsplitpath_s(fileName, NULL, 0, NULL, 0, fileOnly, _MAX_FNAME, ext, _MAX_EXT), ERROR_INVALID_PARAMETER);
fileNameOnlyLength = wcslen(fileOnly) + wcslen(ext);
directoryLength = fileNameLength - fileNameOnlyLength;
ErrorIf(NULL == (directoryName = new WCHAR[directoryLength + 8]), ERROR_NOT_ENOUGH_MEMORY); // pessimistic length after normalization with prefix \\?\UNC\
ErrorIf(NULL == (file->fileName = new WCHAR[fileNameLength + 1]), ERROR_NOT_ENOUGH_MEMORY);
wcscpy(file->fileName, fileName);
if (fileNameLength > 8 && 0 == memcmp(fileName, L"\\\\?\\UNC\\", 8 * sizeof WCHAR))
{
// normalized UNC path
file->unc = TRUE;
memcpy(directoryName, fileName, directoryLength * sizeof WCHAR);
directoryName[directoryLength] = L'\0';
}
else if (fileNameLength > 4 && 0 == memcmp(fileName, L"\\\\?\\", 4 * sizeof WCHAR))
{
// normalized local file
file->unc = FALSE;
memcpy(directoryName, fileName, directoryLength * sizeof WCHAR);
directoryName[directoryLength] = L'\0';
}
else if (fileNameLength > 2 && 0 == memcmp(fileName, L"\\\\", 2 * sizeof(WCHAR)))
{
// not normalized UNC path
file->unc = TRUE;
wcscpy(directoryName, L"\\\\?\\UNC\\");
memcpy(directoryName + 8, fileName + 2, (directoryLength - 2) * sizeof WCHAR);
directoryName[8 + directoryLength - 2] = L'\0';
}
else
{
// not normalized local file
file->unc = FALSE;
wcscpy(directoryName, L"\\\\?\\");
memcpy(directoryName + 4, fileName, directoryLength * sizeof WCHAR);
directoryName[4 + directoryLength] = L'\0';
}
// find matching directory watcher entry
directory = this->directories;
while (NULL != directory)
{
if (0 == wcscmp(directory->directoryName, directoryName))
{
delete [] directoryName;
directoryName = NULL;
break;
}
directory = directory->next;
}
// if directory watcher not found, create one
if (NULL == directory)
{
ErrorIf(NULL == (newDirectory = new WatchedDirectory), ERROR_NOT_ENOUGH_MEMORY);
RtlZeroMemory(newDirectory, sizeof WatchedDirectory);
newDirectory->directoryName = directoryName;
directoryName = NULL;
newDirectory->files = file;
ErrorIf(INVALID_HANDLE_VALUE == (newDirectory->watchHandle = CreateFileW(
newDirectory->directoryName,
FILE_LIST_DIRECTORY,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL,
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED,
NULL)),
//.........这里部分代码省略.........
示例11: sizeof
bool FileSystem::openAndSeekFileSharedRead(QFile *file, QString *errorOrNull, qint64 seek)
{
QString errorDummy;
// avoid many if (errorOrNull) later.
QString &error = errorOrNull ? *errorOrNull : errorDummy;
error.clear();
#ifdef Q_OS_WIN
//
// The following code is adapted from Qt's QFSFileEnginePrivate::nativeOpen()
// by including the FILE_SHARE_DELETE share mode.
//
// Enable full sharing.
DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
int accessRights = GENERIC_READ;
DWORD creationDisp = OPEN_EXISTING;
// Create the file handle.
SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE };
QString fName = longWinPath(file->fileName());
HANDLE fileHandle = CreateFileW(
(const wchar_t *)fName.utf16(),
accessRights,
shareMode,
&securityAtts,
creationDisp,
FILE_ATTRIBUTE_NORMAL,
NULL);
// Bail out on error.
if (fileHandle == INVALID_HANDLE_VALUE) {
error = qt_error_string();
return false;
}
// Convert the HANDLE to an fd and pass it to QFile's foreign-open
// function. The fd owns the handle, so when QFile later closes
// the fd the handle will be closed too.
int fd = _open_osfhandle((intptr_t)fileHandle, _O_RDONLY);
if (fd == -1) {
error = "could not make fd from handle";
return false;
}
if (!file->open(fd, QIODevice::ReadOnly, QFile::AutoCloseHandle)) {
error = file->errorString();
return false;
}
// Seek to the right spot
LARGE_INTEGER *li = reinterpret_cast<LARGE_INTEGER *>(&seek);
DWORD newFilePointer = SetFilePointer(fileHandle, li->LowPart, &li->HighPart, FILE_BEGIN);
if (newFilePointer == 0xFFFFFFFF && GetLastError() != NO_ERROR) {
error = qt_error_string();
return false;
}
return true;
#else
if (!file->open(QFile::ReadOnly)) {
error = file->errorString();
return false;
}
if (!file->seek(seek)) {
error = file->errorString();
return false;
}
return true;
#endif
}
示例12: create_bob_txt
bool create_bob_txt() {
wchar_t *buf = NULL;
uint32_t buflen = 0;
buflen = GetCurrentDirectoryW(buflen, buf);
if (buflen == 0) {
printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError());
return false;
}
buf = (PWSTR)malloc(sizeof(WCHAR)*buflen);
if (GetCurrentDirectoryW(buflen, buf) == 0) {
printf("[error] GetCurrentDirectoryW() failed!!! gle = 0x%08x\n", GetLastError());
free(buf);
return false;
}
// current directory\\bob.txt 생성
wchar_t file_name[260];
if (!SUCCEEDED(StringCbPrintfW(
file_name,
sizeof(file_name),
L"%ws\\bob.txt",
buf))) {
printf("[error] can not create bob.txt\n");
free(buf);
return false;
}
free(buf);
buf = NULL;
if (is_file_existsW(file_name)) {
DeleteFileW(file_name);
}
// 파일 생성
HANDLE file_handle = CreateFileW(
file_name,
GENERIC_WRITE,
FILE_SHARE_READ,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
/////////////////////////////////////////////////////////
DWORD numberOfBytesWritten;
int result;
unsigned char mark[3];
mark[0] = 0xEF;
mark[1] = 0xBB;
// UTF-8
mark[2] = 0xBF;
wchar_t strUnicode[256] = L"안녕하세요 굳 굳굳 HelloWorld";
char strUtf8[256] = { 0, };
if (file_handle == INVALID_HANDLE_VALUE) {
printf("[error] can not CreateFile, gle=0x%08x\n", GetLastError());
return false;
}
int nlen = WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), NULL, 0, NULL, NULL);
WideCharToMultiByte(CP_UTF8, 0, strUnicode, lstrlenW(strUnicode), strUtf8, nlen, NULL, NULL);
result = WriteFile(file_handle, &mark, 3, &numberOfBytesWritten, NULL);
result = WriteFile(file_handle, strUtf8, strlen(strUtf8), &numberOfBytesWritten, NULL);
// bob.txt -> bob2.txt 파일 복사
LPCWSTR file_name2 = L"C:\\Users\\kahissa\\Documents\\Visual Studio 2013\\Projects\\Console_test1\\bob2.txt";
CopyFile(file_name, file_name2, false);
// bob2.txt 파일 내용 읽기
char readBuf[256] = { 0, };
DWORD dwRead = 0;
BOOL readOK;
HANDLE file_handle2 = CreateFileW(file_name2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file_handle2 == INVALID_HANDLE_VALUE) {
printf("[error] can not file open, gle=0x%08x\n", GetLastError());
}
readOK = ReadFile(file_handle2, readBuf, 256, &dwRead, NULL); // 파일 내용 읽어서 rBuf에 저장
if (readOK && dwRead == 0)
printf("[error] can not read file, gle=0x%08x\n", GetLastError());
//readBuf에 UTF8 적용
int len = MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), NULL, NULL);
wchar_t MultiByte[256] = { 0, };
// UTF8 -> 유니코드
MultiByteToWideChar(CP_UTF8, 0, readBuf, strlen(readBuf), MultiByte, len);
char MultiByte2[256] = { 0, };
//.........这里部分代码省略.........
示例13: main
//.........这里部分代码省略.........
"[%u]\n", GetLastError());
}
if(!DeleteFile(sBadFilePath))
{
Trace("CreateFileA: Call to DeleteFile Failed with ErrorCode "
"[%u]\n", GetLastError());
}
}
/*............. Test CreateFileW..................................*/
/* test with an invalid file name */
hFile = CreateFileW(wBadFileName,
GENERIC_READ, /* open for reading */
FILE_SHARE_READ, /* share for reading */
NULL, /* no security */
OPEN_EXISTING, /* existing file only */
FILE_ATTRIBUTE_NORMAL, /* normal file */
NULL); /* no attr. template */
if (hFile == INVALID_HANDLE_VALUE)
{
if(GetLastError() != ERROR_FILE_NOT_FOUND)
{
Trace("CreateFileW: calling GetLastError() returned [%u] "
"while it should return [%u] for a bad filename\n",
GetLastError(), ERROR_FILE_NOT_FOUND);
testPass = FALSE;
}
示例14: ThreadFunc
//.........这里部分代码省略.........
urlComponents.dwSchemeLength = urlLength + 1;
urlComponents.lpszScheme = (LPWSTR)malloc(urlComponents.dwSchemeLength * sizeof(WCHAR));
urlComponents.dwHostNameLength = urlLength + 1;
urlComponents.lpszHostName = (LPWSTR)malloc(urlComponents.dwHostNameLength * sizeof(WCHAR));
if(!InternetCrackUrlW(AppInfo->szUrlDownload, urlLength+1, ICU_DECODE | ICU_ESCAPE, &urlComponents))
goto end;
if(urlComponents.nScheme == INTERNET_SCHEME_HTTP || urlComponents.nScheme == INTERNET_SCHEME_HTTPS)
HttpQueryInfo(hFile, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &dwContentLen, &dwStatus, 0);
if(urlComponents.nScheme == INTERNET_SCHEME_FTP)
dwContentLen = FtpGetFileSize(hFile, &dwStatus);
#ifdef USE_CERT_PINNING
/* are we using HTTPS to download the RAPPS update package? check if the certificate is original */
if ((urlComponents.nScheme == INTERNET_SCHEME_HTTPS) &&
(wcscmp(AppInfo->szUrlDownload, APPLICATION_DATABASE_URL) == 0) &&
(!CertIsValid(hOpen, urlComponents.lpszHostName)))
{
WCHAR szMsgText[MAX_STR_LEN];
if (!LoadStringW(hInst, IDS_CERT_DOES_NOT_MATCH, szMsgText, sizeof(szMsgText) / sizeof(WCHAR)))
goto end;
MessageBoxW(Dlg, szMsgText, NULL, MB_OK | MB_ICONERROR);
goto end;
}
#endif
free(urlComponents.lpszScheme);
free(urlComponents.lpszHostName);
hOut = CreateFileW(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, 0, NULL);
if (hOut == INVALID_HANDLE_VALUE)
goto end;
do
{
if (!InternetReadFile(hFile, lpBuffer, _countof(lpBuffer), &dwBytesRead))
{
WCHAR szMsgText[MAX_STR_LEN];
if (!LoadStringW(hInst, IDS_INTERRUPTED_DOWNLOAD, szMsgText, _countof(szMsgText)))
goto end;
MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
goto end;
}
if (!WriteFile(hOut, &lpBuffer[0], dwBytesRead, &dwBytesWritten, NULL))
{
WCHAR szMsgText[MAX_STR_LEN];
if (!LoadStringW(hInst, IDS_UNABLE_TO_WRITE, szMsgText, _countof(szMsgText)))
goto end;
MessageBoxW(hMainWnd, szMsgText, NULL, MB_OK | MB_ICONERROR);
goto end;
}
dwCurrentBytesRead += dwBytesRead;
dl->OnProgress(dwCurrentBytesRead, dwContentLen, 0, AppInfo->szUrlDownload);
}
while (dwBytesRead && !bCancelled);
CloseHandle(hOut);
示例15: osl_createPipe
//.........这里部分代码省略.........
pSecAttr = rtl_allocateMemory(sizeof(SECURITY_ATTRIBUTES));
pSecAttr->nLength = sizeof(SECURITY_ATTRIBUTES);
pSecAttr->lpSecurityDescriptor = pSecDesc;
pSecAttr->bInheritHandle = TRUE;
}
}
rtl_uString_assign(&temp, name);
rtl_uString_newConcat(&name, temp, strPipeName);
/* alloc memory */
pPipe= __osl_createPipeImpl();
osl_atomic_increment(&(pPipe->m_Reference));
/* build system pipe name */
rtl_uString_assign(&temp, path);
rtl_uString_newConcat(&path, temp, name);
rtl_uString_release(temp);
temp = NULL;
if (Options & osl_Pipe_CREATE)
{
SetLastError( ERROR_SUCCESS );
pPipe->m_NamedObject = CreateMutexW( NULL, FALSE, name->buffer );
if ( pPipe->m_NamedObject != INVALID_HANDLE_VALUE && pPipe->m_NamedObject != NULL )
{
if ( GetLastError() != ERROR_ALREADY_EXISTS )
{
pPipe->m_Security = pSecAttr;
rtl_uString_assign(&pPipe->m_Name, name);
/* try to open system pipe */
pPipe->m_File = CreateNamedPipeW(
path->buffer,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
PIPE_WAIT | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
PIPE_UNLIMITED_INSTANCES,
4096, 4096,
NMPWAIT_WAIT_FOREVER,
pPipe->m_Security);
if (pPipe->m_File != INVALID_HANDLE_VALUE)
{
rtl_uString_release( name );
rtl_uString_release( path );
return pPipe;
}
}
else
{
CloseHandle( pPipe->m_NamedObject );
pPipe->m_NamedObject = INVALID_HANDLE_VALUE;
}
}
}
else
{
BOOL fPipeAvailable;
do
{
/* free instance should be available first */
fPipeAvailable = WaitNamedPipeW(path->buffer, NMPWAIT_WAIT_FOREVER);
/* first try to open system pipe */
if ( fPipeAvailable )
{
pPipe->m_File = CreateFileW(
path->buffer,
GENERIC_READ|GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if ( pPipe->m_File != INVALID_HANDLE_VALUE )
{
// We got it !
rtl_uString_release( name );
rtl_uString_release( path );
return (pPipe);
}
else
{
// Pipe instance maybe catched by another client -> try again
}
}
} while ( fPipeAvailable );
}
/* if we reach here something went wrong */
__osl_destroyPipeImpl(pPipe);
return NULL;
}