voidpf ZCALLBACK win32_open64_file_func (voidpf opaque,const void* filename,int mode) { const char* mode_fopen = NULL; DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; HANDLE hFile = NULL; win32_translate_open_mode(mode,&dwDesiredAccess,&dwCreationDisposition,&dwShareMode,&dwFlagsAndAttributes); #ifdef IOWIN32_USING_WINRT_API #ifdef UNICODE if ((filename!=NULL) && (dwDesiredAccess != 0)) hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); #else if ((filename!=NULL) && (dwDesiredAccess != 0)) { WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; MultiByteToWideChar(CP_ACP,0,(const char*)filename,-1,filenameW,FILENAME_MAX + 0x200); hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); } #endif #else if ((filename!=NULL) && (dwDesiredAccess != 0)) hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); #endif return win32_build_iowin(hFile); }
voidpf ZCALLBACK win32_open64_file_func (voidpf opaque, const void* filename, int mode) { DWORD dwDesiredAccess,dwCreationDisposition,dwShareMode,dwFlagsAndAttributes ; HANDLE hFile = NULL; WIN32FILE_IOWIN *iowin = NULL; win32_translate_open_mode(mode, &dwDesiredAccess, &dwCreationDisposition, &dwShareMode, &dwFlagsAndAttributes); if ((filename != NULL) && (dwDesiredAccess != 0)) { #ifdef IOWIN32_USING_WINRT_API #ifdef UNICODE hFile = CreateFile2((LPCTSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); #else WCHAR filenameW[FILENAME_MAX + 0x200 + 1]; MultiByteToWideChar(CP_ACP, 0, (const char*)filename, -1, filenameW, FILENAME_MAX + 0x200); hFile = CreateFile2(filenameW, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); #endif #else hFile = CreateFile((LPCTSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); #endif } iowin = win32_build_iowin(hFile); if (iowin == NULL) return NULL; iowin->filenameLength = _tcslen(filename) + 1; iowin->filename = (void*)malloc(iowin->filenameLength * sizeof(TCHAR)); _tcsncpy(iowin->filename, filename, iowin->filenameLength); return iowin; }
LWS_VISIBLE lws_fop_fd_t _lws_plat_file_open(const struct lws_plat_file_ops *fops, const char *filename, const char *vpath, lws_fop_flags_t *flags) { HANDLE ret; WCHAR buf[MAX_PATH]; lws_fop_fd_t fop_fd; FILE_STANDARD_INFO fInfo = {0}; MultiByteToWideChar(CP_UTF8, 0, filename, -1, buf, LWS_ARRAY_SIZE(buf)); #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0602 // Windows 8 (minimum when UWP_ENABLED, but can be used in Windows builds) CREATEFILE2_EXTENDED_PARAMETERS extParams = {0}; extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; if (((*flags) & 7) == _O_RDONLY) { ret = CreateFile2(buf, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, &extParams); } else { ret = CreateFile2(buf, GENERIC_WRITE, 0, CREATE_ALWAYS, &extParams); } #else if (((*flags) & 7) == _O_RDONLY) { ret = CreateFileW(buf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); } else { ret = CreateFileW(buf, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); } #endif if (ret == LWS_INVALID_FILE) goto bail; fop_fd = malloc(sizeof(*fop_fd)); if (!fop_fd) goto bail; fop_fd->fops = fops; fop_fd->fd = ret; fop_fd->filesystem_priv = NULL; /* we don't use it */ fop_fd->flags = *flags; fop_fd->len = 0; if(GetFileInformationByHandleEx(ret, FileStandardInfo, &fInfo, sizeof(fInfo))) fop_fd->len = fInfo.EndOfFile.QuadPart; fop_fd->pos = 0; return fop_fd; bail: return NULL; }
voidpf ZCALLBACK win32_open64_file_funcW (voidpf opaque,const void* filename,int mode) { DWORD dwDesiredAccess, dwCreationDisposition, dwShareMode, dwFlagsAndAttributes; HANDLE hFile = NULL; WIN32FILE_IOWIN *iowin = NULL; win32_translate_open_mode(mode, &dwDesiredAccess, &dwCreationDisposition, &dwShareMode, &dwFlagsAndAttributes); if ((filename != NULL) && (dwDesiredAccess != 0)) { #ifdef IOWIN32_USING_WINRT_API hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); #else hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); #endif } iowin = win32_build_iowin(hFile); if (iowin == NULL) return NULL; if (iowin->filename == NULL) { iowin->filenameLength = wcslen(filename) + 1; iowin->filename = (void*)malloc(iowin->filenameLength * sizeof(WCHAR)); wcsncpy(iowin->filename, filename, iowin->filenameLength); } return iowin; }
JsErrorCode LoadByteCode(const wchar_t* szPath, BYTE** pData, HANDLE* hFile, HANDLE* hMap) { *pData = nullptr; *hFile = CreateFile2(szPath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, OPEN_EXISTING, nullptr); if (*hFile == INVALID_HANDLE_VALUE) { return JsErrorFatal; } *hMap = CreateFileMapping(*hFile, nullptr, PAGE_READWRITE | SEC_RESERVE, 0, 0, L"ReactNativeMapping"); if (*hMap == NULL) { CloseHandle(*hFile); return JsErrorFatal; } *pData = (BYTE*)MapViewOfFile(*hMap, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (*pData == NULL) { CloseHandle(*hMap); CloseHandle(*hFile); return JsErrorFatal; } return JsNoError; }
static HANDLE _win32_create_temp_w(_zip_source_win32_read_file_t *ctx, void **temp, zip_uint32_t value, PSECURITY_ATTRIBUTES sa) { int len; len = wcslen((const wchar_t *)ctx->fname) + 10; if (*temp == NULL) { if ((*temp = malloc(sizeof(wchar_t) * len)) == NULL) { zip_error_set(&ctx->error, ZIP_ER_MEMORY, 0); return INVALID_HANDLE_VALUE; } } if (_snwprintf((wchar_t *)*temp, len, L"%s.%08x", (const wchar_t *)ctx->fname, value) != len - 1) { return INVALID_HANDLE_VALUE; } #ifdef WINRT CREATEFILE2_EXTENDED_PARAMETERS extParams = { 0 }; extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY; extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; extParams.dwSize = sizeof(extParams); extParams.hTemplateFile = NULL; extParams.lpSecurityAttributes = NULL; return CreateFile2((const wchar_t *)*temp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, CREATE_NEW, &extParams); #else return CreateFileW((const wchar_t *)*temp, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, sa, CREATE_NEW, FILE_ATTRIBUTE_NORMAL | FILE_ATTRIBUTE_TEMPORARY, NULL); #endif }
static void *doOpen(const char *fname, DWORD mode, DWORD creation, int rdonly) { HANDLE fileh; WinApiFile *retval; WCHAR *wfname; UTF8_TO_UNICODE_STACK_MACRO(wfname, fname); BAIL_IF_MACRO(!wfname, PHYSFS_ERR_OUT_OF_MEMORY, NULL); //fileh = CreateFileW(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, creation, FILE_ATTRIBUTE_NORMAL, NULL); fileh = CreateFile2(wfname, mode, FILE_SHARE_READ | FILE_SHARE_WRITE, creation, NULL); __PHYSFS_smallFree(wfname); BAIL_IF_MACRO(fileh == INVALID_HANDLE_VALUE, errcodeFromWinApi(), NULL); retval = (WinApiFile *)allocator.Malloc(sizeof(WinApiFile)); if (!retval) { CloseHandle(fileh); BAIL_MACRO(PHYSFS_ERR_OUT_OF_MEMORY, NULL); } /* if */ retval->readonly = rdonly; retval->handle = fileh; return retval; } /* doOpen */
HANDLE WINAPI flac_internal_CreateFile_utf8(const char *lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile) { #if _MSC_VER > 1900 && WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) wchar_t *wname; HANDLE handle = INVALID_HANDLE_VALUE; if ((wname = wchar_from_utf8(lpFileName)) != NULL) { handle = CreateFile2(wname, dwDesiredAccess, dwShareMode, CREATE_ALWAYS, NULL); free(wname); } return handle; #else if (!utf8_filenames) { return CreateFileA(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } else { wchar_t *wname; HANDLE handle = INVALID_HANDLE_VALUE; if ((wname = wchar_from_utf8(lpFileName)) != NULL) { handle = CreateFileW(wname, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); free(wname); } return handle; } #endif }
HANDLE WINAPI_DECL CreateFileW( _In_ LPCWSTR lpFileName, _In_ DWORD dwDesiredAccess, _In_ DWORD dwShareMode, _In_opt_ LPSECURITY_ATTRIBUTES lpSecurityAttributes, _In_ DWORD dwCreationDisposition, _In_ DWORD dwFlagsAndAttributes, _In_opt_ HANDLE hTemplateFile ) { CREATEFILE2_EXTENDED_PARAMETERS createExParams; createExParams.dwSize = sizeof(createExParams); createExParams.dwFileAttributes = dwFlagsAndAttributes; createExParams.dwFileFlags = 0; createExParams.dwSecurityQosFlags = 0; createExParams.lpSecurityAttributes = lpSecurityAttributes; createExParams.hTemplateFile = hTemplateFile; HANDLE hFile = CreateFile2( lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, &createExParams); return hFile; }
QT_BEGIN_NAMESPACE QLockFile::LockError QLockFilePrivate::tryLock_sys() { const QFileSystemEntry fileEntry(fileName); // When writing, allow others to read. // When reading, QFile will allow others to read and write, all good. // Adding FILE_SHARE_DELETE would allow forceful deletion of stale files, // but Windows doesn't allow recreating it while this handle is open anyway, // so this would only create confusion (can't lock, but no lock file to read from). const DWORD dwShareMode = FILE_SHARE_READ; #ifndef Q_OS_WINRT SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE }; HANDLE fh = CreateFile((const wchar_t*)fileEntry.nativeFilePath().utf16(), GENERIC_WRITE, dwShareMode, &securityAtts, CREATE_NEW, // error if already exists FILE_ATTRIBUTE_NORMAL, NULL); #else // !Q_OS_WINRT HANDLE fh = CreateFile2((const wchar_t*)fileEntry.nativeFilePath().utf16(), GENERIC_WRITE, dwShareMode, CREATE_NEW, // error if already exists NULL); #endif // Q_OS_WINRT if (fh == INVALID_HANDLE_VALUE) { const DWORD lastError = GetLastError(); switch (lastError) { case ERROR_SHARING_VIOLATION: case ERROR_ALREADY_EXISTS: case ERROR_FILE_EXISTS: case ERROR_ACCESS_DENIED: // readonly file, or file still in use by another process. Assume the latter, since we don't create it readonly. return QLockFile::LockFailedError; default: qWarning() << "Got unexpected locking error" << lastError; return QLockFile::UnknownError; } } // We hold the lock, continue. fileHandle = fh; // Assemble data, to write in a single call to write // (otherwise we'd have to check every write call) QByteArray fileData; fileData += QByteArray::number(QCoreApplication::applicationPid()); fileData += '\n'; fileData += qAppName().toUtf8(); fileData += '\n'; //fileData += localHostname(); // gethostname requires winsock init, see QHostInfo... fileData += '\n'; DWORD bytesWritten = 0; QLockFile::LockError error = QLockFile::NoError; if (!WriteFile(fh, fileData.constData(), fileData.size(), &bytesWritten, NULL) || !FlushFileBuffers(fh)) error = QLockFile::UnknownError; // partition full return error; }
bool CompareLastWrite(const wchar_t* szPath1, const wchar_t* szPath2) { HANDLE hPath1, hPath2; FILETIME ftPath1Create, ftPath1Access, ftPath1Write; FILETIME ftPath2Create, ftPath2Access, ftPath2Write; hPath1 = CreateFile2(szPath1, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); if (hPath1 == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND) { return false; } hPath2 = CreateFile2(szPath2, GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); GetFileTime(hPath1, &ftPath1Create, &ftPath1Access, &ftPath1Write); GetFileTime(hPath2, &ftPath2Create, &ftPath2Access, &ftPath2Write); CloseHandle(hPath1); CloseHandle(hPath2); return CompareFileTime(&ftPath1Write, &ftPath2Write) == 1; }
AsyncIO::AsyncIO(SystemStringView filename, bool truncate) { #if WINDOWS_STORE CREATEFILE2_EXTENDED_PARAMETERS parms = {}; parms.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); parms.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; parms.dwFileFlags = FILE_FLAG_OVERLAPPED; m_fh = CreateFile2(filename.data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, truncate ? CREATE_ALWAYS : OPEN_ALWAYS, &parms); #else m_fh = CreateFileW(filename.data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, truncate ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL, nullptr); #endif }
CF_PRIVATE Boolean _CFWriteBytesToFileAsync(CFURLRef url, const void *bytes, CFIndex length) { char path[CFMaxPathSize]; if (!CFURLGetFileSystemRepresentation(url, true, (uint8_t *)path, CFMaxPathSize)) { return false; } wchar_t wpath[CFMaxPathSize]; int convertedLength = MultiByteToWideChar(CP_UTF8, 0, path, CFMaxPathSize, wpath, CFMaxPathSize); if (0 == convertedLength) { unsigned error = GetLastError(); CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to convert the path (error %u)"), error); return false; } HANDLE fileHandle = NULL; CREATEFILE2_EXTENDED_PARAMETERS createExParams; createExParams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); createExParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; createExParams.dwFileFlags = FILE_FLAG_OVERLAPPED; createExParams.dwSecurityQosFlags = 0; createExParams.lpSecurityAttributes = NULL; createExParams.hTemplateFile = NULL; OVERLAPPED* overlapped = (OVERLAPPED*)calloc(1, sizeof(OVERLAPPED)); if ((fileHandle = CreateFile2(wpath, GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, &createExParams)) == INVALID_HANDLE_VALUE) { unsigned error = GetLastError(); CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to open the file (error %u)"), error); free(overlapped); return false; } PTP_IO threadPoolIo = CreateThreadpoolIo(fileHandle, _threadpoolCallback, NULL, NULL); StartThreadpoolIo(threadPoolIo); if (!WriteFile(fileHandle, bytes, length, NULL, overlapped)) { unsigned error = GetLastError(); if (ERROR_IO_PENDING != error) { CFLog(kCFLogLevelWarning, CFSTR("_CFWriteBytesToFileAsync failed to write to the file (error %u)"), error); CloseHandle(fileHandle); CancelThreadpoolIo(threadPoolIo); CloseThreadpoolIo(threadPoolIo); free(overlapped); return false; } } CloseHandle(fileHandle); return true; }
static HANDLE WINAPI fallbackCreateFileW(LPCWSTR fname, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttrs, DWORD dwCreationDisposition, DWORD dwFlagsAndAttrs, HANDLE hTemplFile) { HANDLE retval; const int buflen = (int)(wStrLen(fname) + 1); char *cpstr = (char *)__PHYSFS_smallAlloc(buflen); WideCharToMultiByte(CP_ACP, 0, fname, buflen, cpstr, buflen, NULL, NULL); //retval = CreateFileA(cpstr, dwDesiredAccess, dwShareMode, lpSecurityAttrs, dwCreationDisposition, dwFlagsAndAttrs, hTemplFile); retval = CreateFile2(fname, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); __PHYSFS_smallFree(cpstr); return(retval); } /* fallbackCreateFileW */
voidpf ZCALLBACK win32_open64_file_funcW(voidpf opaque, const void *filename, int mode) { const char *mode_fopen = NULL; DWORD dwDesiredAccess, dwCreationDisposition, dwShareMode, dwFlagsAndAttributes ; HANDLE hFile = NULL; win32_translate_open_mode(mode, &dwDesiredAccess, &dwCreationDisposition, &dwShareMode, &dwFlagsAndAttributes); #ifdef IOWIN32_USING_WINRT_API if ((filename != NULL) && (dwDesiredAccess != 0)) { hFile = CreateFile2((LPCWSTR)filename, dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); } #else if ((filename != NULL) && (dwDesiredAccess != 0)) { hFile = CreateFileW((LPCWSTR)filename, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); } #endif return win32_build_iowin(hFile); }
static HANDLE _win32_open_w(_zip_source_win32_read_file_t *ctx) { #ifdef WINRT CREATEFILE2_EXTENDED_PARAMETERS extParams = { 0 }; extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; extParams.dwFileFlags = FILE_FLAG_RANDOM_ACCESS; extParams.dwSecurityQosFlags = SECURITY_ANONYMOUS; extParams.dwSize = sizeof(extParams); extParams.hTemplateFile = NULL; extParams.lpSecurityAttributes = NULL; return CreateFile2(ctx->fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, OPEN_EXISTING, &extParams); #else return CreateFileW(ctx->fname, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); #endif }
/* \internal */ bool QFSFileEnginePrivate::nativeOpen(QIODevice::OpenMode openMode) { Q_Q(QFSFileEngine); // All files are opened in share mode (both read and write). DWORD shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; int accessRights = 0; if (openMode & QIODevice::ReadOnly) accessRights |= GENERIC_READ; if (openMode & QIODevice::WriteOnly) accessRights |= GENERIC_WRITE; // WriteOnly can create files, ReadOnly cannot. DWORD creationDisp = (openMode & QIODevice::WriteOnly) ? OPEN_ALWAYS : OPEN_EXISTING; // Create the file handle. #ifndef Q_OS_WINRT SECURITY_ATTRIBUTES securityAtts = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE }; fileHandle = CreateFile((const wchar_t*)fileEntry.nativeFilePath().utf16(), accessRights, shareMode, &securityAtts, creationDisp, FILE_ATTRIBUTE_NORMAL, NULL); #else // !Q_OS_WINRT fileHandle = CreateFile2((const wchar_t*)fileEntry.nativeFilePath().utf16(), accessRights, shareMode, creationDisp, NULL); #endif // Q_OS_WINRT // Bail out on error. if (fileHandle == INVALID_HANDLE_VALUE) { q->setError(QFile::OpenError, qt_error_string()); return false; } // Truncate the file after successfully opening it if Truncate is passed. if (openMode & QIODevice::Truncate) q->setSize(0); return true; }
LocalFileLoader::LocalFileLoader(const std::string &filename) : filesize_(0), filename_(filename) { if (filename.empty()) { ERROR_LOG(FILESYS, "LocalFileLoader can't load empty filenames"); return; } #ifndef _WIN32 fd_ = open(filename.c_str(), O_RDONLY | O_CLOEXEC); if (fd_ == -1) { return; } #if PPSSPP_PLATFORM(ANDROID) || (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64) off64_t off = lseek64(fd_, 0, SEEK_END); filesize_ = off; lseek64(fd_, 0, SEEK_SET); #else off_t off = lseek(fd_, 0, SEEK_END); filesize_ = off; lseek(fd_, 0, SEEK_SET); #endif #else // _WIN32 const DWORD access = GENERIC_READ, share = FILE_SHARE_READ, mode = OPEN_EXISTING, flags = FILE_ATTRIBUTE_NORMAL; #if PPSSPP_PLATFORM(UWP) handle_ = CreateFile2(ConvertUTF8ToWString(filename).c_str(), access, share, mode, nullptr); #else handle_ = CreateFile(ConvertUTF8ToWString(filename).c_str(), access, share, nullptr, mode, flags, nullptr); #endif if (handle_ == INVALID_HANDLE_VALUE) { return; } LARGE_INTEGER end_offset; const LARGE_INTEGER zero = { 0 }; if (SetFilePointerEx(handle_, zero, &end_offset, FILE_END) == 0) { // Couldn't seek in the file. Close it and give up? This should never happen. CloseHandle(handle_); handle_ = INVALID_HANDLE_VALUE; return; } filesize_ = end_offset.QuadPart; SetFilePointerEx(handle_, zero, nullptr, FILE_BEGIN); #endif // _WIN32 }
void FileStreamBuf::open(const std::string& path, std::ios::openmode mode) { poco_assert (_handle == INVALID_HANDLE_VALUE); _path = path; _pos = 0; setMode(mode); resetBuffers(); DWORD access = 0; if (mode & std::ios::in) access |= GENERIC_READ; if (mode & std::ios::out) access |= GENERIC_WRITE; DWORD shareMode = FILE_SHARE_READ; if (!(mode & std::ios::out)) shareMode |= FILE_SHARE_WRITE; DWORD creationDisp = OPEN_EXISTING; if (mode & std::ios::trunc) creationDisp = CREATE_ALWAYS; else if (mode & std::ios::out) creationDisp = OPEN_ALWAYS; DWORD flags = FILE_ATTRIBUTE_NORMAL; #if defined (POCO_WIN32_UTF8) std::wstring utf16Path; UnicodeConverter::toUTF16(path, utf16Path); _handle = CreateFile2(utf16Path.c_str(), access, shareMode, creationDisp, NULL); #else _handle = CreateFileA(path.c_str(), access, shareMode, NULL, creationDisp, flags, NULL); #endif if (_handle == INVALID_HANDLE_VALUE) File::handleLastError(_path); if ((mode & std::ios::ate) || (mode & std::ios::app)) seekoff(0, std::ios::end, mode); }
PJ_DEF(pj_status_t) pj_file_open( pj_pool_t *pool, const char *pathname, unsigned flags, pj_oshandle_t *fd) { PJ_DECL_UNICODE_TEMP_BUF(wpathname,256) HANDLE hFile; DWORD dwDesiredAccess = 0; DWORD dwShareMode = 0; DWORD dwCreationDisposition = 0; DWORD dwFlagsAndAttributes = 0; PJ_UNUSED_ARG(pool); PJ_ASSERT_RETURN(pathname!=NULL, PJ_EINVAL); if ((flags & PJ_O_WRONLY) == PJ_O_WRONLY) { dwDesiredAccess |= GENERIC_WRITE; if ((flags & PJ_O_APPEND) == PJ_O_APPEND) { #if !defined(PJ_WIN32_WINCE) || !PJ_WIN32_WINCE /* FILE_APPEND_DATA is invalid on WM2003 and WM5, but it seems * to be working on WM6. All are tested on emulator though. * Removing this also seem to work (i.e. data is appended), so * I guess this flag is "optional". * See http://trac.pjsip.org/repos/ticket/825 */ dwDesiredAccess |= FILE_APPEND_DATA; #endif dwCreationDisposition |= OPEN_ALWAYS; } else { dwDesiredAccess &= ~(FILE_APPEND_DATA); dwCreationDisposition |= CREATE_ALWAYS; } } if ((flags & PJ_O_RDONLY) == PJ_O_RDONLY) { dwDesiredAccess |= GENERIC_READ; if (flags == PJ_O_RDONLY) dwCreationDisposition |= OPEN_EXISTING; } if (dwDesiredAccess == 0) { pj_assert(!"Invalid file open flags"); return PJ_EINVAL; } dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE; dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL; #ifdef PJ_WIN32_WINPHONE hFile = CreateFile2(PJ_STRING_TO_NATIVE(pathname, wpathname,sizeof(wpathname)), dwDesiredAccess, dwShareMode, dwCreationDisposition, NULL); #else hFile = CreateFile(PJ_STRING_TO_NATIVE(pathname, wpathname,sizeof(wpathname)), dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, dwFlagsAndAttributes, NULL); #endif if (hFile == INVALID_HANDLE_VALUE) { *fd = 0; return PJ_RETURN_OS_ERROR(GetLastError()); } if ((flags & PJ_O_APPEND) == PJ_O_APPEND) { pj_status_t status; status = pj_file_setpos(hFile, 0, PJ_SEEK_END); if (status != PJ_SUCCESS) { pj_file_close(hFile); return status; } } *fd = hFile; return PJ_SUCCESS; }
std::string ResolvePath(const std::string &path) { #ifdef _WIN32 typedef DWORD (WINAPI *getFinalPathNameByHandleW_f)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags); static getFinalPathNameByHandleW_f getFinalPathNameByHandleW = nullptr; #if PPSSPP_PLATFORM(UWP) getFinalPathNameByHandleW = &GetFinalPathNameByHandleW; #else if (!getFinalPathNameByHandleW) { HMODULE kernel32 = GetModuleHandle(L"kernel32.dll"); getFinalPathNameByHandleW = (getFinalPathNameByHandleW_f)GetProcAddress(kernel32, "GetFinalPathNameByHandleW"); } #endif static const int BUF_SIZE = 32768; wchar_t *buf = new wchar_t[BUF_SIZE]; memset(buf, 0, BUF_SIZE); std::wstring input = ConvertUTF8ToWString(path); if (getFinalPathNameByHandleW) { #if PPSSPP_PLATFORM(UWP) HANDLE hFile = CreateFile2(input.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, nullptr); #else HANDLE hFile = CreateFile(input.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); #endif if (hFile == INVALID_HANDLE_VALUE) { wcscpy_s(buf, BUF_SIZE - 1, input.c_str()); } else { int result = getFinalPathNameByHandleW(hFile, buf, BUF_SIZE - 1, FILE_NAME_NORMALIZED | VOLUME_NAME_DOS); if (result >= BUF_SIZE || result == 0) wcscpy_s(buf, BUF_SIZE - 1, input.c_str()); CloseHandle(hFile); } } else { wchar_t *longBuf = new wchar_t[BUF_SIZE]; memset(buf, 0, BUF_SIZE); int result = GetLongPathNameW(input.c_str(), longBuf, BUF_SIZE - 1); if (result >= BUF_SIZE || result == 0) wcscpy_s(longBuf, BUF_SIZE - 1, input.c_str()); result = GetFullPathNameW(longBuf, BUF_SIZE - 1, buf, nullptr); if (result >= BUF_SIZE || result == 0) wcscpy_s(buf, BUF_SIZE - 1, input.c_str()); delete [] longBuf; // Normalize slashes just in case. for (int i = 0; i < BUF_SIZE; ++i) { if (buf[i] == '\\') buf[i] = '/'; } } // Undo the \\?\C:\ syntax that's normally returned. std::string output = ConvertWStringToUTF8(buf); if (buf[0] == '\\' && buf[1] == '\\' && buf[2] == '?' && buf[3] == '\\' && isalpha(buf[4]) && buf[5] == ':') output = output.substr(4); delete [] buf; return output; #else std::unique_ptr<char[]> buf(new char[PATH_MAX + 32768]); if (realpath(path.c_str(), buf.get()) == nullptr) return path; return buf.get(); #endif }
/*! \internal Generates a unique file path and returns a native handle to the open file. \a path is used as a template when generating unique paths, \a pos identifies the position of the first character that will be replaced in the template and \a length the number of characters that may be substituted. Returns an open handle to the newly created file if successful, an invalid handle otherwise. In both cases, the string in \a path will be changed and contain the generated path name. */ static bool createFileFromTemplate(NativeFileHandle &file, QFileSystemEntry::NativePath &path, size_t pos, size_t length, QSystemError &error) { Q_ASSERT(length != 0); Q_ASSERT(pos < size_t(path.length())); Q_ASSERT(length <= size_t(path.length()) - pos); Char *const placeholderStart = (Char *)path.data() + pos; Char *const placeholderEnd = placeholderStart + length; // Initialize placeholder with random chars + PID. { Char *rIter = placeholderEnd; #if defined(QT_BUILD_CORE_LIB) quint64 pid = quint64(QCoreApplication::applicationPid()); do { *--rIter = Latin1Char((pid % 10) + '0'); pid /= 10; } while (rIter != placeholderStart && pid != 0); #endif while (rIter != placeholderStart) { char ch = char((qrand() & 0xffff) % (26 + 26)); if (ch < 26) *--rIter = Latin1Char(ch + 'A'); else *--rIter = Latin1Char(ch - 26 + 'a'); } } for (;;) { // Atomically create file and obtain handle #if defined(Q_OS_WIN) # ifndef Q_OS_WINRT file = CreateFile((const wchar_t *)path.constData(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, NULL); # else // !Q_OS_WINRT file = CreateFile2((const wchar_t *)path.constData(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, CREATE_NEW, NULL); # endif // Q_OS_WINRT if (file != INVALID_HANDLE_VALUE) return true; DWORD err = GetLastError(); if (err == ERROR_ACCESS_DENIED) { WIN32_FILE_ATTRIBUTE_DATA attributes; if (!GetFileAttributesEx((const wchar_t *)path.constData(), GetFileExInfoStandard, &attributes) || attributes.dwFileAttributes == INVALID_FILE_ATTRIBUTES) { // Potential write error (read-only parent directory, etc.). error = QSystemError(err, QSystemError::NativeError); return false; } // else file already exists as a directory. } else if (err != ERROR_FILE_EXISTS) { error = QSystemError(err, QSystemError::NativeError); return false; } #else // POSIX file = QT_OPEN(path.constData(), QT_OPEN_CREAT | O_EXCL | QT_OPEN_RDWR | QT_OPEN_LARGEFILE, 0600); if (file != -1) return true; int err = errno; if (err != EEXIST) { error = QSystemError(err, QSystemError::NativeError); return false; } #endif /* tricky little algorwwithm for backward compatibility */ for (Char *iter = placeholderStart;;) { // Character progression: [0-9] => 'a' ... 'z' => 'A' .. 'Z' // String progression: "ZZaiC" => "aabiC" switch (char(*iter)) { case 'Z': // Rollover, advance next character *iter = Latin1Char('a'); if (++iter == placeholderEnd) { // Out of alternatives. Return file exists error, previously set. error = QSystemError(err, QSystemError::NativeError); return false; } continue; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': *iter = Latin1Char('a'); break; case 'z': // increment 'z' to 'A' *iter = Latin1Char('A'); break; default: ++*iter; break; } break; } } Q_ASSERT(false); }
const TCHAR* FWinRTProcess::BaseDir() { static bool bFirstTime = true; static TCHAR Result[512]=TEXT(""); if (!Result[0] && bFirstTime) { { // Testing DWORD Access = GENERIC_WRITE; DWORD WinFlags = 0; DWORD Create = CREATE_ALWAYS; HANDLE Handle = CreateFile2(L"Test.txt", Access, WinFlags, Create, NULL); if (Handle != INVALID_HANDLE_VALUE) { CloseHandle(Handle); } else { DWORD LastErr = GetLastError(); Handle = CreateFile2(L"c:\\Test.txt", Access, WinFlags, Create, NULL); if (Handle != INVALID_HANDLE_VALUE) { CloseHandle(Handle); } else { LastErr = GetLastError(); uint32 dummy = LastErr; } } } // Check the commandline for -BASEDIR=<base directory> const TCHAR* CmdLine = FCommandLine::Get(); if ((CmdLine == NULL) || (FCString::Strlen(CmdLine) == 0)) { const LONG MaxCmdLineSize = 65536; char AnsiCmdLine[MaxCmdLineSize] = {0}; // Load the text file... const TCHAR* CmdLineFilename = L"WinRTCmdLine.txt"; DWORD Access = GENERIC_READ; DWORD WinFlags = FILE_SHARE_READ; DWORD Create = OPEN_EXISTING; HANDLE Handle = CreateFile2(CmdLineFilename, Access, WinFlags, Create, NULL); if (Handle == INVALID_HANDLE_VALUE) { DWORD ErrorCode = GetLastError(); Handle = CreateFile2(L"D:\\Depot\\UE4\\ExampleGame\\Binaries\\WinRT\\AppX\\WinRTCmdLine.txt", Access, WinFlags, Create, NULL); } if (Handle != INVALID_HANDLE_VALUE) { FPlatformMisc::LowLevelOutputDebugStringf(TEXT("Failed to open CmdLine text file via CreateFile2!!!")); LONG TotalSize = 0; // Get the file size WIN32_FILE_ATTRIBUTE_DATA Info; if (GetFileAttributesExW(CmdLineFilename, GetFileExInfoStandard, &Info) == TRUE) { if ((Info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { LARGE_INTEGER li; li.HighPart = Info.nFileSizeHigh; li.LowPart = Info.nFileSizeLow; // return li.QuadPart; TotalSize = Info.nFileSizeLow; } } if ((TotalSize > 0) && (TotalSize < MaxCmdLineSize)) { DWORD Result=0; if (!ReadFile(Handle, AnsiCmdLine, DWORD(TotalSize), &Result, NULL) || (Result != DWORD(TotalSize))) { FPlatformMisc::LowLevelOutputDebugStringf(TEXT("FAILED TO READ CmdLine.txt file!!!")); } else { TCHAR CmdLine[MaxCmdLineSize] = {0}; FCString::Strcpy(CmdLine, ANSI_TO_TCHAR(AnsiCmdLine)); // Strip off \r\n while (CmdLine[FCString::Strlen(CmdLine) - 1] == TEXT('\n')) { CmdLine[FCString::Strlen(CmdLine) - 1] = 0; if (CmdLine[FCString::Strlen(CmdLine) - 1] == TEXT('\r')) { CmdLine[FCString::Strlen(CmdLine) - 1] = 0; } } // We have to do this here for WinRT due to the pre-init needing the BaseDir... FCommandLine::Set(CmdLine); } } CloseHandle(Handle); } else { FPlatformMisc::LowLevelOutputDebugStringf(TEXT("Failed to open CmdLine.txt file!")); } } if (CmdLine != NULL) { FString BaseDirToken = TEXT("-BASEDIR="); FString NextToken; while (FParse::Token(CmdLine, NextToken, false)) { if (NextToken.StartsWith(BaseDirToken) == true) { FString BaseDir = NextToken.Right(NextToken.Len() - BaseDirToken.Len()); BaseDir.ReplaceInline(TEXT("\\"), TEXT("/")); FCString::Strcpy(Result, *BaseDir); } } } Platform::String^ LocationPath = Windows::ApplicationModel::Package::Current->InstalledLocation->Path; FPlatformMisc::LowLevelOutputDebugStringf(TEXT("LocationPath = %s\n"), LocationPath->Data()); FCString::Strcpy(Result, LocationPath->Data()); bFirstTime = false; } return Result; }
/// Begins recursive monitoring of a directory. Events will be returned in the /// callback as they occur. /// @param[in] directory Directory name to monitor. /// @param[in] num_events_internal Amount of internal buffer to allocate to /// store, events. The more buffer, the less /// chance of overrun. /// @param[in] cb Callback function to call when an event is received. Note: /// win32 users must call VPL_Yield or VPL_Sleep for events to /// be received. /// @param[out] handle_out Handle to identify the monitor. The handle is returned /// with events and used to identify the monitor to stop. int VPLFS_MonitorDir(const char* directory, int num_events_internal, VPLFS_MonitorCallback cb, VPLFS_MonitorHandle *handle_out) { VPL_REPORT_INFO("monitorDir called"); *handle_out = NULL; int rv; int rc; DWORD dwRecSize = sizeof(FILE_NOTIFY_INFORMATION) + MAX_PATH; DWORD dwCount = num_events_internal; int bufferLength = dwRecSize*dwCount; int returnBuf = num_events_internal*ALIGN(sizeof(VPLFS_MonitorEvent)+MAX_PATH); VPLFS_MonitorHandle_t* handle; WCHAR* wDirectory = NULL; VPLMutex_Lock(VPLLazyInitMutex_GetMutex(&g_monitorDirMutex)); if(g_isInitCount==0) { rv = VPL_ERR_NOT_INIT; goto error_not_init; } handle = (VPLFS_MonitorHandle_t*) malloc(sizeof(VPLFS_MonitorHandle_t) + bufferLength + returnBuf); if (handle == NULL) { rv = VPL_ERR_NOMEM; goto error_not_init; } handle->pBuffer = (char*)(handle+1); handle->nBufferLength = bufferLength; handle->internalEvents = num_events_internal; handle->stop = false; handle->has_rename_old_name = false; handle->cb = cb; handle->cbReturnBuf = (VPLFS_MonitorEvent*)(handle->pBuffer + handle->nBufferLength); //open the directory to watch.... rv = _VPL__utf8_to_wstring(directory, &wDirectory); if (rv != 0) { VPL_REPORT_WARN("_VPL__utf8_to_wstring(%s) failed: %d", directory, rv); goto error; } #ifdef VPL_PLAT_IS_WINRT CREATEFILE2_EXTENDED_PARAMETERS cf2ex = {0}; cf2ex.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS); cf2ex.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; cf2ex.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED; handle->hDir = CreateFile2(wDirectory, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, OPEN_EXISTING, &cf2ex); #else handle->hDir = CreateFileW(wDirectory, FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, NULL); #endif if(handle->hDir == INVALID_HANDLE_VALUE) { rv = VPLError_GetLastWinError(); VPL_REPORT_WARN("CreateFile: %d, %s", rv, directory); goto error2; } g_monitorCommand = MONITOR_COMMAND_START; g_monitorHandle = handle; rc = VPLSem_Post(&g_semaphoreCommand); if(rc != VPL_OK) { VPL_REPORT_WARN("semaphore:%d", rc); } rc = VPLSem_Wait(&g_semaphoreReturn); if(rc != VPL_OK) { VPL_REPORT_WARN("semaphore:%d", rc); } rv = g_returnErrorCode; *handle_out = (VPLFS_MonitorHandle*)handle; VPLMutex_Unlock(VPLLazyInitMutex_GetMutex(&g_monitorDirMutex)); return rv; error2: free(wDirectory); error: free(handle); error_not_init: VPLMutex_Unlock(VPLLazyInitMutex_GetMutex(&g_monitorDirMutex)); return rv; }
void Directory::read() const { #if WINAPI_FAMILY_PARTITION (WINAPI_PARTITION_DESKTOP) WIN32_FIND_DATA f; auto pattern = m_path + '*'; auto wpattern = charset::ToWide( pattern.c_str() ); auto h = FindFirstFile( wpattern.get(), &f ); if ( h == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to browse ", m_path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } do { auto file = charset::FromWide( f.cFileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; auto fullpath = m_path + file.get(); try { if ( ( f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( m_mrl + utils::url::encode( file.get() ) ) ); else m_files.emplace_back( std::make_shared<File>( fullpath ) ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to access a listed file/dir: ", ex.what() , ". Ignoring this entry." ); } } while ( FindNextFile( h, &f ) != 0 ); FindClose( h ); #else // We must remove the trailing / // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx // «Do not use a trailing backslash (\), which indicates the root directory of a drive» auto tmpPath = m_path.substr( 0, m_path.length() - 1 ); auto wpath = charset::ToWide( tmpPath.c_str() ); CREATEFILE2_EXTENDED_PARAMETERS params{}; params.dwFileFlags = FILE_FLAG_BACKUP_SEMANTICS; auto handle = CreateFile2( wpath.get(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING, ¶ms ); if ( handle == INVALID_HANDLE_VALUE ) { LOG_ERROR( "Failed to open directory ", m_path ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to open directory" ); } std::unique_ptr<typename std::remove_pointer<HANDLE>::type, decltype(&CloseHandle)> handlePtr( handle, &CloseHandle ); // Allocating a 32 bytes buffer to contain the file name. If more is required, we'll allocate size_t buffSize = sizeof( FILE_FULL_DIR_INFO ) + 32; std::unique_ptr<FILE_FULL_DIR_INFO, void(*)(FILE_FULL_DIR_INFO*)> dirInfo( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ), [](FILE_FULL_DIR_INFO* ptr) { free( ptr ); } ); if ( dirInfo == nullptr ) throw std::bad_alloc(); while ( true ) { auto h = GetFileInformationByHandleEx( handle, FileFullDirectoryInfo, dirInfo.get(), buffSize ); if ( h == 0 ) { auto error = GetLastError(); if ( error == ERROR_FILE_NOT_FOUND ) break; else if ( error == ERROR_MORE_DATA ) { buffSize *= 2; dirInfo.reset( reinterpret_cast<FILE_FULL_DIR_INFO*>( malloc( buffSize ) ) ); if ( dirInfo == nullptr ) throw std::bad_alloc(); continue; } LOG_ERROR( "Failed to browse ", m_path, ". GetLastError(): ", GetLastError() ); throw std::system_error( GetLastError(), std::generic_category(), "Failed to browse through directory" ); } auto file = charset::FromWide( dirInfo->FileName ); if ( file[0] == '.' && strcasecmp( file.get(), ".nomedia" ) ) continue; try { if ( ( dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY ) != 0 ) m_dirs.emplace_back( m_fsFactory.createDirectory( m_path + utils::url::encode( file.get() ) ) ); else m_files.emplace_back( std::make_shared<File>( m_path + file.get()) ); } catch ( const std::system_error& ex ) { LOG_WARN( "Failed to access a listed file/dir: ", ex.what() , ". Ignoring this entry." ); } } #endif }