diff --git a/eng/native/tryrun.browser.cmake b/eng/native/tryrun.browser.cmake index 514e75e4e9ee07..cb205280d3b927 100644 --- a/eng/native/tryrun.browser.cmake +++ b/eng/native/tryrun.browser.cmake @@ -4,7 +4,7 @@ # to significantly speed up the CMake configure phase for WebAssembly builds. # # IMPORTANT: This file is specific to the Emscripten version and WebAssembly target. -# +# # Valid for: # - Emscripten version: 6.0.2 # - Target: wasm32-unknown-emscripten (browser-wasm) @@ -249,9 +249,6 @@ set(HAVE_PROCFS_H "" CACHE INTERNAL "") set(HAVE_PROCFS_STAT_COMPILED TRUE CACHE INTERNAL "") set_cache_value(HAVE_PROCFS_STAT_EXITCODE 1) set(HAVE_PROCFS_STAT "" CACHE INTERNAL "") -set(HAVE_PROCFS_STATM_COMPILED TRUE CACHE INTERNAL "") -set_cache_value(HAVE_PROCFS_STATM_EXITCODE 1) -set(HAVE_PROCFS_STATM "" CACHE INTERNAL "") set(HAVE_PT_REGS FALSE CACHE INTERNAL "") set(HAVE_PTHREAD_ATTR_GET_NP "" CACHE INTERNAL "") set(HAVE_PTHREAD_CONDATTR_SETCLOCK 1 CACHE INTERNAL "") @@ -351,9 +348,3 @@ set(HAVE_VM_FLAGS_SUPERPAGE_SIZE_ANY "" CACHE INTERNAL "") set(HAVE_VM_READ "" CACHE INTERNAL "") set(HAVE_XSW_USAGE "" CACHE INTERNAL "") set(HAVE_XSWDEV "" CACHE INTERNAL "") -set(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_COMPILED TRUE CACHE INTERNAL "") -set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE 1) -set(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS "" CACHE INTERNAL "") -set(REALPATH_SUPPORTS_NONEXISTENT_FILES_COMPILED TRUE CACHE INTERNAL "") -set_cache_value(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1) -set(REALPATH_SUPPORTS_NONEXISTENT_FILES "" CACHE INTERNAL "") diff --git a/eng/native/tryrun.cmake b/eng/native/tryrun.cmake index 468ab4191c4be4..73cfb017526f1f 100644 --- a/eng/native/tryrun.cmake +++ b/eng/native/tryrun.cmake @@ -61,11 +61,8 @@ if(DARWIN AND NOT DEFINED ANDROID_BUILD) set_cache_value(HAVE_CLOCK_THREAD_CPUTIME_EXITCODE 0) set_cache_value(HAVE_PROCFS_CTL_EXITCODE 1) set_cache_value(HAVE_PROCFS_STAT_EXITCODE 1) - set_cache_value(HAVE_PROCFS_STATM_EXITCODE 1) set_cache_value(HAVE_SCHED_GETCPU_EXITCODE 1) set_cache_value(HAVE_SCHED_GET_PRIORITY_EXITCODE 0) - set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE 1) - set_cache_value(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1) set_cache_value(HAVE_SHM_OPEN_THAT_WORKS_WELL_ENOUGH_WITH_MMAP_EXITCODE 1) else() message(FATAL_ERROR "Arch is ${TARGET_ARCH_NAME}. Only arm64 or x64 is supported for OSX cross build!") @@ -75,11 +72,8 @@ else() set_cache_value(HAVE_CLOCK_THREAD_CPUTIME_EXITCODE 0) set_cache_value(HAVE_PROCFS_CTL_EXITCODE 1) set_cache_value(HAVE_PROCFS_STAT_EXITCODE 0) - set_cache_value(HAVE_PROCFS_STATM_EXITCODE 0) set_cache_value(HAVE_SCHED_GETCPU_EXITCODE 0) set_cache_value(HAVE_SCHED_GET_PRIORITY_EXITCODE 0) - set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE 1) - set_cache_value(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1) if(ALPINE_LINUX) set_cache_value(HAVE_SHM_OPEN_THAT_WORKS_WELL_ENOUGH_WITH_MMAP_EXITCODE 1) else() @@ -90,19 +84,14 @@ else() set_cache_value(HAVE_SHM_OPEN_THAT_WORKS_WELL_ENOUGH_WITH_MMAP 1) set_cache_value(HAVE_CLOCK_REALTIME 1) set_cache_value(HAVE_PROCFS_STAT 0) - set_cache_value(HAVE_PROCFS_STATM 0) elseif(OPENBSD) set_cache_value(HAVE_SHM_OPEN_THAT_WORKS_WELL_ENOUGH_WITH_MMAP 1) set_cache_value(HAVE_CLOCK_REALTIME 1) set_cache_value(HAVE_PROCFS_STAT 0) - set_cache_value(HAVE_PROCFS_STATM 0) elseif(ILLUMOS) set_cache_value(HAVE_PROCFS_CTL_EXITCODE 0) elseif (TIZEN) elseif(HAIKU) set_cache_value(HAVE_PROCFS_STAT_EXITCODE 1) - set_cache_value(HAVE_PROCFS_STATM_EXITCODE 1) - elseif(ANDROID_BUILD) - set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS 0) endif() endif() diff --git a/eng/native/tryrun_ios_tvos.cmake b/eng/native/tryrun_ios_tvos.cmake index 27397d619f5c45..0d613c9348955a 100644 --- a/eng/native/tryrun_ios_tvos.cmake +++ b/eng/native/tryrun_ios_tvos.cmake @@ -12,8 +12,5 @@ set_cache_value(HAVE_CLOCK_REALTIME_EXITCODE 0) set_cache_value(HAVE_CLOCK_THREAD_CPUTIME_EXITCODE 0) set_cache_value(HAVE_PROCFS_CTL_EXITCODE 1) set_cache_value(HAVE_PROCFS_STAT_EXITCODE 1) -set_cache_value(HAVE_PROCFS_STATM_EXITCODE 1) set_cache_value(HAVE_SCHED_GET_PRIORITY_EXITCODE 0) -set_cache_value(ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS_EXITCODE 1) -set_cache_value(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1) set_cache_value(HAVE_SHM_OPEN_THAT_WORKS_WELL_ENOUGH_WITH_MMAP_EXITCODE 1) diff --git a/src/coreclr/CMakeLists.txt b/src/coreclr/CMakeLists.txt index 8a996242501b4b..ab1c4fecdd5832 100644 --- a/src/coreclr/CMakeLists.txt +++ b/src/coreclr/CMakeLists.txt @@ -40,10 +40,6 @@ if(CLR_CMAKE_TARGET_WASI) add_compile_definitions(_WASI_EMULATED_MMAN) add_compile_definitions(_WASI_EMULATED_GETPID) include_directories(BEFORE SYSTEM ${CMAKE_CURRENT_SOURCE_DIR}/pal/src/include/pal/wasi) - # Cross-compile try_run() answers — wasm32 binaries cannot execute on - # the build host, so pre-seed the cache. - set(REALPATH_SUPPORTS_NONEXISTENT_FILES_EXITCODE 1 CACHE STRING "" FORCE) - set(HAVE_PROCFS_STATM_EXITCODE 1 CACHE STRING "" FORCE) endif() OPTION(CLR_CMAKE_ENABLE_CODE_COVERAGE "Enable code coverage" OFF) diff --git a/src/coreclr/debug/createdump/createdump.h b/src/coreclr/debug/createdump/createdump.h index ef397e733b9477..4da3b2b81b8d86 100644 --- a/src/coreclr/debug/createdump/createdump.h +++ b/src/coreclr/debug/createdump/createdump.h @@ -116,6 +116,4 @@ extern MINIDUMP_TYPE GetMiniDumpType(DumpType dumpType); #ifdef HOST_WINDOWS extern std::string GetLastErrorString(); extern DWORD GetTempPathWrapper(IN DWORD nBufferLength, OUT LPSTR lpBuffer); -#else -#define GetTempPathWrapper GetTempPathA #endif \ No newline at end of file diff --git a/src/coreclr/debug/createdump/createdumpmain.cpp b/src/coreclr/debug/createdump/createdumpmain.cpp index fc0fe94a76ecd8..253c1df4458c9e 100644 --- a/src/coreclr/debug/createdump/createdumpmain.cpp +++ b/src/coreclr/debug/createdump/createdumpmain.cpp @@ -14,11 +14,26 @@ void print_trace_timestamp() bool GetDefaultDumpPath(char* buffer, size_t bufferSize) { +#ifdef HOST_WINDOWS if (bufferSize > MAXDWORD || GetTempPathWrapper(static_cast(bufferSize), buffer) == 0) { printf_error("GetTempPath failed\n"); return false; } +#else + const char* tmpDir = getenv("TMPDIR"); + if (tmpDir == nullptr || tmpDir[0] == '\0') + { + tmpDir = "/tmp/"; + } + const char* slash = (tmpDir[strlen(tmpDir) - 1] == '/') ? "" : "/"; + int len = snprintf(buffer, bufferSize, "%s%s", tmpDir, slash); + if (len < 0 || static_cast(len) >= bufferSize) + { + printf_error("TMPDIR is too long\n"); + return false; + } +#endif int exitCode = strcat_s(buffer, bufferSize, DEFAULT_DUMP_TEMPLATE); if (exitCode != 0) { diff --git a/src/coreclr/debug/createdump/createdumppal.cpp b/src/coreclr/debug/createdump/createdumppal.cpp index e4105bf059a9ff..5029106e8e80fb 100644 --- a/src/coreclr/debug/createdump/createdumppal.cpp +++ b/src/coreclr/debug/createdump/createdumppal.cpp @@ -14,35 +14,6 @@ DEFINE_GUID(IID_IUnknown, 0x00000000, 0x0000, 0x0000, 0xC0, 0x00, 0x00, 0x00, 0x bool g_arm64_atomics_present = false; #endif -#define TEMP_DIRECTORY_PATH "/tmp/" - -// Used to construct the default dump path. -DWORD -PALAPI -GetTempPathA( - IN DWORD nBufferLength, - OUT LPSTR lpBuffer) -{ - DWORD dwPathLen = 0; - const char *tempDir = getenv("TMPDIR"); - if (tempDir == nullptr) - { - tempDir = TEMP_DIRECTORY_PATH; - } - size_t tempDirLen = strlen(tempDir); - if (tempDirLen < nBufferLength) - { - dwPathLen = tempDirLen; - strcpy_s(lpBuffer, nBufferLength, tempDir); - } - else - { - // Get the required length - dwPathLen = tempDirLen + 1; - } - return dwPathLen; -} - // // Used in pal\inc\rt\safecrt.h's _invalid_parameter handler // diff --git a/src/coreclr/dlls/mscordac/mscordac_unixexports.src b/src/coreclr/dlls/mscordac/mscordac_unixexports.src index 55a97b0fcb8222..b1edc440164e6f 100644 --- a/src/coreclr/dlls/mscordac/mscordac_unixexports.src +++ b/src/coreclr/dlls/mscordac/mscordac_unixexports.src @@ -56,14 +56,10 @@ nativeStringResourceTable_mscorrc #memcpy_s #sscanf_s -#CreateFileMappingW -#CreateFileA -#CreateFileW #CreateThread #CloseHandle #DebugBreak #DuplicateHandle -#FlushFileBuffers #FlushInstructionCache #FormatMessageW #FreeEnvironmentStringsW @@ -74,33 +70,22 @@ nativeStringResourceTable_mscorrc #GetEnvironmentStringsW #GetEnvironmentVariableA #GetEnvironmentVariableW -#GetFileSize -#GetFullPathNameW #GetLastError #GetModuleFileNameW #GetProcAddress -#GetStdHandle #GetSystemInfo -#GetTempPathA #LoadLibraryExA #LoadLibraryExW -#MapViewOfFile -#MapViewOfFileEx #MultiByteToWideChar #OutputDebugStringW #OutputDebugStringA #RaiseException #RaiseFailFastException -#ReadFile #ResumeThread -#SearchPathW -#SetFilePointer #SetLastError #SetThreadDescription #SwitchToThread #TerminateProcess -#UnmapViewOfFile #WideCharToMultiByte -#WriteFile #GUID_NULL diff --git a/src/coreclr/gc/unix/config.gc.h.in b/src/coreclr/gc/unix/config.gc.h.in index 283ff0a7215ee4..c68635e078d25a 100644 --- a/src/coreclr/gc/unix/config.gc.h.in +++ b/src/coreclr/gc/unix/config.gc.h.in @@ -31,6 +31,5 @@ #cmakedefine01 HAVE_XSW_USAGE #cmakedefine01 HAVE_XSWDEV #cmakedefine01 HAVE_NON_LEGACY_STATFS -#cmakedefine01 HAVE_PROCFS_STATM #endif // __CONFIG_H__ diff --git a/src/coreclr/gc/unix/configure.cmake b/src/coreclr/gc/unix/configure.cmake index 8efa1c649f3262..d4080304185c16 100644 --- a/src/coreclr/gc/unix/configure.cmake +++ b/src/coreclr/gc/unix/configure.cmake @@ -159,21 +159,4 @@ check_prototype_definition( ${STATFS_INCLUDES} HAVE_NON_LEGACY_STATFS) -set(CMAKE_REQUIRED_LIBRARIES) -check_cxx_source_runs(" -#include -#include -#include -#include - -int main(void) { - int fd; - - fd = open(\"/proc/self/statm\", O_RDONLY); - if (fd == -1) { - exit(1); - } - exit(0); -}" HAVE_PROCFS_STATM) - configure_file(${CMAKE_CURRENT_LIST_DIR}/config.gc.h.in ${CMAKE_CURRENT_BINARY_DIR}/config.gc.h) diff --git a/src/coreclr/gc/unix/gcenv.unix.cpp b/src/coreclr/gc/unix/gcenv.unix.cpp index 88a88cd075b6c1..8f4080fb37d9e3 100644 --- a/src/coreclr/gc/unix/gcenv.unix.cpp +++ b/src/coreclr/gc/unix/gcenv.unix.cpp @@ -977,7 +977,7 @@ const AffinitySet* GCToOSInterface::SetGCThreadsAffinitySet(uintptr_t configAffi return &g_processAffinitySet; } -#if HAVE_PROCFS_STATM +#ifdef RLIMIT_AS // Return the size of the user-mode portion of the virtual address space of this process. static size_t GetCurrentVirtualMemorySize() { @@ -1016,7 +1016,7 @@ static size_t GetCurrentVirtualMemorySize() return result; } -#endif // HAVE_PROCFS_STATM +#endif // RLIMIT_AS // Return the size of the available user-mode portion of the virtual address space of this process. // Return: @@ -1321,7 +1321,7 @@ void GCToOSInterface::GetMemoryStatus(uint64_t restricted_limit, uint32_t* memor load = (uint32_t)(((float)used * 100) / (float)total); } -#if HAVE_PROCFS_STATM +#ifdef RLIMIT_AS rlimit addressSpaceLimit; if ((getrlimit(RLIMIT_AS, &addressSpaceLimit) == 0) && (addressSpaceLimit.rlim_cur != RLIM_INFINITY)) { @@ -1337,7 +1337,7 @@ void GCToOSInterface::GetMemoryStatus(uint64_t restricted_limit, uint32_t* memor } } } -#endif // HAVE_PROCFS_STATM +#endif // RLIMIT_AS } } diff --git a/src/coreclr/ilasm/asmparse.h b/src/coreclr/ilasm/asmparse.h index a20157e83132d8..71edd235146189 100644 --- a/src/coreclr/ilasm/asmparse.h +++ b/src/coreclr/ilasm/asmparse.h @@ -7,6 +7,7 @@ #define asmparse_h #include // for FILE +#include "minipal.h" #include "assembler.h" // for ErrorReporter Labels //class Assembler; @@ -95,9 +96,9 @@ class MappedFileStream : public ReadStream { public: MappedFileStream(_In_ __nullterminated WCHAR* wFileName) : m_fileNameUtf8(NULL) - , m_hFile(INVALID_HANDLE_VALUE) + , m_hFile(VMToOSInterface::InvalidFileHandle) , m_FileSize(0) - , m_hMapFile(NULL) + , m_hMapFile(VMToOSInterface::InvalidMemoryMapHandle) { m_pStart = open(wFileName); m_pCurr = m_pStart; @@ -112,17 +113,17 @@ class MappedFileStream : public ReadStream { } ~MappedFileStream() { - if (m_hFile != INVALID_HANDLE_VALUE) + if (m_hFile != VMToOSInterface::InvalidFileHandle) { if (m_pStart) - UnmapViewOfFile((void*)m_pStart); - if (m_hMapFile) - CloseHandle(m_hMapFile); - CloseHandle(m_hFile); + VMToOSInterface::UnmapMemory((void*)m_pStart, m_FileSize); + if (m_hMapFile != VMToOSInterface::InvalidMemoryMapHandle) + VMToOSInterface::CloseMemoryMapping(m_hMapFile); + VMToOSInterface::CloseFile(m_hFile); m_pStart = NULL; - m_hMapFile = NULL; - m_hFile = INVALID_HANDLE_VALUE; + m_hMapFile = VMToOSInterface::InvalidMemoryMapHandle; + m_hFile = VMToOSInterface::InvalidFileHandle; m_FileSize = 0; } @@ -173,19 +174,17 @@ class MappedFileStream : public ReadStream { private: char* map_file() { - DWORD dwFileSizeLow; + uint64_t fileSize; - dwFileSizeLow = GetFileSize( m_hFile, NULL); - if (dwFileSizeLow == INVALID_FILE_SIZE) + if (!VMToOSInterface::GetFileSize(m_hFile, &fileSize) || fileSize == 0 || fileSize > UINT32_MAX) return NULL; - m_FileSize = dwFileSizeLow; + m_FileSize = (DWORD)fileSize; - // No difference between A and W in this case: last param (LPCTSTR) is NULL - m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READONLY, 0, 0, NULL); - if (m_hMapFile == NULL) + m_hMapFile = VMToOSInterface::CreateMemoryMapping(m_hFile, 0, VMToOSInterface::MemoryProtection::ReadOnly); + if (m_hMapFile == VMToOSInterface::InvalidMemoryMapHandle) return NULL; - return (char*)(HMODULE) MapViewOfFile(m_hMapFile, FILE_MAP_READ, 0, 0, 0); + return (char*)VMToOSInterface::MapMemory(m_hMapFile, 0, nullptr, m_FileSize, VMToOSInterface::MemoryProtection::ReadOnly, true); } char* open(const WCHAR* moduleName) { @@ -193,15 +192,14 @@ class MappedFileStream : public ReadStream { if (!moduleName) return NULL; - m_hFile = WszCreateFile(moduleName, GENERIC_READ, FILE_SHARE_READ, - 0, OPEN_EXISTING, 0, 0); - return (m_hFile == INVALID_HANDLE_VALUE) ? NULL : map_file(); + m_hFile = VMToOSInterface::OpenFile(reinterpret_cast(moduleName)); + return (m_hFile == VMToOSInterface::InvalidFileHandle) ? NULL : map_file(); } char* m_fileNameUtf8; // FileName (for error reporting) - HANDLE m_hFile; // File we are reading from + VMToOSInterface::MemoryMapHandle m_hFile; // File we are reading from DWORD m_FileSize; - HANDLE m_hMapFile; + VMToOSInterface::MemoryMapHandle m_hMapFile; char* m_pStart; char* m_pEnd; char* m_pCurr; @@ -299,8 +297,6 @@ class AsmParse : public ErrorReporter BinStr* MakeTypeArray(CorElementType kind, BinStr* elemType, BinStr* bounds); char* fillBuff(_In_opt_z_ char* curPos); // refill the input buffer - HANDLE hstdout; - HANDLE hstderr; private: friend void yyerror(_In_ __nullterminated const char* str); diff --git a/src/coreclr/ilasm/grammar_after.cpp b/src/coreclr/ilasm/grammar_after.cpp index f624555da12e83..a66f8543d0b176 100644 --- a/src/coreclr/ilasm/grammar_after.cpp +++ b/src/coreclr/ilasm/grammar_after.cpp @@ -1003,6 +1003,30 @@ int yylex() #endif ) { +#ifdef TARGET_UNIX + for(const WCHAR* wzDir = parser->wzIncludePath; (wzDir != NULL) && (*wzDir != 0); ) + { + const WCHAR* wzEnd = u16_strchr(wzDir, W(':')); + COUNT_T dirLen = (wzEnd != NULL) ? (COUNT_T)(wzEnd - wzDir) : (COUNT_T)u16_strlen(wzDir); + if(dirLen != 0) + { + PathString wzCandidate; + wzCandidate.Set(wzDir, dirLen); + wzCandidate.Append(W("/")); + wzCandidate.Append(wzFile); + MAKE_UTF8PTR_FROMWIDE(candidateUtf8, wzCandidate.GetUnicode()); + FILE* pCandidate = fopen(candidateUtf8, "rb"); + if(pCandidate != NULL) + { + fclose(pCandidate); + delete [] wzFile; + wzFile = wzCandidate.GetCopyOfUnicodeString(); + break; + } + } + wzDir = (wzEnd != NULL) ? wzEnd + 1 : NULL; + } +#else PathString wzFullName; WCHAR* pwz; @@ -1014,7 +1038,7 @@ int yylex() wzFile = wzFullName.GetCopyOfUnicodeString(); } - +#endif } if(PASM->m_fReportProgress) { @@ -1607,9 +1631,6 @@ AsmParse::AsmParse(ReadStream* aIn, Assembler *aAssem) wzIncludePath = NULL; penv = NULL; - hstdout = GetStdHandle(STD_OUTPUT_HANDLE); - hstderr = GetStdHandle(STD_ERROR_HANDLE); - success = true; _ASSERTE(parser == 0); // Should only be one parser instance at a time diff --git a/src/coreclr/ilasm/main.cpp b/src/coreclr/ilasm/main.cpp index 58e0ee7573aa69..b6df0cfdd0c19a 100644 --- a/src/coreclr/ilasm/main.cpp +++ b/src/coreclr/ilasm/main.cpp @@ -11,6 +11,10 @@ #include "clrversion.h" #include "strsafe.h" +#ifdef TARGET_UNIX +#include +#include +#endif #define ASSERTE_ALL_BUILDS(expr) _ASSERTE_ALL_BUILDS((expr)) WCHAR* EqualOrColon(_In_ __nullterminated WCHAR* szArg) @@ -99,11 +103,22 @@ void MakeProperSourceFileName(_In_ __nullterminated WCHAR* wzOrigName, char* FullFileName(_In_ __nullterminated WCHAR* wzFileName, unsigned uCodePage) { +#ifdef TARGET_UNIX + char szFileName[MAX_FILENAME_LENGTH*3]; + WideCharToMultiByte(uCodePage,0,wzFileName,-1,szFileName,MAX_FILENAME_LENGTH*3-1,NULL,NULL); + char szCwd[PATH_MAX]; + char szFullPath[PATH_MAX + MAX_FILENAME_LENGTH*3]; + if((szFileName[0] != '/') && (getcwd(szCwd, sizeof(szCwd)) != NULL)) + sprintf_s(szFullPath, sizeof(szFullPath), "%s/%s", szCwd, szFileName); + else + strcpy_s(szFullPath, sizeof(szFullPath), szFileName); +#else static WCHAR wzFullPath[MAX_FILENAME_LENGTH]; WCHAR* pwz; GetFullPathName(wzFileName,MAX_FILENAME_LENGTH,wzFullPath,&pwz); char szFullPath[MAX_FILENAME_LENGTH*3]; WideCharToMultiByte(uCodePage,0,wzFullPath,-1,szFullPath,MAX_FILENAME_LENGTH*3-1,NULL,NULL); +#endif char* sz = new char[strlen(szFullPath)+1]; if(sz) strcpy_s(sz,strlen(szFullPath)+1,szFullPath); return sz; diff --git a/src/coreclr/ildasm/ceeload.cpp b/src/coreclr/ildasm/ceeload.cpp index df7666d6522bea..bc1627e76368cf 100644 --- a/src/coreclr/ildasm/ceeload.cpp +++ b/src/coreclr/ildasm/ceeload.cpp @@ -17,9 +17,9 @@ /*************************************************************************************/ PELoader::PELoader() { - m_hFile = NULL; + m_hFile = VMToOSInterface::InvalidFileHandle; m_hMod = NULL; - m_hMapFile = NULL; + m_hMapFile = VMToOSInterface::InvalidMemoryMapHandle; m_pNT64 = NULL; m_bIsPE32 = FALSE; m_FileSize = m_FileSizeAligned = 0; @@ -33,7 +33,7 @@ PELoader::~PELoader() // If we have an hFile then we opened this file ourselves! // If we do not then this file was loaded by the OS and the OS will // close it for us. - if (m_hFile) + if (m_hFile != VMToOSInterface::InvalidFileHandle) this->close(); } @@ -41,81 +41,46 @@ PELoader::~PELoader() /*************************************************************************************/ void PELoader::close() { - - // _ASSERTE(m_hFile != NULL); - if (m_hFile) + if (m_hFile != VMToOSInterface::InvalidFileHandle) { if (m_hMod) - UnmapViewOfFile((void*)m_hMod); - if (m_hMapFile) - CloseHandle(m_hMapFile); - CloseHandle(m_hFile); + VMToOSInterface::UnmapMemory((void*)m_hMod, m_FileSize); + if (m_hMapFile != VMToOSInterface::InvalidMemoryMapHandle) + VMToOSInterface::CloseMemoryMapping(m_hMapFile); + VMToOSInterface::CloseFile(m_hFile); m_hMod = NULL; - m_hMapFile = NULL; - m_hFile = NULL; + m_hMapFile = VMToOSInterface::InvalidMemoryMapHandle; + m_hFile = VMToOSInterface::InvalidFileHandle; m_FileSize = m_FileSizeAligned = 0; } } - -BOOL PELoader::open(LPCSTR moduleName) -{ - HMODULE newhMod = NULL; - DWORD dwFileSizeLow; - - _ASSERTE(moduleName); - if (!moduleName) - return FALSE; - - - m_hFile = CreateFileA(moduleName, GENERIC_READ, FILE_SHARE_READ, - 0, OPEN_EXISTING, 0, 0); - if (m_hFile == INVALID_HANDLE_VALUE) - return FALSE; - - dwFileSizeLow = GetFileSize( m_hFile, NULL); - if (dwFileSizeLow == INVALID_FILE_SIZE) - return FALSE; - m_FileSize = dwFileSizeLow; - - m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READONLY, 0, 0, NULL); - if (m_hMapFile == NULL) - return FALSE; - - newhMod = (HMODULE) MapViewOfFile(m_hMapFile, FILE_MAP_READ, 0, 0, 0); - if (newhMod == NULL) - return FALSE; - return open(newhMod); -} - BOOL PELoader::open(const WCHAR* moduleName) { - HMODULE newhMod = NULL; - DWORD dwFileSizeLow; + uint64_t fileSize; + void* view; _ASSERTE(moduleName); if (!moduleName) return FALSE; - m_hFile = WszCreateFile(moduleName, GENERIC_READ, FILE_SHARE_READ, - 0, OPEN_EXISTING, 0, 0); - if (m_hFile == INVALID_HANDLE_VALUE) + m_hFile = VMToOSInterface::OpenFile(reinterpret_cast(moduleName)); + if (m_hFile == VMToOSInterface::InvalidFileHandle) return FALSE; - dwFileSizeLow = GetFileSize( m_hFile, NULL); - if (dwFileSizeLow == INVALID_FILE_SIZE) + if (!VMToOSInterface::GetFileSize(m_hFile, &fileSize) || fileSize == 0 || fileSize > UINT32_MAX) return FALSE; - m_FileSize = dwFileSizeLow; + m_FileSize = (size_t)fileSize; - m_hMapFile = CreateFileMapping(m_hFile, NULL, PAGE_READONLY, 0, 0, NULL); - if (m_hMapFile == NULL) + m_hMapFile = VMToOSInterface::CreateMemoryMapping(m_hFile, 0, VMToOSInterface::MemoryProtection::ReadOnly); + if (m_hMapFile == VMToOSInterface::InvalidMemoryMapHandle) return FALSE; - newhMod = (HMODULE) MapViewOfFile(m_hMapFile, FILE_MAP_READ, 0, 0, 0); - if (newhMod == NULL) + view = VMToOSInterface::MapMemory(m_hMapFile, 0, nullptr, m_FileSize, VMToOSInterface::MemoryProtection::ReadOnly, true); + if (view == nullptr) return FALSE; - return open(newhMod); + return open((HMODULE)view); } diff --git a/src/coreclr/ildasm/ceeload.h b/src/coreclr/ildasm/ceeload.h index f1c8ec7248b9bb..737a94f9d5315b 100644 --- a/src/coreclr/ildasm/ceeload.h +++ b/src/coreclr/ildasm/ceeload.h @@ -9,6 +9,8 @@ #ifndef CEELoad_H #define CEELoad_H +#include "minipal.h" + class PELoader; // @@ -35,8 +37,8 @@ class PELoader { protected: HMODULE m_hMod; - HANDLE m_hFile; - HANDLE m_hMapFile; + VMToOSInterface::MemoryMapHandle m_hFile; + VMToOSInterface::MemoryMapHandle m_hMapFile; BOOL m_bIsPE32; size_t m_FileSize; size_t m_FileSizeAligned; @@ -54,7 +56,6 @@ class PELoader { PELoader(); ~PELoader(); - BOOL open(const char* moduleNameIn); BOOL open(const WCHAR* moduleNameIn); BOOL open(HMODULE hMod); BOOL getCOMHeader(IMAGE_COR20_HEADER **ppCorHeader); @@ -69,7 +70,7 @@ class PELoader { inline DWORD Signature() { return m_pNT32->Signature; }; inline BYTE* base() { return (BYTE*) m_hMod; }; inline HMODULE getHModule() { return m_hMod; }; - inline HANDLE getHFile() { return m_hFile; } ; + inline size_t getFileSize() { return m_FileSize; }; }; #endif // CEELoad_H diff --git a/src/coreclr/ildasm/dasm.cpp b/src/coreclr/ildasm/dasm.cpp index 617a9b98d517f3..68949122909291 100644 --- a/src/coreclr/ildasm/dasm.cpp +++ b/src/coreclr/ildasm/dasm.cpp @@ -5820,7 +5820,7 @@ void DumpStatistics(IMAGE_COR20_HEADER *CORHeader, void* GUICookie) TableSeenReset(); metaSize = 0; - sprintf_s(szString,SZSTRING_SIZE,"// File size : %d", fileSize = SafeGetFileSize(g_pPELoader->getHFile(), NULL)); + sprintf_s(szString,SZSTRING_SIZE,"// File size : %d", fileSize = (int)g_pPELoader->getFileSize()); printLine(GUICookie,szStr); if (g_pPELoader->IsPE32()) diff --git a/src/coreclr/ildasm/dis.cpp b/src/coreclr/ildasm/dis.cpp index 9afb147a4847f8..04d95e3e01781c 100644 --- a/src/coreclr/ildasm/dis.cpp +++ b/src/coreclr/ildasm/dis.cpp @@ -39,8 +39,6 @@ extern unsigned g_uConsoleCP; extern BOOL g_fThisIsInstanceMethod; extern unsigned g_uCodePage; -extern HANDLE hConsoleOut; -extern HANDLE hConsoleErr; // globals for source file info ULONG_PTR ulWasFileToken = 0xFFFFFFFF; GUID guidWasLang={0}, guidWasLangVendor={0},guidWasDoc={0}; @@ -131,10 +129,6 @@ char* AnsiToUtf(_In_ __nullterminated const char* sz) { return UnicodeToUtf(Ansi static void UnicodeToConsoleOrMsgBox(_In_ __nullterminated const WCHAR* wz) { { - //DWORD dw; - //char* sz = UnicodeToAnsi(wz); - //WriteFile(hConsoleOut,(CONST VOID *)sz, (ULONG32)strlen(sz),&dw,NULL); - //WriteFile(hConsoleOut,(CONST VOID *)"\r\n", 2,&dw,NULL); printf("%s\n",UnicodeToAnsi(wz)); } } @@ -156,12 +150,8 @@ static void ToGUIOrFile(_In_ __nullterminated const char* sz, void* GUICookie) void printError(void* GUICookie, _In_ __nullterminated const char* string) { { - //DWORD dw; const char* sz = ERRORMSG(string); if(GUICookie) printLine(GUICookie, sz); - //sz = UnicodeToAnsi(UtfToUnicode(string)); - //WriteFile(hConsoleErr,(CONST VOID *)sz, (ULONG32)strlen(sz),&dw,NULL); - //WriteFile(hConsoleErr,(CONST VOID *)"\r\n", 2,&dw,NULL); fprintf(stderr,"%s\n",UnicodeToAnsi(UtfToUnicode(string))); } } diff --git a/src/coreclr/ildasm/windasm.cpp b/src/coreclr/ildasm/windasm.cpp index 4bf36bb6c08962..6e33c86ceeed0a 100644 --- a/src/coreclr/ildasm/windasm.cpp +++ b/src/coreclr/ildasm/windasm.cpp @@ -82,8 +82,6 @@ extern BOOL g_fDumpMetaInfo; extern ULONG g_ulMetaInfoFilter; HINSTANCE g_hInstance; HINSTANCE g_hResources; -HANDLE hConsoleOut=NULL; -HANDLE hConsoleErr=NULL; // These are implemented in DASM.CPP: BOOL Init(); void Uninit(); @@ -137,6 +135,9 @@ char* EqualOrColon(_In_ __nullterminated char* szArg) void GetInputFileFullPath() { +#ifdef TARGET_UNIX + MultiByteToWideChar(g_uConsoleCP, 0, g_szInputFile, -1, g_wszFullInputFile, MAX_PATH + 1); +#else // We need the input file's full path to make uses of it later, despite changing CurrentDirectory // First, convert back up to UTF16 @@ -148,6 +149,7 @@ void GetInputFileFullPath() // Get the full path len = GetFullPathName(wzArg, MAX_PATH, g_wszFullInputFile, NULL); VDELETE(wzArg); +#endif } int ProcessOneArg(_In_ __nullterminated char* szArg, _Out_ char** ppszObjFileName) @@ -481,8 +483,6 @@ int main(int argc, char* argv[]) g_pszObjFileName = NULL; g_szAsmCodeIndent[0] = 0; - hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE); - hConsoleErr = GetStdHandle(STD_ERROR_HANDLE); #ifndef TARGET_UNIX // Dev11 #5320 - pull the localized resource loader up so if ParseCmdLineW need resources, they're already loaded @@ -506,52 +506,46 @@ int main(int argc, char* argv[]) g_fHideFOA = FALSE; g_fHidePrivScope = FALSE; } - if(hConsoleOut != INVALID_HANDLE_VALUE) //First pass: console + g_uConsoleCP = GetConsoleOutputCP(); + + if(iCommandLineParsed) { - g_uConsoleCP = GetConsoleOutputCP(); + if(iCommandLineParsed > 0) PrintLogo(); + SyntaxCon(); + exit((iCommandLineParsed == 1) ? 0 : 1); + } - if(iCommandLineParsed) + DWORD exitCode = 1; + if(g_szInputFile[0] == 0) + { + SyntaxCon(); + exit(1); + } + g_pFile = NULL; + if(g_szOutputFile[0]) + { + g_pFile = OpenOutput(g_szOutputFile); + if(g_pFile == NULL) { - if(iCommandLineParsed > 0) PrintLogo(); - SyntaxCon(); - exit((iCommandLineParsed == 1) ? 0 : 1); - } - - { - DWORD exitCode = 1; - if(g_szInputFile[0] == 0) - { - SyntaxCon(); - exit(1); - } - g_pFile = NULL; - if(g_szOutputFile[0]) - { - g_pFile = OpenOutput(g_szOutputFile); - if(g_pFile == NULL) - { - char sz[4096]; - sprintf_s(sz,4096,RstrUTF(IDS_E_CANTOPENOUT)/*"Unable to open '%s' for output."*/, g_szOutputFile); - g_uCodePage = CP_ACP; - printError(NULL,sz); - exit(1); - } - } - else // console output -- force the code page to ANSI - { - g_uCodePage = g_uConsoleCP; - g_fDumpRTF = FALSE; - g_fDumpHTML = FALSE; - } - if (Init() == TRUE) - { - exitCode = DumpFile() ? 0 : 1; - Cleanup(); - } - Uninit(); - exit(exitCode); + char sz[4096]; + sprintf_s(sz,4096,RstrUTF(IDS_E_CANTOPENOUT)/*"Unable to open '%s' for output."*/, g_szOutputFile); + g_uCodePage = CP_ACP; + printError(NULL,sz); + exit(1); } } - return 0; + else // console output -- force the code page to ANSI + { + g_uCodePage = g_uConsoleCP; + g_fDumpRTF = FALSE; + g_fDumpHTML = FALSE; + } + if (Init() == TRUE) + { + exitCode = DumpFile() ? 0 : 1; + Cleanup(); + } + Uninit(); + return exitCode; } diff --git a/src/coreclr/inc/holder.h b/src/coreclr/inc/holder.h index d05899b07cf199..50b4df9b54f4df 100644 --- a/src/coreclr/inc/holder.h +++ b/src/coreclr/inc/holder.h @@ -1030,6 +1030,7 @@ struct HandleTraits final }; using HandleHolder = LifetimeHolder; +#ifdef HOST_WINDOWS struct MapViewTraits final { using Type = void*; @@ -1043,6 +1044,7 @@ struct MapViewTraits final }; using MapViewHolder = LifetimeHolder; +#endif // HOST_WINDOWS template struct LocalAllocTraits final diff --git a/src/coreclr/inc/longfilepathwrappers.h b/src/coreclr/inc/longfilepathwrappers.h index adcd3517a43b24..445449080f8f20 100644 --- a/src/coreclr/inc/longfilepathwrappers.h +++ b/src/coreclr/inc/longfilepathwrappers.h @@ -27,8 +27,6 @@ CreateFileWrapper( int u16_fopen_wrapper(FILE** stream, const WCHAR* filename, const WCHAR* mode); -#endif //HOST_WINDOWS - DWORD SearchPathWrapper( _In_opt_ LPCWSTR lpPath, @@ -39,6 +37,8 @@ SearchPathWrapper( _Out_opt_ LPWSTR * lpFilePart ); +#endif //HOST_WINDOWS + DWORD GetModuleFileNameWrapper( _In_opt_ HMODULE hModule, diff --git a/src/coreclr/inc/safewrap.h b/src/coreclr/inc/safewrap.h index a23dafd78c5b55..48e376a2027139 100644 --- a/src/coreclr/inc/safewrap.h +++ b/src/coreclr/inc/safewrap.h @@ -80,6 +80,7 @@ DWORD ClrReportEvent( PSID lpUserSid, LPCWSTR pMessage); +#ifdef HOST_WINDOWS //***************************************************************************** // This provides a wrapper around GetFileSize() that forces it to fail // if the file is >4g and pdwHigh is NULL. Other than that, it acts like @@ -122,5 +123,6 @@ DWORD inline SafeGetFileSize(HANDLE hFile, DWORD *pdwHigh) } } +#endif // HOST_WINDOWS #endif // _safewrap_h_ diff --git a/src/coreclr/inc/winwrap.h b/src/coreclr/inc/winwrap.h index 1d16e5ff300ed5..0fc7a0d25668e1 100644 --- a/src/coreclr/inc/winwrap.h +++ b/src/coreclr/inc/winwrap.h @@ -40,15 +40,14 @@ #define WszLoadLibrary LoadLibraryExWrapper #define WszCreateFile CreateFileWrapper #define fopen_lp u16_fopen_wrapper +#define WszSearchPath SearchPathWrapper #else // HOST_WINDOWS #define WszLoadLibrary LoadLibraryExW -#define WszCreateFile CreateFileW #define fopen_lp u16_fopen_s #endif // HOST_WINDOWS //APIS which have a buffer as an out parameter #define WszGetEnvironmentVariable GetEnvironmentVariableWrapper -#define WszSearchPath SearchPathWrapper #define WszGetModuleFileName GetModuleFileNameWrapper #ifdef HOST_WINDOWS diff --git a/src/coreclr/md/enc/stgio.cpp b/src/coreclr/md/enc/stgio.cpp index 802169c2059f57..a781c83237d7bf 100644 --- a/src/coreclr/md/enc/stgio.cpp +++ b/src/coreclr/md/enc/stgio.cpp @@ -38,6 +38,12 @@ #include "corerror.h" #include "posterror.h" #include "pedecoder.h" + +#ifndef HOST_WINDOWS +#include +#include +#include +#endif #include "pedecoder.inl" #include @@ -59,6 +65,128 @@ inline HRESULT MapFileError(DWORD error) return (PostError(HRESULT_FROM_WIN32(error))); } +#ifdef HOST_WINDOWS +static STGIO_FILE StgIOCreateFile(LPCWSTR szName, bool fFailIfThere) +{ + return WszCreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, 0, + fFailIfThere ? CREATE_NEW : CREATE_ALWAYS, 0, 0); +} + +static STGIO_FILE StgIOOpenFileForRead(LPCWSTR szName, DWORD dwFileSharingFlags) +{ + return WszCreateFile(szName, GENERIC_READ, dwFileSharingFlags, 0, OPEN_EXISTING, 0, 0); +} + +static ULONG StgIOGetFileSize(STGIO_FILE hFile) +{ + return ::SetFilePointer(hFile, 0, 0, FILE_END); +} + +static ULONG StgIOSeek(STGIO_FILE hFile, int lVal, ULONG fMoveType) +{ + return ::SetFilePointer(hFile, lVal, 0, fMoveType); +} + +static BOOL StgIORead(STGIO_FILE hFile, void *pbBuff, ULONG cbBuff, ULONG *pcbRead) +{ + return ::ReadFile(hFile, pbBuff, cbBuff, pcbRead, 0); +} + +static BOOL StgIOWrite(STGIO_FILE hFile, const void *pbBuff, ULONG cbWrite, ULONG *pcbWritten) +{ + return ::WriteFile(hFile, pbBuff, cbWrite, pcbWritten, 0); +} + +static BOOL StgIOFlush(STGIO_FILE hFile) +{ + return ::FlushFileBuffers(hFile); +} + +static void StgIOCloseFile(STGIO_FILE hFile) +{ + CloseHandle(hFile); +} + +static VMToOSInterface::MemoryMapHandle StgIOGetMappableFile(STGIO_FILE hFile) +{ + return hFile; +} + +static HRESULT StgIOLastFileError() +{ + return MapFileError(GetLastError()); +} +#else // HOST_WINDOWS +static STGIO_FILE StgIOOpenFile(LPCWSTR szName, const WCHAR *szMode) +{ + FILE *stream; + int error = u16_fopen_s(&stream, szName, szMode); + if (error != 0) + { + errno = error; + return STGIO_INVALID_FILE; + } + return stream; +} + +static STGIO_FILE StgIOCreateFile(LPCWSTR szName, bool fFailIfThere) +{ + return StgIOOpenFile(szName, fFailIfThere ? W("w+xb") : W("w+b")); +} + +static STGIO_FILE StgIOOpenFileForRead(LPCWSTR szName, DWORD) +{ + return StgIOOpenFile(szName, W("rb")); +} + +static ULONG StgIOGetFileSize(STGIO_FILE hFile) +{ + return (ULONG)fgetsize(hFile); +} + +static ULONG StgIOSeek(STGIO_FILE hFile, int lVal, ULONG fMoveType) +{ + static_assert(FILE_BEGIN == SEEK_SET && FILE_CURRENT == SEEK_CUR && FILE_END == SEEK_END, ""); + if (fseek(hFile, lVal, (int)fMoveType) != 0) + return 0xffffffff; + return (ULONG)ftell(hFile); +} + +static BOOL StgIORead(STGIO_FILE hFile, void *pbBuff, ULONG cbBuff, ULONG *pcbRead) +{ + *pcbRead = (ULONG)fread(pbBuff, 1, cbBuff, hFile); + return !ferror(hFile); +} + +static BOOL StgIOWrite(STGIO_FILE hFile, const void *pbBuff, ULONG cbWrite, ULONG *pcbWritten) +{ + *pcbWritten = (ULONG)fwrite(pbBuff, 1, cbWrite, hFile); + return *pcbWritten == cbWrite; +} + +static BOOL StgIOFlush(STGIO_FILE hFile) +{ + return fflush(hFile) == 0 && fsync(fileno(hFile)) == 0; +} + +static void StgIOCloseFile(STGIO_FILE hFile) +{ + fclose(hFile); +} + +#ifndef TARGET_WASM +static VMToOSInterface::MemoryMapHandle StgIOGetMappableFile(STGIO_FILE hFile) +{ + return fileno(hFile); +} +#endif // !TARGET_WASM + +static HRESULT StgIOLastFileError() +{ + return PostError(HRESULTFromErr(errno)); +} +#endif // HOST_WINDOWS + // Static to class. int StgIO::m_iPageSize=0; // Size of an OS page. int StgIO::m_iCacheSize=0; // Size for the write cache. @@ -91,9 +219,10 @@ void StgIO::CtorInit() m_bRewrite = false; m_bFreeMem = false; m_pIStream = 0; - m_hFile = INVALID_HANDLE_VALUE; + m_hFile = STGIO_INVALID_FILE; m_hModule = NULL; - m_hMapping = 0; + m_hMapping = VMToOSInterface::InvalidMemoryMapHandle; + m_cbMapping = 0; m_pBaseData = 0; m_pData = 0; m_cbData = 0; @@ -199,11 +328,9 @@ HRESULT StgIO::Open( // Return code. // but would be much slower. // Create the new file, overwriting only if caller allows it. - if ((m_hFile = WszCreateFile(szName, GENERIC_READ | GENERIC_WRITE, 0, 0, - (fFlags & DBPROP_TMODEF_FAILIFTHERE) ? CREATE_NEW : CREATE_ALWAYS, - 0, 0)) == INVALID_HANDLE_VALUE) + if ((m_hFile = StgIOCreateFile(szName, (fFlags & DBPROP_TMODEF_FAILIFTHERE) != 0)) == STGIO_INVALID_FILE) { - return (MapFileError(GetLastError())); + return (StgIOLastFileError()); } // Data will come from the file. @@ -214,7 +341,7 @@ HRESULT StgIO::Open( // Return code. else if ((fFlags & DBPROP_TMODEF_WRITE) == 0) { // We have not opened the file nor loaded it as module - _ASSERTE(m_hFile == INVALID_HANDLE_VALUE); + _ASSERTE(m_hFile == STGIO_INVALID_FILE); _ASSERTE(m_hModule == NULL); // Open the file for read. Sharing is determined by caller, it can @@ -269,26 +396,23 @@ HRESULT StgIO::Open( // Return code. if (m_hModule == NULL) { // We didn't get the loaded module (we either didn't want to or it failed) - HandleHolder hFile(WszCreateFile(szName, - GENERIC_READ, - dwFileSharingFlags, - 0, - OPEN_EXISTING, - 0, - 0)); + STGIO_FILE hFile = StgIOOpenFileForRead(szName, dwFileSharingFlags); - if (hFile == INVALID_HANDLE_VALUE) - return (MapFileError(GetLastError())); + if (hFile == STGIO_INVALID_FILE) + return (StgIOLastFileError()); // Get size of file. - m_cbData = ::SetFilePointer(hFile, 0, 0, FILE_END); + m_cbData = StgIOGetFileSize(hFile); // Can't read anything from an empty file. if (m_cbData == 0) + { + StgIOCloseFile(hFile); return (PostError(CLDB_E_NO_DATA)); + } // Data will come from the file. - m_hFile = hFile.Detach(); + m_hFile = hFile; m_iType = STGIO_HFILE; } @@ -360,8 +484,8 @@ void StgIO::Close() case STGIO_HFILE: { // Free the file handle. - if (m_hFile != INVALID_HANDLE_VALUE) - CloseHandle(m_hFile); + if (m_hFile != STGIO_INVALID_FILE) + StgIOCloseFile(m_hFile); // If we allocated space for in memory paging, then free it. } @@ -472,7 +596,7 @@ HRESULT StgIO::Read( // Return code. case STGIO_HFILE: case STGIO_HMODULE: { - _ASSERTE((m_hFile != INVALID_HANDLE_VALUE) || (m_hModule != NULL)); + _ASSERTE((m_hFile != STGIO_INVALID_FILE) || (m_hModule != NULL)); // Backing store does its own paging. if (IsBackingStore() || IsMemoryMapped()) @@ -489,7 +613,7 @@ HRESULT StgIO::Read( // Return code. // If there is no backing store, this is just a read operation. else { - _ASSERTE((m_iType == STGIO_HFILE) && (m_hFile != INVALID_HANDLE_VALUE)); + _ASSERTE((m_iType == STGIO_HFILE) && (m_hFile != STGIO_INVALID_FILE)); _ASSERTE(m_hModule == NULL); ULONG cbTemp = 0; @@ -624,8 +748,8 @@ HRESULT StgIO::Seek( // New offset. case STGIO_HFILE: { // Use the file system's move. - _ASSERTE(m_hFile != INVALID_HANDLE_VALUE); - cbRtn = ::SetFilePointer(m_hFile, lVal, 0, fMoveType); + _ASSERTE(m_hFile != STGIO_INVALID_FILE); + cbRtn = StgIOSeek(m_hFile, lVal, fMoveType); // Save the location redundantly. if (cbRtn != 0xffffffff) @@ -736,7 +860,6 @@ HRESULT StgIO::MapFileToMem( // Return code. ULONG *pcbSize, // Return size of data. LPSECURITY_ATTRIBUTES pAttributes) // Security token. { - char rcShared[MAXSHMEM]; // ANSI version of shared name. HRESULT hr = S_OK; // Don't penalize for multiple calls. Also, allow calls for mem type so @@ -785,14 +908,14 @@ HRESULT StgIO::MapFileToMem( // Return code. // If it is for exclusive, then we need to keep the handle open so the // file is locked, preventing other readers. Also leave it open if // in read/write mode so we can truncate and rewrite. - if (m_hFile == INVALID_HANDLE_VALUE || + if (m_hFile == STGIO_INVALID_FILE || ((m_fFlags & DBPROP_TMODEF_EXCLUSIVE) == 0 && (m_fFlags & DBPROP_TMODEF_WRITE) == 0)) { // If there was a handle open, then free it. - if (m_hFile != INVALID_HANDLE_VALUE) + if (m_hFile != STGIO_INVALID_FILE) { - VERIFY(CloseHandle(m_hFile)); - m_hFile = INVALID_HANDLE_VALUE; + StgIOCloseFile(m_hFile); + m_hFile = STGIO_INVALID_FILE; } // Free the stream pointer. else @@ -815,40 +938,30 @@ HRESULT StgIO::MapFileToMem( // Return code. else { // Now we will map, so better have it right. - _ASSERTE(m_hFile != INVALID_HANDLE_VALUE || m_iType == STGIO_STREAM); + _ASSERTE(m_hFile != STGIO_INVALID_FILE || m_iType == STGIO_STREAM); _ASSERTE(m_rgPageMap == 0); +#ifndef TARGET_WASM // For read mode, use a memory mapped file since the size will never // change for the life of the handle. if ((m_fFlags & DBPROP_TMODEF_WRITE) == 0 && m_iType != STGIO_STREAM) { // Create a mapping object for the file. - _ASSERTE(m_hMapping == 0); - - DWORD dwProtectionFlags = PAGE_READONLY; + _ASSERTE(m_hMapping == VMToOSInterface::InvalidMemoryMapHandle); - if ((m_hMapping = CreateFileMapping(m_hFile, pAttributes, dwProtectionFlags, - 0, 0, nullptr)) == 0) + if ((m_hMapping = VMToOSInterface::CreateMemoryMapping(StgIOGetMappableFile(m_hFile), 0, + VMToOSInterface::MemoryProtection::ReadOnly)) == VMToOSInterface::InvalidMemoryMapHandle) { - return (MapFileError(GetLastError())); + return (PostError(VMToOSInterface::GetLastMemoryMappingError())); } m_mtMappedType = MTYPE_FLAT; - // Check to see if the memory already exists, in which case we have - // no guarantees it is the right piece of data. - if (GetLastError() == ERROR_ALREADY_EXISTS) - { - hr = PostError(CLDB_E_SMDUPLICATE, rcShared); - goto ErrExit; - } // Now map the file into memory so we can read from pointer access. - // Note: Added a check for IsBadReadPtr per the Services team which - // indicates that under some conditions this API can give you back - // a totally bogus pointer. - if ((m_pBaseData = m_pData = MapViewOfFile(m_hMapping, FILE_MAP_READ, - 0, 0, 0)) == 0) + m_cbMapping = m_cbData; + if ((m_pBaseData = m_pData = VMToOSInterface::MapMemory(m_hMapping, 0, nullptr, m_cbMapping, + VMToOSInterface::MemoryProtection::ReadOnly, true)) == 0) { - hr = MapFileError(GetLastError()); + hr = PostError(VMToOSInterface::GetLastMemoryMappingError()); if (SUCCEEDED(hr)) { _ASSERTE_MSG(FALSE, "Error code doesn't indicate error."); @@ -865,6 +978,7 @@ HRESULT StgIO::MapFileToMem( // Return code. // throw away our cached copy. Memory mapped files are not good for this // case due to poor write characteristics. else +#endif // !TARGET_WASM { ULONG iMaxSize; // How much memory required for file. @@ -899,9 +1013,11 @@ HRESULT StgIO::MapFileToMem( // Return code. // Check for errors and clean up. if (FAILED(hr)) { - if (m_hMapping) - CloseHandle(m_hMapping); - m_hMapping = 0; +#ifndef TARGET_WASM + if (m_hMapping != VMToOSInterface::InvalidMemoryMapHandle) + VMToOSInterface::CloseMemoryMapping(m_hMapping); +#endif // !TARGET_WASM + m_hMapping = VMToOSInterface::InvalidMemoryMapHandle; m_pBaseData = m_pData = 0; m_cbData = 0; } @@ -1085,12 +1201,12 @@ HRESULT StgIO::FlushFileBuffers() { _ASSERTE(!IsReadOnly()); - if (m_hFile != INVALID_HANDLE_VALUE) + if (m_hFile != STGIO_INVALID_FILE) { - if (::FlushFileBuffers(m_hFile)) + if (StgIOFlush(m_hFile)) return (S_OK); else - return (MapFileError(GetLastError())); + return (StgIOLastFileError()); } return (S_OK); } @@ -1147,11 +1263,11 @@ HRESULT StgIO::WriteToDisk( // Return code. case STGIO_HFILEMEM: { // Use the file system's move. - _ASSERTE(m_hFile != INVALID_HANDLE_VALUE); + _ASSERTE(m_hFile != STGIO_INVALID_FILE); // Do the write to disk. - if (!::WriteFile(m_hFile, pbBuff, cbWrite, pcbWritten, 0)) - hr = MapFileError(GetLastError()); + if (!StgIOWrite(m_hFile, pbBuff, cbWrite, pcbWritten)) + hr = StgIOLastFileError(); } break; @@ -1200,9 +1316,9 @@ HRESULT StgIO::ReadFromDisk( // Return code. // Read only from file to avoid recursive logic. if (m_iType == STGIO_HFILE || m_iType == STGIO_HFILEMEM) { - if (::ReadFile(m_hFile, pbBuff, cbBuff, pcbRead, 0)) + if (StgIORead(m_hFile, pbBuff, cbBuff, pcbRead)) return (S_OK); - return (MapFileError(GetLastError())); + return (StgIOLastFileError()); } // Read directly from stream. else @@ -1220,12 +1336,14 @@ void StgIO::FreePageMap() // If a small file was allocated, then free that memory. if (m_bFreeMem && m_pBaseData) FreeMemory(m_pBaseData); +#ifndef TARGET_WASM // For mmf, close handles and free resources. - else if (m_hMapping && m_pBaseData) + else if (m_hMapping != VMToOSInterface::InvalidMemoryMapHandle && m_pBaseData) { - VERIFY(UnmapViewOfFile(m_pBaseData)); - VERIFY(CloseHandle(m_hMapping)); + VERIFY(VMToOSInterface::UnmapMemory(m_pBaseData, m_cbMapping) == 0); + VERIFY(VMToOSInterface::CloseMemoryMapping(m_hMapping)); } +#endif // !TARGET_WASM // For our own system, free memory. else if (m_rgPageMap && m_pBaseData) { @@ -1239,7 +1357,8 @@ void StgIO::FreePageMap() } m_pBaseData = 0; - m_hMapping = 0; + m_hMapping = VMToOSInterface::InvalidMemoryMapHandle; + m_cbMapping = 0; m_cbData = 0; } diff --git a/src/coreclr/md/inc/stgio.h b/src/coreclr/md/inc/stgio.h index a9561d1445a6d8..64939c46f95022 100644 --- a/src/coreclr/md/inc/stgio.h +++ b/src/coreclr/md/inc/stgio.h @@ -36,6 +36,16 @@ #ifndef __STGIO_H_ #define __STGIO_H_ +#include "minipal.h" + +#ifdef HOST_WINDOWS +typedef HANDLE STGIO_FILE; +#define STGIO_INVALID_FILE INVALID_HANDLE_VALUE +#else +typedef FILE* STGIO_FILE; +#define STGIO_INVALID_FILE nullptr +#endif + #define MAXSHMEM 32 #define STGIO_READ 0x1 @@ -234,7 +244,7 @@ class StgIO int IsBackingStore() { return (m_rgPageMap != 0); } int IsMemoryMapped() - { return ((m_hMapping != NULL) || (m_hModule != NULL)); } + { return ((m_hMapping != VMToOSInterface::InvalidMemoryMapHandle) || (m_hModule != NULL)); } void CtorInit(); HRESULT WriteToDisk(const void *pbBuff, ULONG cbWrite, ULONG *pcbWritten); @@ -252,8 +262,9 @@ class StgIO // Handles. IStream * m_pIStream; // For save to stream instead of file. - HANDLE m_hFile; // The actual file with contents. - HANDLE m_hMapping; // Mapping handle. + STGIO_FILE m_hFile; // The actual file with contents. + VMToOSInterface::MemoryMapHandle m_hMapping; // Mapping handle. + SIZE_T m_cbMapping; // Size of the mapped view. HMODULE m_hModule; // If we load with LoadLibrary, this is the module (otherwise NULL). void * m_pBaseData; // Base address for memory mapped file. void * m_pData; // For memory mapped file read. diff --git a/src/coreclr/minipal/Unix/dn-stdio.cpp b/src/coreclr/minipal/Unix/dn-stdio.cpp index c60c72e476eae6..e8f0169b7e4ffc 100644 --- a/src/coreclr/minipal/Unix/dn-stdio.cpp +++ b/src/coreclr/minipal/Unix/dn-stdio.cpp @@ -86,7 +86,6 @@ int fsetpos_64(FILE* stream, int64_t pos) HRESULT HRESULTFromErr(int err) { // maps the common I/O errors - // based on FILEGetLastErrorFromErrno int32_t win32Err; diff --git a/src/coreclr/minipal/Windows/dn-stdio.cpp b/src/coreclr/minipal/Windows/dn-stdio.cpp index 589444e7be10ad..c9a937f30e410c 100644 --- a/src/coreclr/minipal/Windows/dn-stdio.cpp +++ b/src/coreclr/minipal/Windows/dn-stdio.cpp @@ -33,7 +33,6 @@ int fsetpos_64(FILE* stream, int64_t pos) HRESULT HRESULTFromErr(int err) { // maps the common I/O errors - // based on FILEGetLastErrorFromErrno // stdio functions aren't guaranteed to preserve GetLastError. // errno/ferror should be used as source of truth. diff --git a/src/coreclr/pal/inc/pal.h b/src/coreclr/pal/inc/pal.h index 3d9d91e74689e4..4f932f3182594f 100644 --- a/src/coreclr/pal/inc/pal.h +++ b/src/coreclr/pal/inc/pal.h @@ -421,39 +421,6 @@ typedef struct _SECURITY_ATTRIBUTES { #define INVALID_SET_FILE_POINTER ((DWORD)-1) -PALIMPORT -HANDLE -PALAPI -CreateFileW( - IN LPCWSTR lpFileName, - IN DWORD dwDesiredAccess, - IN DWORD dwShareMode, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes, - IN DWORD dwCreationDisposition, - IN DWORD dwFlagsAndAttributes, - IN HANDLE hTemplateFile); - -#ifdef UNICODE -#define CreateFile CreateFileW -#else -#define CreateFile CreateFileA -#endif - - -PALIMPORT -DWORD -PALAPI -SearchPathW( - IN LPCWSTR lpPath, - IN LPCWSTR lpFileName, - IN LPCWSTR lpExtension, - IN DWORD nBufferLength, - OUT LPWSTR lpBuffer, - OUT LPWSTR *lpFilePart - ); - -#define SearchPath SearchPathW - typedef struct _OVERLAPPED { ULONG_PTR Internal; ULONG_PTR InternalHigh; @@ -462,100 +429,15 @@ typedef struct _OVERLAPPED { HANDLE hEvent; } OVERLAPPED, *LPOVERLAPPED; -PALIMPORT -BOOL -PALAPI -WriteFile( - IN HANDLE hFile, - IN LPCVOID lpBuffer, - IN DWORD nNumberOfBytesToWrite, - OUT LPDWORD lpNumberOfBytesWritten, - IN LPOVERLAPPED lpOverlapped); - -PALIMPORT -BOOL -PALAPI -ReadFile( - IN HANDLE hFile, - OUT LPVOID lpBuffer, - IN DWORD nNumberOfBytesToRead, - OUT LPDWORD lpNumberOfBytesRead, - IN LPOVERLAPPED lpOverlapped); - #define STD_INPUT_HANDLE ((DWORD)-10) #define STD_OUTPUT_HANDLE ((DWORD)-11) #define STD_ERROR_HANDLE ((DWORD)-12) -PALIMPORT -HANDLE -PALAPI -GetStdHandle( - IN DWORD nStdHandle); - -PALIMPORT -DWORD -PALAPI -SetFilePointer( - IN HANDLE hFile, - IN LONG lDistanceToMove, - IN PLONG lpDistanceToMoveHigh, - IN DWORD dwMoveMethod); - -PALIMPORT -BOOL -PALAPI -SetFilePointerEx( - IN HANDLE hFile, - IN LARGE_INTEGER liDistanceToMove, - OUT PLARGE_INTEGER lpNewFilePointer, - IN DWORD dwMoveMethod); - -PALIMPORT -DWORD -PALAPI -GetFileSize( - IN HANDLE hFile, - OUT LPDWORD lpFileSizeHigh); - -PALIMPORT -BOOL -PALAPI GetFileSizeEx( - IN HANDLE hFile, - OUT PLARGE_INTEGER lpFileSize); - -PALIMPORT -BOOL -PALAPI -FlushFileBuffers( - IN HANDLE hFile); - PALIMPORT UINT PALAPI GetConsoleOutputCP(); -PALIMPORT -DWORD -PALAPI -GetFullPathNameW( - IN LPCWSTR lpFileName, - IN DWORD nBufferLength, - OUT LPWSTR lpBuffer, - OUT LPWSTR *lpFilePart); - -#ifdef UNICODE -#define GetFullPathName GetFullPathNameW -#else -#define GetFullPathName GetFullPathNameA -#endif - -PALIMPORT -DWORD -PALAPI -GetTempPathA( - IN DWORD nBufferLength, - OUT LPSTR lpBuffer); - PALIMPORT DWORD PALAPI @@ -2140,19 +2022,6 @@ PALIMPORT BOOL PALAPI PAL_GetUnwindInfoSize(SIZE_T baseAddress, ULONG64 ehFrameH #define MEM_RELEASE 0x8000 #define MEM_FREE 0x10000 -PALIMPORT -HANDLE -PALAPI -CreateFileMappingW( - IN HANDLE hFile, - IN LPSECURITY_ATTRIBUTES lpFileMappingAttributes, - IN DWORD flProtect, - IN DWORD dwMaxmimumSizeHigh, - IN DWORD dwMaximumSizeLow, - IN LPCWSTR lpName); - -#define CreateFileMapping CreateFileMappingW - #define SECTION_QUERY 0x0001 #define SECTION_MAP_WRITE 0x0002 #define SECTION_MAP_READ 0x0004 @@ -2165,33 +2034,6 @@ CreateFileMappingW( typedef INT_PTR (PALAPI_NOEXPORT *FARPROC)(); -PALIMPORT -LPVOID -PALAPI -MapViewOfFile( - IN HANDLE hFileMappingObject, - IN DWORD dwDesiredAccess, - IN DWORD dwFileOffsetHigh, - IN DWORD dwFileOffsetLow, - IN SIZE_T dwNumberOfBytesToMap); - -PALIMPORT -LPVOID -PALAPI -MapViewOfFileEx( - IN HANDLE hFileMappingObject, - IN DWORD dwDesiredAccess, - IN DWORD dwFileOffsetHigh, - IN DWORD dwFileOffsetLow, - IN SIZE_T dwNumberOfBytesToMap, - IN LPVOID lpBaseAddress); - -PALIMPORT -BOOL -PALAPI -UnmapViewOfFile( - IN LPCVOID lpBaseAddress) noexcept; - PALIMPORT HMODULE PALAPI diff --git a/src/coreclr/pal/inc/palprivate.h b/src/coreclr/pal/inc/palprivate.h index 0fe566b7cc17d8..58629c00204289 100644 --- a/src/coreclr/pal/inc/palprivate.h +++ b/src/coreclr/pal/inc/palprivate.h @@ -8,66 +8,6 @@ extern "C" { #endif -PALIMPORT -HANDLE -PALAPI -CreateFileA( - IN LPCSTR lpFileName, - IN DWORD dwDesiredAccess, - IN DWORD dwShareMode, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes, - IN DWORD dwCreationDisposition, - IN DWORD dwFlagsAndAttributes, - IN HANDLE hTemplateFile); - -PALIMPORT -BOOL -PALAPI -DeleteFileA( - IN LPCSTR lpFileName); - -PALIMPORT -BOOL -PALAPI -CreateDirectoryA( - IN LPCSTR lpPathName, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes); - -PALIMPORT -BOOL -PALAPI -CreateDirectoryW( - IN LPCWSTR lpPathName, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes); - -PALIMPORT -DWORD -PALAPI -GetFullPathNameA( - IN LPCSTR lpFileName, - IN DWORD nBufferLength, - OUT LPSTR lpBuffer, - OUT LPSTR *lpFilePart); - -PALIMPORT -DWORD -PALAPI -GetTempPathA( - IN DWORD nBufferLength, - OUT LPSTR lpBuffer); - -PALIMPORT -BOOL -PALAPI -SetCurrentDirectoryW( - IN LPCWSTR lpPathName); - -PALIMPORT -BOOL -PALAPI -SetCurrentDirectoryA( - IN LPCSTR lpPathName); - PALIMPORT HANDLE PALAPI @@ -107,12 +47,6 @@ GetEnvironmentVariableA( OUT LPSTR lpBuffer, IN DWORD nSize); -PALIMPORT -BOOL -PALAPI -RemoveDirectoryW( - IN LPCWSTR lpPathName); - #ifdef __cplusplus } #endif diff --git a/src/coreclr/pal/src/CMakeLists.txt b/src/coreclr/pal/src/CMakeLists.txt index 73cdefc3844afa..a089d2f22ddb13 100644 --- a/src/coreclr/pal/src/CMakeLists.txt +++ b/src/coreclr/pal/src/CMakeLists.txt @@ -151,16 +151,12 @@ set(SOURCES com/guid.cpp cruntime/wchar.cpp exception/seh.cpp - file/directory.cpp - file/file.cpp - file/path.cpp handlemgr/handleapi.cpp handlemgr/handlemgr.cpp init/pal.cpp init/sxs.cpp loader/module.cpp locale/unicode.cpp - map/map.cpp misc/cgroup.cpp misc/dbgmsg.cpp misc/environ.cpp diff --git a/src/coreclr/pal/src/config.h.in b/src/coreclr/pal/src/config.h.in index ede531c82605bf..01df7c7c2f58b2 100644 --- a/src/coreclr/pal/src/config.h.in +++ b/src/coreclr/pal/src/config.h.in @@ -71,13 +71,11 @@ #cmakedefine01 HAVE__SC_PHYS_PAGES #cmakedefine01 HAVE__SC_AVPHYS_PAGES -#cmakedefine01 REALPATH_SUPPORTS_NONEXISTENT_FILES #cmakedefine01 UNWIND_CONTEXT_IS_UCONTEXT_T #cmakedefine01 HAVE_GET_PROC_INFO_IN_RANGE #cmakedefine01 HAVE_SCHED_GET_PRIORITY #cmakedefine01 HAVE_CLOCK_THREAD_CPUTIME #cmakedefine01 HAVE_PTHREAD_CONDATTR_SETCLOCK -#cmakedefine01 ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS #cmakedefine01 HAVE_PROCFS_CTL #cmakedefine01 HAVE_PROCFS_STAT @@ -91,8 +89,6 @@ #cmakedefine01 SET_SCHEDPARAM_NEEDS_PRIVS #define CHECK_TRACE_SPECIFIERS 0 -#define OPEN64_IS_USED_INSTEAD_OF_OPEN 0 #define PAL_IGNORE_NORMAL_THREAD_PRIORITY 0 -#define WRITE_0_BYTES_HANGS_TTY 0 #endif // PAL_CONFIG_H_INCLUDED diff --git a/src/coreclr/pal/src/configure.cmake b/src/coreclr/pal/src/configure.cmake index 1f225844174a3f..79d4592dedf8a5 100644 --- a/src/coreclr/pal/src/configure.cmake +++ b/src/coreclr/pal/src/configure.cmake @@ -177,25 +177,6 @@ check_cxx_symbol_exists(_DEBUG sys/user.h USER_H_DEFINES_DEBUG) check_cxx_symbol_exists(_SC_PHYS_PAGES unistd.h HAVE__SC_PHYS_PAGES) check_cxx_symbol_exists(_SC_AVPHYS_PAGES unistd.h HAVE__SC_AVPHYS_PAGES) -check_cxx_source_runs(" -#include -#include - -int main(void) { - char *path; -#ifdef PATH_MAX - char resolvedPath[PATH_MAX]; -#elif defined(MAXPATHLEN) - char resolvedPath[MAXPATHLEN]; -#else - char resolvedPath[1024]; -#endif - path = realpath(\"a_nonexistent_file\", resolvedPath); - if (path == NULL) { - exit(1); - } - exit(0); -}" REALPATH_SUPPORTS_NONEXISTENT_FILES) set(CMAKE_REQUIRED_LIBRARIES pthread) check_cxx_source_runs(" #include @@ -244,62 +225,6 @@ int main() }" HAVE_CLOCK_THREAD_CPUTIME) set(CMAKE_REQUIRED_LIBRARIES) -check_cxx_source_runs(" -#include -#include -#include -#include -#include -#include -#include - -#define MEM_SIZE 1024 -#define TEMP_FILE_TEMPLATE \"${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeTmp/multiplemaptestXXXXXX\" -int main(void) -{ - char * fname; - int fd; - int ret; - void * pAddr0, * pAddr1; - - fname = (char *)malloc(std::max((size_t)MEM_SIZE, sizeof(TEMP_FILE_TEMPLATE))); - if (!fname) - exit(1); - strcpy(fname, TEMP_FILE_TEMPLATE); - - fd = mkstemp(fname); - if (fd < 0) - exit(1); - - ret = write (fd, (void *)fname, MEM_SIZE); - if (ret < 0) - exit(1); - - pAddr0 = mmap(0, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - pAddr1 = mmap(0, MEM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - - /* In theory we should look for (pAddr1 == MAP_FAILED) && (pAddr1 != MAP_FAILED) - but in case the first test also failed, i.e. we failed to run the test, - let's assume that the system might not allow multiple shared mapping of the - same file region in the same process. The code enabled in this case is - only a fall-back code path. In case the double mmap actually works, virtually - nothing will change and the normal code path will be executed */ - if (pAddr1 == MAP_FAILED) - ret = 1; - else - ret = 0; - - if (pAddr0) - munmap (pAddr0, MEM_SIZE); - if (pAddr1) - munmap (pAddr1, MEM_SIZE); - close(fd); - unlink(fname); - free(fname); - - exit(ret != 1); -}" ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS) - check_cxx_source_runs(" #include #include diff --git a/src/coreclr/pal/src/debug/debug.cpp b/src/coreclr/pal/src/debug/debug.cpp index cebc8503b5262e..cdf7e58cc1f03d 100644 --- a/src/coreclr/pal/src/debug/debug.cpp +++ b/src/coreclr/pal/src/debug/debug.cpp @@ -14,7 +14,6 @@ SET_DEFAULT_DEBUG_CHANNEL(DEBUG); // some headers have code with asserts, so do #include "pal/thread.hpp" #include "pal/procobj.hpp" -#include "pal/file.hpp" #include "pal/palinternal.h" #include "pal/process.h" diff --git a/src/coreclr/pal/src/exception/machexception.cpp b/src/coreclr/pal/src/exception/machexception.cpp index 0c35e32bb159c7..588ddaad4daf97 100644 --- a/src/coreclr/pal/src/exception/machexception.cpp +++ b/src/coreclr/pal/src/exception/machexception.cpp @@ -26,7 +26,6 @@ SET_DEFAULT_DEBUG_CHANNEL(EXCEPT); // some headers have code with asserts, so do #include "pal/utils.h" #include "pal/context.h" #include "pal/process.h" -#include "pal/map.hpp" #include "pal/environ.h" #include diff --git a/src/coreclr/pal/src/file/directory.cpp b/src/coreclr/pal/src/file/directory.cpp deleted file mode 100644 index e06afd0b19e1c2..00000000000000 --- a/src/coreclr/pal/src/file/directory.cpp +++ /dev/null @@ -1,566 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - directory.c - -Abstract: - - Implementation of the file WIN API for the PAL - -Revision History: - - - ---*/ - -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" -#include "pal/file.h" -#include "pal/stackstring.hpp" - -#include -#include -#include -#include -#include - -SET_DEFAULT_DEBUG_CHANNEL(FILE); - - - -/*++ -Function: - CreateDirectoryW - -Note: - lpSecurityAttributes always NULL. - -See MSDN doc. ---*/ -BOOL -PALAPI -CreateDirectoryW( - IN LPCWSTR lpPathName, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes) -{ - BOOL bRet = FALSE; - DWORD dwLastError = 0; - int mb_size; - char *mb_dir = NULL; - - PERF_ENTRY(CreateDirectoryW); - ENTRY("CreateDirectoryW(lpPathName=%p (%S), lpSecurityAttr=%p)\n", - lpPathName?lpPathName:W16_NULLSTRING, - lpPathName?lpPathName:W16_NULLSTRING, lpSecurityAttributes); - - if ( lpSecurityAttributes ) - { - ASSERT("lpSecurityAttributes is not NULL as it should be\n"); - dwLastError = ERROR_INVALID_PARAMETER; - goto done; - } - - /* translate the wide char lpPathName string to multibyte string */ - if(0 == (mb_size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, NULL, 0, - NULL, NULL ))) - { - ASSERT("WideCharToMultiByte failure! error is %d\n", GetLastError()); - dwLastError = ERROR_INTERNAL_ERROR; - goto done; - } - - if (((mb_dir = (char *)malloc(mb_size)) == NULL) || - (WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, mb_dir, mb_size, NULL, - NULL) != mb_size)) - { - ASSERT("WideCharToMultiByte or malloc failure! LastError:%d errno:%d\n", - GetLastError(), errno); - dwLastError = ERROR_INTERNAL_ERROR; - goto done; - } - - bRet = CreateDirectoryA(mb_dir,NULL); -done: - if( dwLastError ) - { - SetLastError( dwLastError ); - } - if (mb_dir != NULL) - { - free(mb_dir); - } - LOGEXIT("CreateDirectoryW returns BOOL %d\n", bRet); - PERF_EXIT(CreateDirectoryW); - return bRet; -} - -/*++ -Routine Name: - - RemoveDirectoryHelper - -Routine Description: - - Core function which removes a directory. Called by RemoveDirectory[AW] - -Parameters: - - LPSTR lpPathName - [in/out] - The directory name to remove. It is converted in place to a unix path. - -Return Value: - - BOOL - - TRUE <=> successful - ---*/ - -static -BOOL -RemoveDirectoryHelper ( - PathCharString& lpPathName, - LPDWORD dwLastError -) -{ - BOOL bRet = FALSE; - *dwLastError = 0; - - if ( rmdir(lpPathName) != 0 ) - { - TRACE("Removal of directory [%s] was unsuccessful, errno = %d.\n", - lpPathName.GetString(), errno); - - switch( errno ) - { - case ENOTDIR: - /* FALL THROUGH */ - case ENOENT: - { - struct stat stat_data; - - if ( stat( lpPathName, &stat_data) == 0 && - (stat_data.st_mode & S_IFMT) == S_IFREG ) - { - /* Not a directory, it is a file. */ - *dwLastError = ERROR_DIRECTORY; - } - else - { - FILEGetProperNotFoundError( lpPathName, dwLastError ); - } - break; - } - case ENOTEMPTY: - *dwLastError = ERROR_DIR_NOT_EMPTY; - break; - default: - *dwLastError = ERROR_ACCESS_DENIED; - } - } - else { - TRACE("Removal of directory [%s] was successful.\n", lpPathName.GetString()); - bRet = TRUE; - } - - return bRet; -} - -/*++ -Function: - RemoveDirectoryW - -See MSDN doc. ---*/ -BOOL -PALAPI -RemoveDirectoryW( - IN LPCWSTR lpPathName) -{ - PathCharString mb_dirPathString; - int mb_size; - DWORD dwLastError = 0; - BOOL bRet = FALSE; - size_t length; - char * mb_dir = NULL; - - PERF_ENTRY(RemoveDirectoryW); - ENTRY("RemoveDirectoryW(lpPathName=%p (%S))\n", - lpPathName?lpPathName:W16_NULLSTRING, - lpPathName?lpPathName:W16_NULLSTRING); - - if (lpPathName == NULL) - { - dwLastError = ERROR_PATH_NOT_FOUND; - goto done; - } - - length = (PAL_wcslen(lpPathName)+1) * 3; - mb_dir = mb_dirPathString.OpenStringBuffer(length); - if (NULL == mb_dir) - { - dwLastError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - - mb_size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, mb_dir, length, - NULL, NULL ); - - if( mb_size == 0 ) - { - mb_dirPathString.CloseBuffer(0); - ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); - dwLastError = ERROR_INTERNAL_ERROR; - goto done; - } - - mb_dirPathString.CloseBuffer(mb_size - 1); - - if ((bRet = RemoveDirectoryHelper (mb_dirPathString, &dwLastError))) - { - TRACE("Removal of directory [%s] was successful.\n", mb_dir); - } - -done: - if( dwLastError ) - { - SetLastError( dwLastError ); - } - - LOGEXIT("RemoveDirectoryW returns BOOL %d\n", bRet); - PERF_EXIT(RemoveDirectoryW); - return bRet; -} - - -/*++ -Function: - GetCurrentDirectoryA - ---*/ -DWORD -GetCurrentDirectoryA(PathCharString& lpBuffer) -{ - DWORD dwDirLen = 0; - DWORD dwLastError = 0; - - char *current_dir; - - PERF_ENTRY(GetCurrentDirectoryA); - ENTRY("GetCurrentDirectoryA(lpBuffer=%p)\n", lpBuffer.GetString()); - - current_dir = lpBuffer.OpenStringBuffer(MAX_PATH); - /* NULL first arg means getcwd will allocate the string */ - current_dir = getcwd( current_dir, MAX_PATH); - - if (current_dir != NULL ) - { - dwDirLen = strlen( current_dir ); - lpBuffer.CloseBuffer(dwDirLen); - goto done; - } - else if ( errno == ERANGE ) - { - lpBuffer.CloseBuffer(0); - current_dir = getcwd( NULL, 0); - } - - if ( !current_dir ) - { - WARN("Getcwd failed with errno=%d [%s]\n", errno, strerror(errno)); - dwLastError = DIRGetLastErrorFromErrno(); - dwDirLen = 0; - goto done; - } - - dwDirLen = strlen( current_dir ); - lpBuffer.Set(current_dir, dwDirLen); - free(current_dir); -done: - - if ( dwLastError ) - { - SetLastError(dwLastError); - } - - LOGEXIT("GetCurrentDirectoryA returns DWORD %u\n", dwDirLen); - PERF_EXIT(GetCurrentDirectoryA); - return dwDirLen; -} - -/*++ -Function: - SetCurrentDirectoryW - -See MSDN doc. ---*/ -BOOL -PALAPI -SetCurrentDirectoryW( - IN LPCWSTR lpPathName) -{ - BOOL bRet; - DWORD dwLastError = 0; - PathCharString dirPathString; - int size; - size_t length; - char * dir = NULL; - - PERF_ENTRY(SetCurrentDirectoryW); - ENTRY("SetCurrentDirectoryW(lpPathName=%p (%S))\n", - lpPathName?lpPathName:W16_NULLSTRING, - lpPathName?lpPathName:W16_NULLSTRING); - - /*check if the given path is null. If so - return FALSE*/ - if (lpPathName == NULL ) - { - ERROR("Invalid path/directory name\n"); - dwLastError = ERROR_INVALID_NAME; - bRet = FALSE; - goto done; - } - - length = (PAL_wcslen(lpPathName)+1) * 3; - dir = dirPathString.OpenStringBuffer(length); - if (NULL == dir) - { - dwLastError = ERROR_NOT_ENOUGH_MEMORY; - bRet = FALSE; - goto done; - } - - size = WideCharToMultiByte( CP_ACP, 0, lpPathName, -1, dir, length, - NULL, NULL ); - - if( size == 0 ) - { - dirPathString.CloseBuffer(0); - dwLastError = GetLastError(); - ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); - dwLastError = ERROR_INTERNAL_ERROR; - bRet = FALSE; - goto done; - } - - dirPathString.CloseBuffer(size - 1); - bRet = SetCurrentDirectoryA(dir); -done: - if( dwLastError ) - { - SetLastError(dwLastError); - } - - LOGEXIT("SetCurrentDirectoryW returns BOOL %d\n", bRet); - PERF_EXIT(SetCurrentDirectoryW); - return bRet; -} - -/*++ -Function: - CreateDirectoryA - -Note: - lpSecurityAttributes always NULL. - -See MSDN doc. ---*/ -BOOL -PALAPI -CreateDirectoryA( - IN LPCSTR lpPathName, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes) -{ - BOOL bRet = FALSE; - DWORD dwLastError = 0; - PathCharString realPath; - char* realPathBuf; - LPSTR unixPathName = NULL; - int pathLength; - int i; - const int mode = S_IRWXU | S_IRWXG | S_IRWXO; - - PERF_ENTRY(CreateDirectoryA); - ENTRY("CreateDirectoryA(lpPathName=%p (%s), lpSecurityAttr=%p)\n", - lpPathName?lpPathName:"NULL", - lpPathName?lpPathName:"NULL", lpSecurityAttributes); - - if ( lpSecurityAttributes ) - { - ASSERT("lpSecurityAttributes is not NULL as it should be\n"); - dwLastError = ERROR_INVALID_PARAMETER; - goto done; - } - - // Windows returns ERROR_PATH_NOT_FOUND when called with NULL. - // If we don't have this check, strdup(NULL) segfaults. - if (lpPathName == NULL) - { - ERROR("CreateDirectoryA called with NULL pathname!\n"); - dwLastError = ERROR_PATH_NOT_FOUND; - goto done; - } - - unixPathName = strdup(lpPathName); - if (unixPathName == NULL ) - { - ERROR("strdup() failed\n"); - dwLastError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - // Remove any trailing slashes at the end because mkdir might not - // handle them appropriately on all platforms. - pathLength = strlen(unixPathName); - i = pathLength; - while(i > 1) - { - if(unixPathName[i - 1] =='/') - { - unixPathName[i - 1]='\0'; - i--; - } - else - { - break; - } - } - - - // Get an absolute path. - if (unixPathName[0] == '/') - { - realPathBuf = unixPathName; - } - else - { - - DWORD len = GetCurrentDirectoryA(realPath); - if (len == 0 || !realPath.Reserve(realPath.GetCount() + pathLength + 1 )) - { - dwLastError = DIRGetLastErrorFromErrno(); - WARN("Getcwd failed with errno=%d \n", dwLastError); - goto done; - } - - realPath.Append("/", 1); - realPath.Append(unixPathName, pathLength); - realPathBuf = realPath.OpenStringBuffer(realPath.GetCount()); - } - - // Canonicalize the path so we can determine its length. - FILECanonicalizePath(realPathBuf); - - if ( mkdir(realPathBuf, mode) != 0 ) - { - TRACE("Creation of directory [%s] was unsuccessful, errno = %d.\n", - unixPathName, errno); - - switch( errno ) - { - case ENOTDIR: - /* FALL THROUGH */ - case ENOENT: - FILEGetProperNotFoundError( realPathBuf, &dwLastError ); - goto done; - case EEXIST: - dwLastError = ERROR_ALREADY_EXISTS; - break; - default: - dwLastError = ERROR_ACCESS_DENIED; - } - } - else - { - TRACE("Creation of directory [%s] was successful.\n", unixPathName); - bRet = TRUE; - } - - realPath.CloseBuffer(0); //The PathCharString usage is done -done: - if( dwLastError ) - { - SetLastError( dwLastError ); - } - free( unixPathName ); - LOGEXIT("CreateDirectoryA returns BOOL %d\n", bRet); - PERF_EXIT(CreateDirectoryA); - return bRet; -} - -/*++ -Function: - SetCurrentDirectoryA - -See MSDN doc. ---*/ -BOOL -PALAPI -SetCurrentDirectoryA( - IN LPCSTR lpPathName) -{ - BOOL bRet = FALSE; - DWORD dwLastError = 0; - int result; - - PERF_ENTRY(SetCurrentDirectoryA); - ENTRY("SetCurrentDirectoryA(lpPathName=%p (%s))\n", - lpPathName?lpPathName:"NULL", - lpPathName?lpPathName:"NULL"); - - /*check if the given path is null. If so - return FALSE*/ - if (lpPathName == NULL ) - { - ERROR("Invalid path/directory name\n"); - dwLastError = ERROR_INVALID_NAME; - goto done; - } - - TRACE("Attempting to open Unix dir [%s]\n", lpPathName); - result = chdir(lpPathName); - - if ( result == 0 ) - { - bRet = TRUE; - } - else - { - if ( errno == ENOTDIR || errno == ENOENT ) - { - struct stat stat_data; - - if ( stat( lpPathName, &stat_data) == 0 && - (stat_data.st_mode & S_IFMT) == S_IFREG ) - { - /* Not a directory, it is a file. */ - dwLastError = ERROR_DIRECTORY; - } - else - { - FILEGetProperNotFoundError( lpPathName, &dwLastError ); - } - TRACE("chdir() failed, path was invalid.\n"); - } - else - { - dwLastError = ERROR_ACCESS_DENIED; - ERROR("chdir() failed; errno is %d (%s)\n", errno, strerror(errno)); - } - } - - -done: - if( dwLastError ) - { - SetLastError(dwLastError); - } - - LOGEXIT("SetCurrentDirectoryA returns BOOL %d\n", bRet); - PERF_EXIT(SetCurrentDirectoryA); - return bRet; -} diff --git a/src/coreclr/pal/src/file/file.cpp b/src/coreclr/pal/src/file/file.cpp deleted file mode 100644 index f7e524d1152408..00000000000000 --- a/src/coreclr/pal/src/file/file.cpp +++ /dev/null @@ -1,2544 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ -Module Name: - file.cpp - -Abstract: - Implementation of the file WIN API for the PAL ---*/ - -#include "pal/dbgmsg.h" -SET_DEFAULT_DEBUG_CHANNEL(FILE); // some headers have code with asserts, so do this first - -#include "pal/thread.hpp" -#include "pal/file.hpp" -#include "pal/stackstring.hpp" - -#include "pal/palinternal.h" -#include "pal/file.h" -#include "pal/utils.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if HAVE_SYS_MOUNT_H -#include -#endif - -using namespace CorUnix; - -int MaxWCharToAcpLengthFactor = 3; - -PAL_ERROR -InternalSetFilePointerForUnixFd( - int iUnixFd, - LONG lDistanceToMove, - PLONG lpDistanceToMoveHigh, - DWORD dwMoveMethod, - PLONG lpNewFilePointerLow - ); - -void -CFileProcessLocalDataCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup - ); - -void -FileCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup, - bool fShutdown - ); - -CObjectType CorUnix::otFile( - otiFile, - FileCleanupRoutine, - 0, // No immutable data - NULL, // No immutable data copy routine - NULL, // No immutable data cleanup routine - sizeof(CFileProcessLocalData), - CFileProcessLocalDataCleanupRoutine - ); - -CAllowedObjectTypes CorUnix::aotFile(otiFile); - -void -CFileProcessLocalDataCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup - ) -{ - PAL_ERROR palError; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - - palError = pObjectToCleanup->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - ASSERT("Unable to obtain data to cleanup file object"); - return; - } - - free(pLocalData->unix_filename); - - pLocalDataLock->ReleaseLock(pThread, FALSE); -} - -void -FileCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup, - bool fShutdown - ) -{ - PAL_ERROR palError; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - - palError = pObjectToCleanup->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - ASSERT("Unable to obtain data to cleanup file object"); - return; - } - - if (!fShutdown && -1 != pLocalData->unix_fd) - { -#if defined(TARGET_WASI) - // WASI: init_std_handle borrows fileno(stream) for stdin/stdout/stderr - // because WASI has no dup(). Never close a borrowed std fd here. - if (pLocalData->unix_fd != STDIN_FILENO && - pLocalData->unix_fd != STDOUT_FILENO && - pLocalData->unix_fd != STDERR_FILENO) -#endif - close(pLocalData->unix_fd); - } - - pLocalDataLock->ReleaseLock(pThread, FALSE); -} - -typedef enum -{ - PIID_STDIN_HANDLE, - PIID_STDOUT_HANDLE, - PIID_STDERR_HANDLE -} PROCINFO_ID; - -#define PAL_LEGAL_FLAGS_ATTRIBS (FILE_ATTRIBUTE_NORMAL| \ - FILE_FLAG_SEQUENTIAL_SCAN| \ - FILE_FLAG_WRITE_THROUGH| \ - FILE_FLAG_RANDOM_ACCESS| \ - FILE_FLAG_BACKUP_SEMANTICS) - -/* Static global. The init function must be called -before any other functions and if it is not successful, -no other functions should be done. */ -static HANDLE pStdIn = INVALID_HANDLE_VALUE; -static HANDLE pStdOut = INVALID_HANDLE_VALUE; -static HANDLE pStdErr = INVALID_HANDLE_VALUE; - -/*++ -Function : - FILEGetProperNotFoundError - -Returns the proper error code, based on the -Windows behavior. - - IN LPSTR lpPath - The path to check. - LPDWORD lpErrorCode - The error to set. -*/ -void FILEGetProperNotFoundError( LPCSTR lpPath, LPDWORD lpErrorCode ) -{ - struct stat stat_data; - LPSTR lpDupedPath = NULL; - LPSTR lpLastPathSeparator = NULL; - - TRACE( "FILEGetProperNotFoundError( %s )\n", lpPath?lpPath:"(null)" ); - - if ( !lpErrorCode ) - { - ASSERT( "lpErrorCode has to be valid\n" ); - return; - } - - if ( NULL == ( lpDupedPath = strdup(lpPath) ) ) - { - ERROR( "strdup() failed!\n" ); - *lpErrorCode = ERROR_NOT_ENOUGH_MEMORY; - return; - } - - /* Determine whether it's a file not found or path not found. */ - lpLastPathSeparator = strrchr( lpDupedPath, '/'); - if ( lpLastPathSeparator != NULL ) - { - *lpLastPathSeparator = '\0'; - - /* If the last path component is a directory, - we return file not found. If it's a file or - doesn't exist, we return path not found. */ - if ( '\0' == *lpDupedPath || - ( stat( lpDupedPath, &stat_data ) == 0 && - ( stat_data.st_mode & S_IFMT ) == S_IFDIR ) ) - { - TRACE( "ERROR_FILE_NOT_FOUND\n" ); - *lpErrorCode = ERROR_FILE_NOT_FOUND; - } - else - { - TRACE( "ERROR_PATH_NOT_FOUND\n" ); - *lpErrorCode = ERROR_PATH_NOT_FOUND; - } - } - else - { - TRACE( "ERROR_FILE_NOT_FOUND\n" ); - *lpErrorCode = ERROR_FILE_NOT_FOUND; - } - - free(lpDupedPath); - lpDupedPath = NULL; - TRACE( "FILEGetProperNotFoundError returning TRUE\n" ); - return; -} - -/*++ -Function : - FILEGetLastErrorFromErrnoAndFilename - -Returns the proper error code for errno, or, if errno is ENOENT, -based on the Windows behavior for nonexistent filenames. - - IN LPSTR lpPath - The path to check. -*/ -PAL_ERROR FILEGetLastErrorFromErrnoAndFilename(LPCSTR lpPath) -{ - PAL_ERROR palError; - if (ENOENT == errno) - { - FILEGetProperNotFoundError(lpPath, &palError); - } - else - { - palError = FILEGetLastErrorFromErrno(); - } - return palError; -} - -BOOL -CorUnix::RealPathHelper(LPCSTR lpUnixPath, PathCharString& lpBuffer) -{ - StringHolder lpRealPath; - lpRealPath = realpath(lpUnixPath, NULL); - if (lpRealPath.IsNull()) - { - return FALSE; - } - - lpBuffer.Set(lpRealPath, strlen(lpRealPath)); - return TRUE; -} -/*++ -InternalCanonicalizeRealPath - Wraps realpath() to hide platform differences. See the man page for - realpath(3) for details of how realpath() works. - - On systems on which realpath() allows the last path component to not - exist, this is a straight thunk through to realpath(). On other - systems, we remove the last path component, then call realpath(). - ---*/ -PAL_ERROR -CorUnix::InternalCanonicalizeRealPath(LPCSTR lpUnixPath, PathCharString& lpBuffer) -{ - PAL_ERROR palError = NO_ERROR; - -#if !REALPATH_SUPPORTS_NONEXISTENT_FILES - StringHolder lpExistingPath; - LPSTR pchSeparator = NULL; - LPSTR lpFilename = NULL; -#endif // !REALPATH_SUPPORTS_NONEXISTENT_FILES - - if (lpUnixPath == NULL) - { - ERROR ("Invalid argument to InternalCanonicalizeRealPath\n"); - palError = ERROR_INVALID_PARAMETER; - goto LExit; - } - -#if REALPATH_SUPPORTS_NONEXISTENT_FILES - RealPathHelper(lpUnixPath, lpBuffer); -#else // !REALPATH_SUPPORTS_NONEXISTENT_FILES - - lpExistingPath = strdup(lpUnixPath); - if (lpExistingPath.IsNull()) - { - ERROR ("strdup failed with error %d\n", errno); - palError = ERROR_NOT_ENOUGH_MEMORY; - goto LExit; - } - - pchSeparator = strrchr(lpExistingPath, '/'); - if (pchSeparator == NULL) - { - PathCharString pszCwdBuffer; - - if (GetCurrentDirectoryA(pszCwdBuffer)== 0) - { - WARN("getcwd(NULL) failed with error %d\n", errno); - palError = DIRGetLastErrorFromErrno(); - goto LExit; - } - - if (!RealPathHelper(pszCwdBuffer, lpBuffer)) - { - WARN("realpath() failed with error %d\n", errno); - palError = FILEGetLastErrorFromErrno(); - goto LExit; - } - lpFilename = lpExistingPath; - } - else if (pchSeparator == lpExistingPath) - { - // This is a path in the root i.e. '/tmp' - // This scenario will probably only come up in WASM where it is normal to - // have a cwd of '/' and store files in the root of the virtual filesystem - lpBuffer.Clear(); - lpBuffer.Append(lpExistingPath, strlen(lpExistingPath)); - return NO_ERROR; - } - else - { - bool fSetFilename = true; - // Since realpath implementation cannot handle inexistent filenames, - // check if we are going to truncate the "/" corresponding to the - // root folder (e.g. case of "/Volumes"). If so: - // - // 1) Set the separator to point to the NULL terminator of the specified - // file/folder name. - // - // 2) Null terminate lpBuffer - // - // 3) Since there is no explicit filename component in lpExistingPath (as - // we only have "/" corresponding to the root), set lpFilename to NULL, - // alongwith a flag indicating that it has already been set. - if (pchSeparator == lpExistingPath) - { - pchSeparator = lpExistingPath+strlen(lpExistingPath); - - // Set the lpBuffer to NULL - lpBuffer.Clear(); - lpFilename = NULL; - fSetFilename = false; - } - else - { - *pchSeparator = '\0'; - } - - if (!RealPathHelper(lpExistingPath, lpBuffer)) - { - WARN("realpath() failed with error %d\n", errno); - palError = FILEGetLastErrorFromErrno(); - goto LExit; - } - - if (fSetFilename == true) - lpFilename = pchSeparator + 1; - } - - if (lpFilename == NULL) - goto LExit; - - if (!lpBuffer.Append("/",1) || !lpBuffer.Append(lpFilename, strlen(lpFilename))) - { - ERROR ("Append failed!\n"); - palError = ERROR_INSUFFICIENT_BUFFER; - - // Doing a goto here since we want to exit now. This will work - // incase someone else adds another if clause below us. - goto LExit; - } - -#endif // REALPATH_SUPPORTS_NONEXISTENT_FILES -LExit: - - if ((palError == NO_ERROR) && lpBuffer.IsEmpty()) - { - // convert all these into ERROR_PATH_NOT_FOUND - palError = ERROR_PATH_NOT_FOUND; - } - - return palError; -} - -PAL_ERROR -CorUnix::InternalCreateFile( - CPalThread *pThread, - LPCSTR lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - LPSECURITY_ATTRIBUTES lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - HANDLE hTemplateFile, - HANDLE *phFile - ) -{ - PAL_ERROR palError = 0; - IPalObject *pFileObject = NULL; - IPalObject *pRegisteredFile = NULL; - IDataLock *pDataLock = NULL; - CFileProcessLocalData *pLocalData = NULL; - CObjectAttributes oaFile(NULL, lpSecurityAttributes); - BOOL fFileExists = FALSE; - - BOOL inheritable = FALSE; - PathCharString lpUnixPath; - int filed = -1; - int create_flags = (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - int open_flags = 0; - int open_flags_for_syscall = 0; - - // track whether we've created the file with the intended name, - // so that it can be removed on failure exit - BOOL bFileCreated = FALSE; - - const char* szNonfilePrefix = "\\\\.\\"; - PathCharString lpFullUnixPath; - - /* for dwShareMode only three flags are accepted */ - if ( dwShareMode & ~(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) ) - { - ASSERT( "dwShareMode is invalid\n" ); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - if ( lpFileName == NULL ) - { - ERROR("InternalCreateFile called with NULL filename\n"); - palError = ERROR_PATH_NOT_FOUND; - goto done; - } - - if ( strncmp(lpFileName, szNonfilePrefix, strlen(szNonfilePrefix)) == 0 ) - { - ERROR("InternalCreateFile does not support paths beginning with %s\n", szNonfilePrefix); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - if( !lpUnixPath.Set(lpFileName,strlen(lpFileName))) - { - ERROR("strdup() failed\n"); - palError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - - // Compute the absolute pathname to the file. This pathname is used - // to determine if two file names represent the same file. - palError = InternalCanonicalizeRealPath(lpUnixPath, lpFullUnixPath); - if (palError != NO_ERROR) - { - goto done; - } - - lpUnixPath.Set(lpFullUnixPath); - - switch( dwDesiredAccess ) - { - case 0: - /* Device Query Access was requested. let's use open() with - no flags, it's basically the equivalent of O_RDONLY, since - O_RDONLY is defined as 0x0000 */ - break; - case( GENERIC_READ ): - open_flags |= O_RDONLY; - break; - case( GENERIC_WRITE ): - open_flags |= O_WRONLY; - break; - case( GENERIC_READ | GENERIC_WRITE ): - open_flags |= O_RDWR; - break; - default: - ERROR("dwDesiredAccess value of %d is invalid\n", dwDesiredAccess); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - TRACE("open flags are 0x%lx\n", open_flags); - - if ( lpSecurityAttributes ) - { - if ( lpSecurityAttributes->nLength != sizeof( SECURITY_ATTRIBUTES ) || - lpSecurityAttributes->lpSecurityDescriptor != NULL || - !lpSecurityAttributes->bInheritHandle ) - { - ASSERT("lpSecurityAttributes points to invalid values.\n"); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - inheritable = TRUE; - } - - if ( (dwFlagsAndAttributes & PAL_LEGAL_FLAGS_ATTRIBS) != - dwFlagsAndAttributes) - { - ASSERT("Bad dwFlagsAndAttributes\n"); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - else if (dwFlagsAndAttributes & FILE_FLAG_BACKUP_SEMANTICS) - { - /* Override the open flags, and always open as readonly. This - flag is used when opening a directory, to change its - creation/modification/access times. On Windows, the directory - must be open for write, but on Unix, it needs to be readonly. */ - open_flags = O_RDONLY; - } else { - struct stat st; - - if (stat(lpUnixPath, &st) == 0 && (st.st_mode & S_IFDIR)) - { - /* The file exists and it is a directory. Without - FILE_FLAG_BACKUP_SEMANTICS, Win32 CreateFile always fails - to open directories. */ - palError = ERROR_ACCESS_DENIED; - goto done; - } - } - - if ( hTemplateFile ) - { - ASSERT("hTemplateFile is not NULL, as it should be.\n"); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - /* NB: According to MSDN docs, When CREATE_ALWAYS or OPEN_ALWAYS is - set, CreateFile should SetLastError to ERROR_ALREADY_EXISTS, - even though/if CreateFile will be successful. - */ - switch( dwCreationDisposition ) - { - case( CREATE_ALWAYS ): - // check whether the file exists - if ( access( lpUnixPath, F_OK ) == 0 ) - { - fFileExists = TRUE; - } - open_flags |= O_CREAT | O_TRUNC; - break; - case( CREATE_NEW ): - open_flags |= O_CREAT | O_EXCL; - break; - case( OPEN_EXISTING ): - /* don't need to do anything here */ - break; - case( OPEN_ALWAYS ): - if ( access( lpUnixPath, F_OK ) == 0 ) - { - fFileExists = TRUE; - } - open_flags |= O_CREAT; - break; - case( TRUNCATE_EXISTING ): - open_flags |= O_TRUNC; - break; - default: - ASSERT("dwCreationDisposition value of %d is not valid\n", - dwCreationDisposition); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - - open_flags_for_syscall = open_flags; -#if defined(__OpenBSD__) - /* On OpenBSD, open() requires O_RDWR or O_WRONLY to be specified along with - O_TRUNC, otherwise it fails with EINVAL. Windows allows truncating a file - that is opened for read-only access (e.g. GENERIC_READ with CREATE_ALWAYS). - Upgrade only the flags passed to open() so the truncation succeeds, while - leaving open_flags (used later for access checks such as file mappings) - unchanged to preserve the caller's requested access. */ - if ((open_flags_for_syscall & O_TRUNC) && (open_flags_for_syscall & O_ACCMODE) == O_RDONLY) - { - open_flags_for_syscall = (open_flags_for_syscall & ~O_ACCMODE) | O_RDWR; - } -#endif // __OpenBSD__ - - filed = InternalOpen(lpUnixPath, open_flags_for_syscall, create_flags); - TRACE("Allocated file descriptor [%d]\n", filed); - - if ( filed < 0 ) - { - TRACE("open() failed; error is %s (%d)\n", strerror(errno), errno); - palError = FILEGetLastErrorFromErrnoAndFilename(lpUnixPath); - goto done; - } - - // Deduce whether we created a file in the previous operation (there's a - // small timing window between the access() used to determine fFileExists - // and the open() operation, but there's not much we can do about that. - bFileCreated = (dwCreationDisposition == CREATE_ALWAYS || - dwCreationDisposition == CREATE_NEW || - dwCreationDisposition == OPEN_ALWAYS) && - !fFileExists; - - /* make file descriptor close-on-exec; inheritable handles will get - "uncloseonexeced" in CreateProcess if they are actually being inherited*/ - if(-1 == fcntl(filed,F_SETFD, FD_CLOEXEC)) - { - ASSERT("can't set close-on-exec flag; fcntl() failed. errno is %d " - "(%s)\n", errno, strerror(errno)); - palError = ERROR_INTERNAL_ERROR; - goto done; - } - - palError = g_pObjectManager->AllocateObject( - pThread, - &otFile, - &oaFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto done; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - WriteLock, - &pDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto done; - } - - _ASSERTE(pLocalData->unix_filename == NULL); - pLocalData->unix_filename = strdup(lpUnixPath); - if (pLocalData->unix_filename == NULL) - { - ASSERT("Unable to copy string\n"); - palError = ERROR_INTERNAL_ERROR; - goto done; - } - - pLocalData->inheritable = inheritable; - pLocalData->unix_fd = filed; - pLocalData->open_flags = open_flags; - pLocalData->open_flags_deviceaccessonly = (dwDesiredAccess == 0); - - // - // We've finished initializing our local data, so release that lock - // - - pDataLock->ReleaseLock(pThread, TRUE); - pDataLock = NULL; - - palError = g_pObjectManager->RegisterObject( - pThread, - pFileObject, - &aotFile, - phFile, - &pRegisteredFile - ); - - // - // pFileObject is invalidated by the call to RegisterObject, so NULL it - // out here to ensure that we don't try to release a reference on - // it down the line. - // - - pFileObject = NULL; - -done: - - // At this point, if we've been successful, palError will be NO_ERROR. - // CreateFile can return ERROR_ALREADY_EXISTS in some success cases; - // those cases are flagged by fFileExists and are handled below. - if (NO_ERROR != palError) - { - if (filed >= 0) - { - close(filed); - } - if (bFileCreated) - { - if (-1 == unlink(lpUnixPath)) - { - WARN("can't delete file; unlink() failed with errno %d (%s)\n", - errno, strerror(errno)); - } - } - } - - if (NULL != pDataLock) - { - pDataLock->ReleaseLock(pThread, TRUE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - if (NULL != pRegisteredFile) - { - pRegisteredFile->ReleaseReference(pThread); - } - - if (NO_ERROR == palError && fFileExists) - { - palError = ERROR_ALREADY_EXISTS; - } - - return palError; -} - -/*++ -Function: - CreateFileA - -Note: - Only bInherit flag is used from the LPSECURITY_ATTRIBUTES struct. - Desired access is READ, WRITE or 0 - Share mode is READ, WRITE or DELETE - -See MSDN doc. ---*/ -HANDLE -PALAPI -CreateFileA( - IN LPCSTR lpFileName, - IN DWORD dwDesiredAccess, - IN DWORD dwShareMode, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes, - IN DWORD dwCreationDisposition, - IN DWORD dwFlagsAndAttributes, - IN HANDLE hTemplateFile - ) -{ - CPalThread *pThread; - PAL_ERROR palError = NO_ERROR; - HANDLE hRet = INVALID_HANDLE_VALUE; - - PERF_ENTRY(CreateFileA); - ENTRY("CreateFileA(lpFileName=%p (%s), dwAccess=%#x, dwShareMode=%#x, " - "lpSecurityAttr=%p, dwDisposition=%#x, dwFlags=%#x, " - "hTemplateFile=%p )\n",lpFileName?lpFileName:"NULL",lpFileName?lpFileName:"NULL", dwDesiredAccess, - dwShareMode, lpSecurityAttributes, dwCreationDisposition, - dwFlagsAndAttributes, hTemplateFile); - - pThread = InternalGetCurrentThread(); - - palError = InternalCreateFile( - pThread, - lpFileName, - dwDesiredAccess, - dwShareMode, - lpSecurityAttributes, - dwCreationDisposition, - dwFlagsAndAttributes, - hTemplateFile, - &hRet - ); - - // - // We always need to set last error, even on success: - // we need to protect ourselves from the situation - // where last error is set to ERROR_ALREADY_EXISTS on - // entry to the function - // - - pThread->SetLastError(palError); - - LOGEXIT("CreateFileA returns HANDLE %p\n", hRet); - PERF_EXIT(CreateFileA); - return hRet; -} - - -/*++ -Function: - CreateFileW - -Note: - Only bInherit flag is used from the LPSECURITY_ATTRIBUTES struct. - Desired access is READ, WRITE or 0 - Share mode is READ, WRITE or DELETE - -See MSDN doc. ---*/ -HANDLE -PALAPI -CreateFileW( - IN LPCWSTR lpFileName, - IN DWORD dwDesiredAccess, - IN DWORD dwShareMode, - IN LPSECURITY_ATTRIBUTES lpSecurityAttributes, - IN DWORD dwCreationDisposition, - IN DWORD dwFlagsAndAttributes, - IN HANDLE hTemplateFile) -{ - CPalThread *pThread; - PAL_ERROR palError = NO_ERROR; - PathCharString namePathString; - char * name; - int size; - int length = 0; - HANDLE hRet = INVALID_HANDLE_VALUE; - - PERF_ENTRY(CreateFileW); - ENTRY("CreateFileW(lpFileName=%p (%S), dwAccess=%#x, dwShareMode=%#x, " - "lpSecurityAttr=%p, dwDisposition=%#x, dwFlags=%#x, hTemplateFile=%p )\n", - lpFileName?lpFileName:W16_NULLSTRING, - lpFileName?lpFileName:W16_NULLSTRING, dwDesiredAccess, dwShareMode, - lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, - hTemplateFile); - - pThread = InternalGetCurrentThread(); - - if (lpFileName != NULL) - { - length = (PAL_wcslen(lpFileName)+1) * MaxWCharToAcpLengthFactor; - } - - name = namePathString.OpenStringBuffer(length); - if (NULL == name) - { - palError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - - size = WideCharToMultiByte( CP_ACP, 0, lpFileName, -1, name, length, - NULL, NULL ); - - if( size == 0 ) - { - namePathString.CloseBuffer(0); - DWORD dwLastError = GetLastError(); - ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); - palError = ERROR_INTERNAL_ERROR; - goto done; - } - - namePathString.CloseBuffer(size - 1); - - palError = InternalCreateFile( - pThread, - name, - dwDesiredAccess, - dwShareMode, - lpSecurityAttributes, - dwCreationDisposition, - dwFlagsAndAttributes, - hTemplateFile, - &hRet - ); - - // - // We always need to set last error, even on success: - // we need to protect ourselves from the situation - // where last error is set to ERROR_ALREADY_EXISTS on - // entry to the function - // - -done: - pThread->SetLastError(palError); - LOGEXIT( "CreateFileW returns HANDLE %p\n", hRet ); - PERF_EXIT(CreateFileW); - return hRet; -} - - -/*++ -Function: - DeleteFileA - -See MSDN doc. ---*/ -BOOL -PALAPI -DeleteFileA( - IN LPCSTR lpFileName) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - int result; - BOOL bRet = FALSE; - DWORD dwLastError = 0; - PathCharString lpunixFileName; - PathCharString lpFullunixFileName; - - PERF_ENTRY(DeleteFileA); - ENTRY("DeleteFileA(lpFileName=%p (%s))\n", lpFileName?lpFileName:"NULL", lpFileName?lpFileName:"NULL"); - - pThread = InternalGetCurrentThread(); - - if( !lpunixFileName.Set(lpFileName, strlen(lpFileName))) - { - palError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - - // Compute the absolute pathname to the file. This pathname is used - // to determine if two file names represent the same file. - palError = InternalCanonicalizeRealPath(lpunixFileName, lpFullunixFileName); - if (palError != NO_ERROR) - { - if (!lpFullunixFileName.Set(lpunixFileName, strlen(lpunixFileName))) - { - palError = ERROR_NOT_ENOUGH_MEMORY; - goto done; - } - } - - result = unlink( lpFullunixFileName ); - - if (result < 0) - { - TRACE("unlink returns %d\n", result); - dwLastError = FILEGetLastErrorFromErrnoAndFilename(lpFullunixFileName); - } - else - { - bRet = TRUE; - } - -done: - if(dwLastError) - { - pThread->SetLastError( dwLastError ); - } - - LOGEXIT("DeleteFileA returns BOOL %d\n", bRet); - PERF_EXIT(DeleteFileA); - return bRet; -} - -/*++ -InternalOpen - -Wrapper for open. - -Input parameters: - -szPath = pointer to a pathname of a file to be opened -nFlags = arguments that control how the file should be accessed -mode = file permission settings that are used only when a file is created - -Return value: - File descriptor on success, -1 on failure ---*/ -int -CorUnix::InternalOpen( - const char *szPath, - int nFlags, - ... - ) -{ - int nRet = -1; - int mode = 0; - va_list ap; - - // If nFlags does not contain O_CREAT, the mode parameter will be ignored. - if (nFlags & O_CREAT) - { - va_start(ap, nFlags); - mode = va_arg(ap, int); - va_end(ap); - } - - do - { -#if OPEN64_IS_USED_INSTEAD_OF_OPEN - nRet = open64(szPath, nFlags, mode); -#else - nRet = open(szPath, nFlags, mode); -#endif - } - while ((nRet == -1) && (errno == EINTR)); - - return nRet; -} - -PAL_ERROR -CorUnix::InternalWriteFile( - CPalThread *pThread, - HANDLE hFile, - LPCVOID lpBuffer, - DWORD nNumberOfBytesToWrite, - LPDWORD lpNumberOfBytesWritten, - LPOVERLAPPED lpOverlapped - ) -{ - PAL_ERROR palError = 0; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - int ifd; - int res; - - if (NULL != lpNumberOfBytesWritten) - { - // - // This must be set to 0 before any other error checking takes - // place, per MSDN - // - - *lpNumberOfBytesWritten = 0; - } - else - { - ASSERT( "lpNumberOfBytesWritten is NULL\n" ); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - // Win32 WriteFile disallows writing to STD_INPUT_HANDLE - if (hFile == INVALID_HANDLE_VALUE || hFile == pStdIn) - { - palError = ERROR_INVALID_HANDLE; - goto done; - } - else if ( lpOverlapped ) - { - ASSERT( "lpOverlapped is not NULL, as it should be.\n" ); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto done; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto done; - } - - if (pLocalData->open_flags_deviceaccessonly == TRUE) - { - ERROR("File open for device access only\n"); - palError = ERROR_ACCESS_DENIED; - goto done; - } - - ifd = pLocalData->unix_fd; - - // - // Release the data lock before performing the (possibly blocking) - // write call - // - - pLocalDataLock->ReleaseLock(pThread, FALSE); - pLocalDataLock = NULL; - pLocalData = NULL; - -#if WRITE_0_BYTES_HANGS_TTY - if( nNumberOfBytesToWrite == 0 && isatty(ifd) ) - { - res = 0; - *lpNumberOfBytesWritten = 0; - goto done; - } -#endif - - res = write( ifd, lpBuffer, nNumberOfBytesToWrite ); - TRACE("write() returns %d\n", res); - - if ( res >= 0 ) - { - *lpNumberOfBytesWritten = res; - } - else - { - palError = FILEGetLastErrorFromErrno(); - } - -done: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - - -/*++ -Function: - WriteFileW - -Note: - lpOverlapped always NULL. - -See MSDN doc. ---*/ -BOOL -PALAPI -WriteFile( - IN HANDLE hFile, - IN LPCVOID lpBuffer, - IN DWORD nNumberOfBytesToWrite, - OUT LPDWORD lpNumberOfBytesWritten, - IN LPOVERLAPPED lpOverlapped) -{ - PAL_ERROR palError; - CPalThread *pThread; - - PERF_ENTRY(WriteFile); - ENTRY("WriteFile(hFile=%p, lpBuffer=%p, nToWrite=%u, lpWritten=%p, " - "lpOverlapped=%p)\n", hFile, lpBuffer, nNumberOfBytesToWrite, - lpNumberOfBytesWritten, lpOverlapped); - - pThread = InternalGetCurrentThread(); - - palError = InternalWriteFile( - pThread, - hFile, - lpBuffer, - nNumberOfBytesToWrite, - lpNumberOfBytesWritten, - lpOverlapped - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT("WriteFile returns BOOL %d\n", NO_ERROR == palError); - PERF_EXIT(WriteFile); - return NO_ERROR == palError; -} - -PAL_ERROR -CorUnix::InternalReadFile( - CPalThread *pThread, - HANDLE hFile, - LPVOID lpBuffer, - DWORD nNumberOfBytesToRead, - LPDWORD lpNumberOfBytesRead, - LPOVERLAPPED lpOverlapped - ) -{ - PAL_ERROR palError = 0; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - int ifd; - int res; - - if (NULL != lpNumberOfBytesRead) - { - // - // This must be set to 0 before any other error checking takes - // place, per MSDN - // - - *lpNumberOfBytesRead = 0; - } - else - { - ERROR( "lpNumberOfBytesRead is NULL\n" ); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - if (INVALID_HANDLE_VALUE == hFile) - { - ERROR( "Invalid file handle\n" ); - palError = ERROR_INVALID_HANDLE; - goto done; - } - else if (NULL != lpOverlapped) - { - ASSERT( "lpOverlapped is not NULL, as it should be.\n" ); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - else if (NULL == lpBuffer) - { - ERROR( "Invalid parameter. (lpBuffer:%p)\n", lpBuffer); - palError = ERROR_NOACCESS; - goto done; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto done; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto done; - } - - if (pLocalData->open_flags_deviceaccessonly == TRUE) - { - ERROR("File open for device access only\n"); - palError = ERROR_ACCESS_DENIED; - goto done; - } - - ifd = pLocalData->unix_fd; - - // - // Release the data lock before performing the (possibly blocking) - // read call - // - - pLocalDataLock->ReleaseLock(pThread, FALSE); - pLocalDataLock = NULL; - pLocalData = NULL; - -Read: - TRACE("Reading from file descriptor %d\n", ifd); - res = read(ifd, lpBuffer, nNumberOfBytesToRead); - TRACE("read() returns %d\n", res); - - if (res >= 0) - { - *lpNumberOfBytesRead = res; - } - else if (errno == EINTR) - { - // Try to read again. - goto Read; - } - else - { - palError = FILEGetLastErrorFromErrno(); - } - -done: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - -/*++ -Function: - ReadFile - -Note: - lpOverlapped always NULL. - -See MSDN doc. ---*/ -BOOL -PALAPI -ReadFile( - IN HANDLE hFile, - OUT LPVOID lpBuffer, - IN DWORD nNumberOfBytesToRead, - OUT LPDWORD lpNumberOfBytesRead, - IN LPOVERLAPPED lpOverlapped) -{ - PAL_ERROR palError; - CPalThread *pThread; - - PERF_ENTRY(ReadFile); - ENTRY("ReadFile(hFile=%p, lpBuffer=%p, nToRead=%u, " - "lpRead=%p, lpOverlapped=%p)\n", - hFile, lpBuffer, nNumberOfBytesToRead, - lpNumberOfBytesRead, lpOverlapped); - - pThread = InternalGetCurrentThread(); - - palError = InternalReadFile( - pThread, - hFile, - lpBuffer, - nNumberOfBytesToRead, - lpNumberOfBytesRead, - lpOverlapped - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT("ReadFile returns BOOL %d\n", NO_ERROR == palError); - PERF_EXIT(ReadFile); - return NO_ERROR == palError; -} - - -/*++ -Function: - GetStdHandle - -See MSDN doc. ---*/ -HANDLE -PALAPI -GetStdHandle( - IN DWORD nStdHandle) -{ - CPalThread *pThread; - HANDLE hRet = INVALID_HANDLE_VALUE; - - PERF_ENTRY(GetStdHandle); - ENTRY("GetStdHandle(nStdHandle=%#x)\n", nStdHandle); - - pThread = InternalGetCurrentThread(); - switch( nStdHandle ) - { - case STD_INPUT_HANDLE: - hRet = pStdIn; - break; - case STD_OUTPUT_HANDLE: - hRet = pStdOut; - break; - case STD_ERROR_HANDLE: - hRet = pStdErr; - break; - default: - ERROR("nStdHandle is invalid\n"); - pThread->SetLastError(ERROR_INVALID_PARAMETER); - break; - } - - LOGEXIT("GetStdHandle returns HANDLE %p\n", hRet); - PERF_EXIT(GetStdHandle); - return hRet; -} - -// -// We need to break out the actual mechanics of setting the file pointer -// on the unix FD for InternalReadFile and InternalWriteFile, as they -// need to call this routine in order to determine the value of the -// current file pointer when computing the scope of their transaction -// lock. If we didn't break out this logic we'd end up referencing the file -// handle multiple times, and, in the process, would attempt to recursively -// obtain the local process data lock for the underlying file object. -// - -PAL_ERROR -InternalSetFilePointerForUnixFd( - int iUnixFd, - LONG lDistanceToMove, - PLONG lpDistanceToMoveHigh, - DWORD dwMoveMethod, - PLONG lpNewFilePointerLow - ) -{ - PAL_ERROR palError = NO_ERROR; - int seek_whence = 0; - int64_t seek_offset = 0LL; - int64_t seek_res = 0LL; - off_t old_offset; - - switch( dwMoveMethod ) - { - case FILE_BEGIN: - seek_whence = SEEK_SET; - break; - case FILE_CURRENT: - seek_whence = SEEK_CUR; - break; - case FILE_END: - seek_whence = SEEK_END; - break; - default: - ERROR("dwMoveMethod = %d is invalid\n", dwMoveMethod); - palError = ERROR_INVALID_PARAMETER; - goto done; - } - - // - // According to MSDN, if lpDistanceToMoveHigh is not null, - // lDistanceToMove is treated as unsigned; - // it is treated as signed otherwise - // - - if ( lpDistanceToMoveHigh ) - { - /* set the high 32 bits of the offset */ - seek_offset = ((int64_t)*lpDistanceToMoveHigh << 32); - - /* set the low 32 bits */ - /* cast to unsigned long to avoid sign extension */ - seek_offset |= (ULONG) lDistanceToMove; - } - else - { - seek_offset |= lDistanceToMove; - } - - /* store the current position, in case the lseek moves the pointer - before the beginning of the file */ - old_offset = lseek(iUnixFd, 0, SEEK_CUR); - if (old_offset == -1) - { - ERROR("lseek(fd,0,SEEK_CUR) failed errno:%d (%s)\n", - errno, strerror(errno)); - palError = ERROR_ACCESS_DENIED; - goto done; - } - - // Check to see if we're going to seek to a negative offset. - // If we're seeking from the beginning or the current mark, - // this is simple. - if ((seek_whence == SEEK_SET && seek_offset < 0) || - (seek_whence == SEEK_CUR && seek_offset + old_offset < 0)) - { - palError = ERROR_NEGATIVE_SEEK; - goto done; - } - else if (seek_whence == SEEK_END && seek_offset < 0) - { - // We need to determine if we're seeking past the - // beginning of the file, but we don't want to adjust - // the mark in the process. stat is the only way to - // do that. - struct stat fileData; - int result; - - result = fstat(iUnixFd, &fileData); - if (result == -1) - { - // It's a bad fd. This shouldn't happen because - // we've already called lseek on it, but you - // never know. This is the best we can do. - palError = ERROR_ACCESS_DENIED; - goto done; - } - if (fileData.st_size < -seek_offset) - { - // Seeking past the beginning. - palError = ERROR_NEGATIVE_SEEK; - goto done; - } - } - - seek_res = (int64_t)lseek( iUnixFd, - seek_offset, - seek_whence ); - if ( seek_res < 0 ) - { - /* lseek() returns -1 on error, but also can seek to negative - file offsets, so -1 can also indicate a successful seek to offset - -1. Win32 doesn't allow negative file offsets, so either case - is an error. */ - ERROR("lseek failed errno:%d (%s)\n", errno, strerror(errno)); - lseek(iUnixFd, old_offset, SEEK_SET); - palError = ERROR_ACCESS_DENIED; - } - else - { - /* store high-order DWORD */ - if ( lpDistanceToMoveHigh ) - *lpDistanceToMoveHigh = (DWORD)(seek_res >> 32); - - /* return low-order DWORD of seek result */ - *lpNewFilePointerLow = (DWORD)seek_res; - } - -done: - - return palError; -} - -PAL_ERROR -CorUnix::InternalSetFilePointer( - CPalThread *pThread, - HANDLE hFile, - LONG lDistanceToMove, - PLONG lpDistanceToMoveHigh, - DWORD dwMoveMethod, - PLONG lpNewFilePointerLow - ) -{ - PAL_ERROR palError = NO_ERROR; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - - if (INVALID_HANDLE_VALUE == hFile) - { - ERROR( "Invalid file handle\n" ); - palError = ERROR_INVALID_HANDLE; - goto InternalSetFilePointerExit; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto InternalSetFilePointerExit; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto InternalSetFilePointerExit; - } - - palError = InternalSetFilePointerForUnixFd( - pLocalData->unix_fd, - lDistanceToMove, - lpDistanceToMoveHigh, - dwMoveMethod, - lpNewFilePointerLow - ); - -InternalSetFilePointerExit: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - -/*++ -Function: - SetFilePointer - -See MSDN doc. ---*/ -DWORD -PALAPI -SetFilePointer( - IN HANDLE hFile, - IN LONG lDistanceToMove, - IN PLONG lpDistanceToMoveHigh, - IN DWORD dwMoveMethod) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - LONG lNewFilePointerLow = 0; - - PERF_ENTRY(SetFilePointer); - ENTRY("SetFilePointer(hFile=%p, lDistance=%d, lpDistanceHigh=%p, " - "dwMoveMethod=%#x)\n", hFile, lDistanceToMove, - lpDistanceToMoveHigh, dwMoveMethod); - - pThread = InternalGetCurrentThread(); - - palError = InternalSetFilePointer( - pThread, - hFile, - lDistanceToMove, - lpDistanceToMoveHigh, - dwMoveMethod, - &lNewFilePointerLow - ); - - if (NO_ERROR != palError) - { - lNewFilePointerLow = INVALID_SET_FILE_POINTER; - } - - /* This function must always call SetLastError - even if successful. - If we seek to a value greater than 2^32 - 1, we will effectively be - returning a negative value from this function. Now, let's say that - returned value is -1. Furthermore, assume that win32error has been - set before even entering this function. Then, when this function - returns to SetFilePointer in win32native.cs, it will have returned - -1 and win32error will have been set, which will cause an error to be - returned. Since -1 may not be an error in this case and since we - can't assume that the win32error is related to SetFilePointer, - we need to always call SetLastError here. That way, if this function - succeeds, SetFilePointer in win32native won't mistakenly determine - that it failed. */ - pThread->SetLastError(palError); - - LOGEXIT("SetFilePointer returns DWORD %#x\n", lNewFilePointerLow); - PERF_EXIT(SetFilePointer); - return lNewFilePointerLow; -} - -/*++ -Function: - SetFilePointerEx - -See MSDN doc. ---*/ -BOOL -PALAPI -SetFilePointerEx( - IN HANDLE hFile, - IN LARGE_INTEGER liDistanceToMove, - OUT PLARGE_INTEGER lpNewFilePointer, - IN DWORD dwMoveMethod) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - BOOL Ret = FALSE; - - PERF_ENTRY(SetFilePointerEx); - ENTRY("SetFilePointerEx(hFile=%p, liDistanceToMove=0x%llx, " - "lpNewFilePointer=%p (0x%llx), dwMoveMethod=0x%x)\n", hFile, - liDistanceToMove.QuadPart, lpNewFilePointer, - (lpNewFilePointer) ? (*lpNewFilePointer).QuadPart : 0, dwMoveMethod); - - LONG lDistanceToMove; - lDistanceToMove = (LONG)liDistanceToMove.u.LowPart; - LONG lDistanceToMoveHigh; - lDistanceToMoveHigh = liDistanceToMove.u.HighPart; - - LONG lNewFilePointerLow = 0; - - pThread = InternalGetCurrentThread(); - - palError = InternalSetFilePointer( - pThread, - hFile, - lDistanceToMove, - &lDistanceToMoveHigh, - dwMoveMethod, - &lNewFilePointerLow - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - else - { - if (lpNewFilePointer != NULL) - { - lpNewFilePointer->u.LowPart = (DWORD)lNewFilePointerLow; - lpNewFilePointer->u.HighPart = (DWORD)lDistanceToMoveHigh; - } - Ret = TRUE; - } - - LOGEXIT("SetFilePointerEx returns BOOL %d\n", Ret); - PERF_EXIT(SetFilePointerEx); - return Ret; -} - -PAL_ERROR -CorUnix::InternalGetFileSize( - CPalThread *pThread, - HANDLE hFile, - DWORD *pdwFileSizeLow, - DWORD *pdwFileSizeHigh - ) -{ - PAL_ERROR palError = NO_ERROR; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - - struct stat stat_data; - - if (INVALID_HANDLE_VALUE == hFile) - { - ERROR( "Invalid file handle\n" ); - palError = ERROR_INVALID_HANDLE; - goto InternalGetFileSizeExit; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto InternalGetFileSizeExit; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto InternalGetFileSizeExit; - } - - if (fstat(pLocalData->unix_fd, &stat_data) != 0) - { - ERROR("fstat failed of file descriptor %d\n", pLocalData->unix_fd); - palError = FILEGetLastErrorFromErrno(); - goto InternalGetFileSizeExit; - } - - *pdwFileSizeLow = (DWORD)stat_data.st_size; - - if (NULL != pdwFileSizeHigh) - { -#if SIZEOF_OFF_T > 4 - *pdwFileSizeHigh = (DWORD)(stat_data.st_size >> 32); -#else - *pdwFileSizeHigh = 0; -#endif - } - -InternalGetFileSizeExit: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - -/*++ -Function: - GetFileSize - -See MSDN doc. ---*/ -DWORD -PALAPI -GetFileSize( - IN HANDLE hFile, - OUT LPDWORD lpFileSizeHigh) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - DWORD dwFileSizeLow; - - PERF_ENTRY(GetFileSize); - ENTRY("GetFileSize(hFile=%p, lpFileSizeHigh=%p)\n", hFile, lpFileSizeHigh); - - pThread = InternalGetCurrentThread(); - - palError = InternalGetFileSize( - pThread, - hFile, - &dwFileSizeLow, - lpFileSizeHigh - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - dwFileSizeLow = INVALID_FILE_SIZE; - } - - LOGEXIT("GetFileSize returns DWORD %u\n", dwFileSizeLow); - PERF_EXIT(GetFileSize); - return dwFileSizeLow; -} - -/*++ -Function: -GetFileSizeEx - -See MSDN doc. ---*/ -BOOL -PALAPI GetFileSizeEx( -IN HANDLE hFile, -OUT PLARGE_INTEGER lpFileSize) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - DWORD dwFileSizeHigh; - DWORD dwFileSizeLow; - - PERF_ENTRY(GetFileSizeEx); - ENTRY("GetFileSizeEx(hFile=%p, lpFileSize=%p)\n", hFile, lpFileSize); - - pThread = InternalGetCurrentThread(); - - if (lpFileSize != NULL) - { - palError = InternalGetFileSize( - pThread, - hFile, - &dwFileSizeLow, - &dwFileSizeHigh - ); - - if (NO_ERROR == palError) - { - lpFileSize->u.LowPart = dwFileSizeLow; - lpFileSize->u.HighPart = dwFileSizeHigh; - } - } - else - { - palError = ERROR_INVALID_PARAMETER; - } - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT("GetFileSizeEx returns BOOL %d\n", NO_ERROR == palError); - PERF_EXIT(GetFileSizeEx); - return NO_ERROR == palError; -} - -PAL_ERROR -CorUnix::InternalFlushFileBuffers( - CPalThread *pThread, - HANDLE hFile - ) -{ - PAL_ERROR palError = NO_ERROR; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - - if (INVALID_HANDLE_VALUE == hFile) - { - ERROR( "Invalid file handle\n" ); - palError = ERROR_INVALID_HANDLE; - goto InternalFlushFileBuffersExit; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto InternalFlushFileBuffersExit; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto InternalFlushFileBuffersExit; - } - - if (pLocalData->open_flags_deviceaccessonly == TRUE) - { - ERROR("File open for device access only\n"); - palError = ERROR_ACCESS_DENIED; - goto InternalFlushFileBuffersExit; - } - -#if HAVE_FSYNC || defined(__APPLE__) - do - { - -#if defined(__APPLE__) - if (fcntl(pLocalData->unix_fd, F_FULLFSYNC) != -1) - break; -#else // __APPLE__ - if (fsync(pLocalData->unix_fd) == 0) - break; -#endif // __APPLE__ - - switch (errno) - { - case EINTR: - // Execution was interrupted by a signal, so restart. - TRACE("fsync(%d) was interrupted. Restarting\n", pLocalData->unix_fd); - break; - - default: - palError = FILEGetLastErrorFromErrno(); - WARN("fsync(%d) failed with error %d\n", pLocalData->unix_fd, errno); - break; - } - } while (NO_ERROR == palError); -#else // HAVE_FSYNC - /* flush all buffers out to disk - there is no way to flush - an individual file descriptor's buffers out. */ - sync(); -#endif // HAVE_FSYNC else - - -InternalFlushFileBuffersExit: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - - -/*++ -Function: - FlushFileBuffers - -See MSDN doc. ---*/ -BOOL -PALAPI -FlushFileBuffers( - IN HANDLE hFile) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread; - - PERF_ENTRY(FlushFileBuffers); - ENTRY("FlushFileBuffers(hFile=%p)\n", hFile); - - pThread = InternalGetCurrentThread(); - - palError = InternalFlushFileBuffers( - pThread, - hFile - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT("FlushFileBuffers returns BOOL %d\n", NO_ERROR == palError); - PERF_EXIT(FlushFileBuffers); - return NO_ERROR == palError; -} - -/*++ -Function: - FILEGetLastErrorFromErrno - -Convert errno into the appropriate win32 error and return it. ---*/ -DWORD FILEGetLastErrorFromErrno( void ) -{ - DWORD dwRet; - - switch(errno) - { - case 0: - dwRet = ERROR_SUCCESS; - break; - case ENAMETOOLONG: - dwRet = ERROR_FILENAME_EXCED_RANGE; - break; - case ENOTDIR: - dwRet = ERROR_PATH_NOT_FOUND; - break; - case ENOENT: - dwRet = ERROR_FILE_NOT_FOUND; - break; - case EACCES: - case EPERM: - case EROFS: - case EISDIR: - dwRet = ERROR_ACCESS_DENIED; - break; - case EEXIST: - dwRet = ERROR_ALREADY_EXISTS; - break; - case ENOTEMPTY: - dwRet = ERROR_DIR_NOT_EMPTY; - break; - case EBADF: - dwRet = ERROR_INVALID_HANDLE; - break; - case ENOMEM: - dwRet = ERROR_NOT_ENOUGH_MEMORY; - break; - case EBUSY: - dwRet = ERROR_BUSY; - break; - case ENOSPC: - case EDQUOT: - dwRet = ERROR_DISK_FULL; - break; - case ELOOP: - dwRet = ERROR_BAD_PATHNAME; - break; - case EIO: - dwRet = ERROR_WRITE_FAULT; - break; - case EMFILE: - dwRet = ERROR_TOO_MANY_OPEN_FILES; - break; - case ERANGE: - dwRet = ERROR_BAD_PATHNAME; - break; - default: - ERROR("unexpected errno %d (%s); returning ERROR_GEN_FAILURE\n", - errno, strerror(errno)); - dwRet = ERROR_GEN_FAILURE; - } - - TRACE("errno = %d (%s), LastError = %d\n", errno, strerror(errno), dwRet); - - return dwRet; -} - -/*++ -Function: - DIRGetLastErrorFromErrno - -Convert errno into the appropriate win32 error and return it. ---*/ -DWORD DIRGetLastErrorFromErrno( void ) -{ - if (errno == ENOENT) - return ERROR_PATH_NOT_FOUND; - else - return FILEGetLastErrorFromErrno(); -} - - -PAL_ERROR -CorUnix::InternalCreatePipe( - CPalThread *pThread, - HANDLE *phReadPipe, - HANDLE *phWritePipe, - LPSECURITY_ATTRIBUTES lpPipeAttributes, - DWORD nSize - ) -{ -#ifdef TARGET_WASM - // Pipes are not supported on wasm - return ERROR_NOT_SUPPORTED; -#else // TARGET_WASM - PAL_ERROR palError = NO_ERROR; - IPalObject *pReadFileObject = NULL; - IPalObject *pReadRegisteredFile = NULL; - IPalObject *pWriteFileObject = NULL; - IPalObject *pWriteRegisteredFile = NULL; - IDataLock *pDataLock = NULL; - CFileProcessLocalData *pLocalData = NULL; - CObjectAttributes oaFile(NULL, lpPipeAttributes); - - int readWritePipeDes[2] = {-1, -1}; - - if ((phReadPipe == NULL) || (phWritePipe == NULL)) - { - ERROR("One of the two parameters hReadPipe(%p) and hWritePipe(%p) is Null\n",phReadPipe,phWritePipe); - palError = ERROR_INVALID_PARAMETER; - goto InternalCreatePipeExit; - } - - if ((lpPipeAttributes == NULL) || - (lpPipeAttributes->bInheritHandle == FALSE) || - (lpPipeAttributes->lpSecurityDescriptor != NULL)) - { - ASSERT("invalid security attributes!\n"); - palError = ERROR_INVALID_PARAMETER; - goto InternalCreatePipeExit; - } - - if (pipe(readWritePipeDes) == -1) - { - ERROR("pipe() call failed errno:%d (%s) \n", errno, strerror(errno)); - palError = ERROR_INTERNAL_ERROR; - goto InternalCreatePipeExit; - } - - /* enable close-on-exec for both pipes; if one gets passed to CreateProcess - it will be "uncloseonexeced" in order to be inherited */ - if(-1 == fcntl(readWritePipeDes[0],F_SETFD,FD_CLOEXEC)) - { - ASSERT("can't set close-on-exec flag; fcntl() failed. errno is %d " - "(%s)\n", errno, strerror(errno)); - palError = ERROR_INTERNAL_ERROR; - goto InternalCreatePipeExit; - } - if(-1 == fcntl(readWritePipeDes[1],F_SETFD,FD_CLOEXEC)) - { - ASSERT("can't set close-on-exec flag; fcntl() failed. errno is %d " - "(%s)\n", errno, strerror(errno)); - palError = ERROR_INTERNAL_ERROR; - goto InternalCreatePipeExit; - } - - // - // Setup the object for the read end of the pipe - // - - palError = g_pObjectManager->AllocateObject( - pThread, - &otFile, - &oaFile, - &pReadFileObject - ); - - if (NO_ERROR != palError) - { - goto InternalCreatePipeExit; - } - - palError = pReadFileObject->GetProcessLocalData( - pThread, - WriteLock, - &pDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto InternalCreatePipeExit; - } - - pLocalData->inheritable = TRUE; - pLocalData->open_flags = O_RDONLY; - - // - // After storing the file descriptor in the object's local data - // we want to clear it from the array to prevent a possible double - // close if an error occurs. - // - - pLocalData->unix_fd = readWritePipeDes[0]; - readWritePipeDes[0] = -1; - - pDataLock->ReleaseLock(pThread, TRUE); - pDataLock = NULL; - - // - // Setup the object for the write end of the pipe - // - - palError = g_pObjectManager->AllocateObject( - pThread, - &otFile, - &oaFile, - &pWriteFileObject - ); - - if (NO_ERROR != palError) - { - goto InternalCreatePipeExit; - } - - palError = pWriteFileObject->GetProcessLocalData( - pThread, - WriteLock, - &pDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto InternalCreatePipeExit; - } - - pLocalData->inheritable = TRUE; - pLocalData->open_flags = O_WRONLY; - - // - // After storing the file descriptor in the object's local data - // we want to clear it from the array to prevent a possible double - // close if an error occurs. - // - - pLocalData->unix_fd = readWritePipeDes[1]; - readWritePipeDes[1] = -1; - - pDataLock->ReleaseLock(pThread, TRUE); - pDataLock = NULL; - - // - // Register the pipe objects - // - - palError = g_pObjectManager->RegisterObject( - pThread, - pReadFileObject, - &aotFile, - phReadPipe, - &pReadRegisteredFile - ); - - // - // pReadFileObject is invalidated by the call to RegisterObject, so NULL it - // out here to ensure that we don't try to release a reference on - // it down the line. - // - - pReadFileObject = NULL; - - if (NO_ERROR != palError) - { - goto InternalCreatePipeExit; - } - - palError = g_pObjectManager->RegisterObject( - pThread, - pWriteFileObject, - &aotFile, - phWritePipe, - &pWriteRegisteredFile - ); - - // - // pWriteFileObject is invalidated by the call to RegisterObject, so NULL it - // out here to ensure that we don't try to release a reference on - // it down the line. - // - - pWriteFileObject = NULL; - -InternalCreatePipeExit: - - if (NO_ERROR != palError) - { - if (-1 != readWritePipeDes[0]) - { - close(readWritePipeDes[0]); - } - - if (-1 != readWritePipeDes[1]) - { - close(readWritePipeDes[1]); - } - } - - if (NULL != pReadFileObject) - { - pReadFileObject->ReleaseReference(pThread); - } - - if (NULL != pReadRegisteredFile) - { - pReadRegisteredFile->ReleaseReference(pThread); - } - - if (NULL != pWriteFileObject) - { - pWriteFileObject->ReleaseReference(pThread); - } - - if (NULL != pWriteRegisteredFile) - { - pWriteRegisteredFile->ReleaseReference(pThread); - } - - return palError; -#endif // !TARGET_WASM -} - -/*++ -Function: - CreatePipe - -See MSDN doc. ---*/ -PALIMPORT -BOOL -PALAPI -CreatePipe( - OUT PHANDLE hReadPipe, - OUT PHANDLE hWritePipe, - IN LPSECURITY_ATTRIBUTES lpPipeAttributes, - IN DWORD nSize) -{ - PAL_ERROR palError; - CPalThread *pThread; - - PERF_ENTRY(CreatePipe); - ENTRY("CreatePipe(hReadPipe:%p, hWritePipe:%p, lpPipeAttributes:%p, nSize:%d\n", - hReadPipe, hWritePipe, lpPipeAttributes, nSize); - - pThread = InternalGetCurrentThread(); - - palError = InternalCreatePipe( - pThread, - hReadPipe, - hWritePipe, - lpPipeAttributes, - nSize - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT("CreatePipe return %s\n", NO_ERROR == palError ? "TRUE":"FALSE"); - PERF_EXIT(CreatePipe); - return NO_ERROR == palError; -} - -/*++ -init_std_handle [static] - -utility function for FILEInitStdHandles. do the work that is common to all -three standard handles - -Parameters: - HANDLE pStd : Defines which standard handle to assign - FILE *stream : file stream to associate to handle - -Return value: - handle for specified stream, or INVALID_HANDLE_VALUE on failure ---*/ -static HANDLE init_std_handle(HANDLE * pStd, FILE *stream) -{ - CPalThread *pThread = InternalGetCurrentThread(); - PAL_ERROR palError = NO_ERROR; - IPalObject *pFileObject = NULL; - IPalObject *pRegisteredFile = NULL; - IDataLock *pDataLock = NULL; - CFileProcessLocalData *pLocalData = NULL; - CObjectAttributes oa; - - HANDLE hFile = INVALID_HANDLE_VALUE; - int new_fd = -1; - - /* duplicate the FILE *, so that we can fclose() in FILECloseHandle without - closing the original */ -#if defined(TARGET_WASI) - // WASI has no dup(); use fileno directly. FileCleanupRoutine skips - // close() for the borrowed standard-stream fds (STDIN/STDOUT/STDERR). - new_fd = fileno(stream); -#else - new_fd = fcntl(fileno(stream), F_DUPFD_CLOEXEC, 0); // dup, but with CLOEXEC -#endif - if(-1 == new_fd) - { - ERROR("dup() failed; errno is %d (%s)\n", errno, strerror(errno)); - goto done; - } - - palError = g_pObjectManager->AllocateObject( - pThread, - &otFile, - &oa, - &pFileObject - ); - - if (NO_ERROR != palError) - { - goto done; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - WriteLock, - &pDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto done; - } - - pLocalData->inheritable = TRUE; - pLocalData->unix_fd = new_fd; - pLocalData->open_flags = 0; - pLocalData->open_flags_deviceaccessonly = FALSE; - - // - // We've finished initializing our local data, so release that lock - // - - pDataLock->ReleaseLock(pThread, TRUE); - pDataLock = NULL; - - palError = g_pObjectManager->RegisterObject( - pThread, - pFileObject, - &aotFile, - &hFile, - &pRegisteredFile - ); - - // - // pFileObject is invalidated by the call to RegisterObject, so NULL it - // out here to ensure that we don't try to release a reference on - // it down the line. - // - - pFileObject = NULL; - -done: - - if (NULL != pDataLock) - { - pDataLock->ReleaseLock(pThread, TRUE); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - if (NULL != pRegisteredFile) - { - pRegisteredFile->ReleaseReference(pThread); - } - - if (NO_ERROR == palError) - { - *pStd = hFile; - } - else if (-1 != new_fd) - { -#if defined(TARGET_WASI) - // See FileCleanupRoutine: on WASI, new_fd may be a borrowed std fd - // (STDIN/STDOUT/STDERR) because init_std_handle can't dup on WASI. - if (new_fd != STDIN_FILENO && - new_fd != STDOUT_FILENO && - new_fd != STDERR_FILENO) -#endif - close(new_fd); - } - - return hFile; -} - - -/*++ -FILEInitStdHandles - -Create handle objects for stdin, stdout and stderr - -(no parameters) - -Return value: - TRUE on success, FALSE on failure ---*/ -BOOL FILEInitStdHandles(void) -{ - HANDLE stdin_handle; - HANDLE stdout_handle; - HANDLE stderr_handle; - - TRACE("creating handle objects for stdin, stdout, stderr\n"); - - stdin_handle = init_std_handle(&pStdIn, stdin); - if(INVALID_HANDLE_VALUE == stdin_handle) - { - ERROR("failed to create stdin handle\n"); - goto fail; - } - - stdout_handle = init_std_handle(&pStdOut, stdout); - if(INVALID_HANDLE_VALUE == stdout_handle) - { - ERROR("failed to create stdout handle\n"); - CloseHandle(stdin_handle); - goto fail; - } - - stderr_handle = init_std_handle(&pStdErr, stderr); - if(INVALID_HANDLE_VALUE == stderr_handle) - { - ERROR("failed to create stderr handle\n"); - CloseHandle(stdin_handle); - CloseHandle(stdout_handle); - goto fail; - } - return TRUE; - -fail: - pStdIn = INVALID_HANDLE_VALUE; - pStdOut = INVALID_HANDLE_VALUE; - pStdErr = INVALID_HANDLE_VALUE; - return FALSE; -} diff --git a/src/coreclr/pal/src/file/path.cpp b/src/coreclr/pal/src/file/path.cpp deleted file mode 100644 index ff4e0dad2542a8..00000000000000 --- a/src/coreclr/pal/src/file/path.cpp +++ /dev/null @@ -1,765 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ -Module Name: - path.c - -Abstract: - Implementation of all functions related to path support ---*/ - -#include "pal/thread.hpp" -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" -#include "pal/file.h" -#include "pal/stackstring.hpp" - -#include - -#include -#include - -SET_DEFAULT_DEBUG_CHANNEL(FILE); - - -// In safemath.h, Template SafeInt uses macro _ASSERTE, which need to use variable -// defdbgchan defined by SET_DEFAULT_DEBUG_CHANNEL. Therefore, the include statement -// should be placed after the SET_DEFAULT_DEBUG_CHANNEL(FILE) -#include - -int MaxWCharToAcpLengthRatio = 3; -/*++ -Function: - GetFullPathNameA - -See MSDN doc. ---*/ -DWORD -PALAPI -GetFullPathNameA( - IN LPCSTR lpFileName, - IN DWORD nBufferLength, - OUT LPSTR lpBuffer, - OUT LPSTR *lpFilePart) -{ - DWORD nReqPathLen, nRet = 0; - PathCharString unixPath; - LPSTR unixPathBuf; - BOOL fullPath = FALSE; - - PERF_ENTRY(GetFullPathNameA); - ENTRY("GetFullPathNameA(lpFileName=%p (%s), nBufferLength=%u, lpBuffer=%p, " - "lpFilePart=%p)\n", - lpFileName?lpFileName:"NULL", - lpFileName?lpFileName:"NULL", nBufferLength, lpBuffer, lpFilePart); - - if(NULL == lpFileName) - { - WARN("lpFileName is NULL\n"); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - - /* find out if lpFileName is a partial or full path */ - if ('/' == *lpFileName) - { - fullPath = TRUE; - } - - if(fullPath) - { - if( !unixPath.Set(lpFileName, strlen(lpFileName))) - { - ERROR("Set() failed;\n"); - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - } - else - { - - /* build full path */ - if(!GetCurrentDirectoryA(unixPath)) - { - /* no reason for this to fail now... */ - ASSERT("GetCurrentDirectoryA() failed! lasterror is %#xd\n", - GetLastError()); - SetLastError(ERROR_INTERNAL_ERROR); - goto done; - } - - if (!unixPath.Append("/", 1) || - !unixPath.Append(lpFileName,strlen(lpFileName)) - ) - { - ERROR("Append failed!\n"); - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - - } - - unixPathBuf = unixPath.OpenStringBuffer(unixPath.GetCount()); - - /* now we can canonicalize this */ - FILECanonicalizePath(unixPathBuf); - - /* at last, we can figure out how long this path is */ - nReqPathLen = strlen(unixPathBuf); - - unixPath.CloseBuffer(nReqPathLen); - nReqPathLen++; - if(nBufferLength < nReqPathLen) - { - TRACE("reporting insufficient buffer : minimum is %d, caller " - "provided %d\n", nReqPathLen, nBufferLength); - nRet = nReqPathLen; - goto done; - } - - nRet = nReqPathLen-1; - strcpy_s(lpBuffer, nBufferLength, unixPath); - - /* locate the filename component if caller cares */ - if(lpFilePart) - { - *lpFilePart = strrchr(lpBuffer, '/'); - - if (*lpFilePart == NULL) - { - ASSERT("Not able to find '/' in the full path.\n"); - SetLastError( ERROR_INTERNAL_ERROR ); - nRet = 0; - goto done; - } - else - { - (*lpFilePart)++; - } - } - -done: - LOGEXIT("GetFullPathNameA returns DWORD %u\n", nRet); - PERF_EXIT(GetFullPathNameA); - return nRet; -} - - -/*++ -Function: - GetFullPathNameW - -See MSDN doc. ---*/ -DWORD -PALAPI -GetFullPathNameW( - IN LPCWSTR lpFileName, - IN DWORD nBufferLength, - OUT LPWSTR lpBuffer, - OUT LPWSTR *lpFilePart) -{ - LPSTR fileNameA; - CHAR * bufferA; - size_t bufferASize = 0; - PathCharString bufferAPS; - LPSTR lpFilePartA; - int fileNameLength; - int srcSize; - DWORD length; - DWORD nRet = 0; - - PERF_ENTRY(GetFullPathNameW); - ENTRY("GetFullPathNameW(lpFileName=%p (%S), nBufferLength=%u, lpBuffer=%p" - ", lpFilePart=%p)\n", - lpFileName?lpFileName:W16_NULLSTRING, - lpFileName?lpFileName:W16_NULLSTRING, nBufferLength, - lpBuffer, lpFilePart); - - - fileNameLength = WideCharToMultiByte(CP_ACP, 0, lpFileName, - -1, NULL, 0, NULL, NULL); - if (fileNameLength == 0) - { - /* Couldn't convert to ANSI. That's odd. */ - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - else - { - fileNameA = static_cast(alloca(fileNameLength)); - } - - /* Now convert lpFileName to ANSI. */ - srcSize = WideCharToMultiByte (CP_ACP, 0, lpFileName, - -1, fileNameA, fileNameLength, - NULL, NULL ); - if( srcSize == 0 ) - { - DWORD dwLastError = GetLastError(); - ASSERT("WideCharToMultiByte failure! error is %d\n", dwLastError); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - - bufferASize = nBufferLength * MaxWCharToAcpLengthRatio; - bufferA = bufferAPS.OpenStringBuffer(bufferASize); - if (NULL == bufferA) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - length = GetFullPathNameA(fileNameA, bufferASize, bufferA, &lpFilePartA); - bufferAPS.CloseBuffer(length); - - if (length == 0 || length > bufferASize) - { - /* Last error is set by GetFullPathNameA */ - nRet = length; - goto done; - } - - /* Convert back to Unicode the result */ - nRet = MultiByteToWideChar( CP_ACP, 0, bufferA, -1, - lpBuffer, nBufferLength ); - - if (nRet == 0) - { - if ( GetLastError() == ERROR_INSUFFICIENT_BUFFER ) - { - /* get the required length */ - nRet = MultiByteToWideChar( CP_ACP, 0, bufferA, -1, - NULL, 0 ); - SetLastError(ERROR_BUFFER_OVERFLOW); - } - - goto done; - } - - /* MultiByteToWideChar counts the trailing NULL, but - GetFullPathName does not. */ - nRet--; - - /* now set lpFilePart */ - if (lpFilePart != NULL) - { - *lpFilePart = lpBuffer; - *lpFilePart += MultiByteToWideChar( CP_ACP, 0, bufferA, - lpFilePartA - bufferA, NULL, 0); - } - -done: - LOGEXIT("GetFullPathNameW returns DWORD %u\n", nRet); - PERF_EXIT(GetFullPathNameW); - return nRet; -} - - -/*++ -Function: - GetTempPathA - -See MSDN. - -Notes: - On Windows, the temp path is determined by the following steps: - 1. The value of the "TMP" environment variable, or if it doesn't exist, - 2. The value of the "TEMP" environment variable, or if it doesn't exist, - 3. The Windows directory. - - On Unix, we follow in spirit: - 1. The value of the "TMPDIR" environment variable, or if it doesn't exist, - 2. The /tmp directory. - This is the same approach employed by mktemp. - ---*/ -DWORD -PALAPI -GetTempPathA( - IN DWORD nBufferLength, - OUT LPSTR lpBuffer) -{ - DWORD dwPathLen = 0; - - PERF_ENTRY(GetTempPathA); - ENTRY("GetTempPathA(nBufferLength=%u, lpBuffer=%p)\n", - nBufferLength, lpBuffer); - - if ( !lpBuffer ) - { - ERROR( "lpBuffer was not a valid pointer.\n" ) - SetLastError( ERROR_INVALID_PARAMETER ); - LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen); - PERF_EXIT(GetTempPathA); - return 0; - } - - /* Try the TMPDIR environment variable. This is the same env var checked by mktemp. */ - dwPathLen = GetEnvironmentVariableA("TMPDIR", lpBuffer, nBufferLength); - if (dwPathLen > 0) - { - /* The env var existed. dwPathLen will be the length without null termination - * if the entire value was successfully retrieved, or it'll be the length - * required to store the value with null termination. - */ - if (dwPathLen < nBufferLength) - { - /* The environment variable fit in the buffer. Make sure it ends with '/'. */ - if (lpBuffer[dwPathLen - 1] != '/') - { - /* If adding the slash would still fit in our provided buffer, do it. Otherwise, - * let the caller know how much space would be needed. - */ - if (dwPathLen + 2 <= nBufferLength) - { - lpBuffer[dwPathLen++] = '/'; - lpBuffer[dwPathLen] = '\0'; - } - else - { - dwPathLen += 2; - } - } - } - else /* dwPathLen >= nBufferLength */ - { - /* The value is too long for the supplied buffer. dwPathLen will now be the - * length required to hold the value, but we don't know whether that value - * is going to be '/' terminated. Since we'll need enough space for the '/', and since - * a caller would assume that the dwPathLen we return will be sufficient, - * we make sure to account for it in dwPathLen even if that means we end up saying - * one more byte of space is needed than actually is. - */ - dwPathLen++; - } - } - else /* env var not found or was empty */ - { - /* no luck, use /tmp/ or /data/local/tmp on Android */ - const char *defaultDir = TEMP_DIRECTORY_PATH; - size_t defaultDirLen = strlen(defaultDir); - if (defaultDirLen < nBufferLength) - { - dwPathLen = defaultDirLen; - strcpy_s(lpBuffer, nBufferLength, defaultDir); - } - else - { - /* get the required length */ - dwPathLen = defaultDirLen + 1; - } - } - - if ( dwPathLen >= nBufferLength ) - { - ERROR("Buffer is too small, need space for %d characters including null termination\n", dwPathLen); - SetLastError( ERROR_INSUFFICIENT_BUFFER ); - } - - LOGEXIT("GetTempPathA returns DWORD %u\n", dwPathLen); - PERF_EXIT(GetTempPathA); - return dwPathLen; -} - -/*++ -FILECanonicalizePath - Removes all instances of '/./', '/../' and '//' from an absolute path. - -Parameters: - LPSTR lpUnixPath : absolute path to modify, in Unix format - -(no return value) - -Notes : --behavior is undefined if path is not absolute --the order of steps *is* important: /one/./../two would give /one/two - instead of /two if step 3 was done before step 2 --reason for this function is that GetFullPathName can't use realpath(), since - realpath() requires the given path to be valid and GetFullPathName does not. ---*/ -void FILECanonicalizePath(LPSTR lpUnixPath) -{ - LPSTR slashslashptr; - LPSTR dotdotptr; - LPSTR slashdotptr; - LPSTR slashptr; - - /* step 1 : replace '//' sequences by a single '/' */ - - slashslashptr = lpUnixPath; - while(1) - { - slashslashptr = strstr(slashslashptr,"//"); - if(NULL == slashslashptr) - { - break; - } - /* remove extra '/' */ - TRACE("stripping '//' from %s\n", lpUnixPath); - memmove(slashslashptr,slashslashptr+1,strlen(slashslashptr+1)+1); - } - - /* step 2 : replace '/./' sequences by a single '/' */ - - slashdotptr = lpUnixPath; - while(1) - { - slashdotptr = strstr(slashdotptr,"/./"); - if(NULL == slashdotptr) - { - break; - } - /* strip the extra '/.' */ - TRACE("removing '/./' sequence from %s\n", lpUnixPath); - memmove(slashdotptr,slashdotptr+2,strlen(slashdotptr+2)+1); - } - - /* step 3 : replace '//../' sequences by a single '/' */ - - while(1) - { - dotdotptr = strstr(lpUnixPath,"/../"); - if(NULL == dotdotptr) - { - break; - } - if(dotdotptr == lpUnixPath) - { - /* special case : '/../' at the beginning of the path are replaced - by a single '/' */ - TRACE("stripping leading '/../' from %s\n", lpUnixPath); - memmove(lpUnixPath, lpUnixPath+3,strlen(lpUnixPath+3)+1); - continue; - } - - /* null-terminate the string before the '/../', so that strrchr will - start looking right before it */ - *dotdotptr = '\0'; - slashptr = strrchr(lpUnixPath,'/'); - if(NULL == slashptr) - { - /* this happens if this function was called with a relative path. - don't do that. */ - ASSERT("can't find leading '/' before '/../ sequence\n"); - break; - } - TRACE("removing '//../' sequence from %s\n", lpUnixPath); - memmove(slashptr,dotdotptr+3,strlen(dotdotptr+3)+1); - } - - /* step 4 : remove a trailing '/..' */ - - dotdotptr = strstr(lpUnixPath,"/.."); - if(dotdotptr == lpUnixPath) - { - /* if the full path is simply '/..', replace it by '/' */ - lpUnixPath[1] = '\0'; - } - else if(NULL != dotdotptr && '\0' == dotdotptr[3]) - { - *dotdotptr = '\0'; - slashptr = strrchr(lpUnixPath,'/'); - if(NULL != slashptr) - { - /* make sure the last slash isn't the root */ - if (slashptr == lpUnixPath) - { - lpUnixPath[1] = '\0'; - } - else - { - *slashptr = '\0'; - } - } - } - - /* step 5 : remove a trailing '/.' */ - - slashdotptr = strstr(lpUnixPath,"/."); - if (slashdotptr != NULL && slashdotptr[2] == '\0') - { - if(slashdotptr == lpUnixPath) - { - // if the full path is simply '/.', replace it by '/' */ - lpUnixPath[1] = '\0'; - } - else - { - *slashdotptr = '\0'; - } - } -} - - -/*++ -Function: - SearchPathW - -See MSDN doc. - -PAL-specific notes : --lpPath must be non-NULL; path delimiters are platform-dependent (':' for Unix) --lpFileName must be non-NULL, may be an absolute path --lpExtension must be NULL --lpFilePart (if non-NULL) doesn't need to be used (but we do) ---*/ -DWORD -PALAPI -SearchPathW( - IN LPCWSTR lpPath, - IN LPCWSTR lpFileName, - IN LPCWSTR lpExtension, - IN DWORD nBufferLength, - OUT LPWSTR lpBuffer, - OUT LPWSTR *lpFilePart - ) -{ - DWORD nRet = 0; - WCHAR * FullPath; - size_t FullPathLength = 0; - PathWCharString FullPathPS; - LPCWSTR pPathStart; - LPCWSTR pPathEnd; - size_t PathLength; - size_t FileNameLength; - DWORD dw; - DWORD length; - char * AnsiPath; - PathCharString AnsiPathPS; - size_t CanonicalPathLength; - int canonical_size; - WCHAR * CanonicalPath; - PathWCharString CanonicalPathPS; - - PERF_ENTRY(SearchPathW); - ENTRY("SearchPathW(lpPath=%p (%S), lpFileName=%p (%S), lpExtension=%p, " - "nBufferLength=%u, lpBuffer=%p, lpFilePart=%p)\n", - lpPath, - lpPath, lpFileName, lpFileName, lpExtension, nBufferLength, lpBuffer, - lpFilePart); - - /* validate parameters */ - - if(NULL == lpPath) - { - ASSERT("lpPath may not be NULL\n"); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - if(NULL == lpFileName) - { - ASSERT("lpFileName may not be NULL\n"); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - if(NULL != lpExtension) - { - ASSERT("lpExtension must be NULL, is %p instead\n", lpExtension); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - - /* special case : if file name contains absolute path, don't search the - provided path */ - if(L'/' == lpFileName[0]) - { - /* Canonicalize the path to deal with back-to-back '/', etc. */ - length = MAX_LONGPATH; //Use it for first try - CanonicalPath = CanonicalPathPS.OpenStringBuffer(length); - if (NULL == CanonicalPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - dw = GetFullPathNameW(lpFileName, length+1, CanonicalPath, NULL); - CanonicalPathPS.CloseBuffer(dw); - if (length+1 < dw) - { - CanonicalPath = CanonicalPathPS.OpenStringBuffer(dw-1); - if (NULL == CanonicalPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - dw = GetFullPathNameW(lpFileName, dw, CanonicalPath, NULL); - CanonicalPathPS.CloseBuffer(dw); - } - - if (dw == 0) - { - WARN("couldn't canonicalize path <%S>, error is %#x. failing.\n", - lpPath, GetLastError()); - SetLastError(ERROR_INVALID_PARAMETER); - goto done; - } - - /* see if the file exists */ - CanonicalPathLength = (PAL_wcslen(CanonicalPath)+1) * MaxWCharToAcpLengthRatio; - AnsiPath = AnsiPathPS.OpenStringBuffer(CanonicalPathLength); - if (NULL == AnsiPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - canonical_size = WideCharToMultiByte(CP_ACP, 0, CanonicalPath, -1, - AnsiPath, CanonicalPathLength, NULL, NULL); - AnsiPathPS.CloseBuffer(canonical_size); - - if(0 == access(AnsiPath, F_OK)) - { - /* found it */ - nRet = dw; - } - } - else - { - LPCWSTR pNextPath; - - pNextPath = lpPath; - - FileNameLength = PAL_wcslen(lpFileName); - - while (*pNextPath) - { - pPathStart = pNextPath; - - /* get a pointer to the end of the first path in pPathStart */ - pPathEnd = PAL_wcschr(pPathStart, ':'); - if (!pPathEnd) - { - pPathEnd = pPathStart + PAL_wcslen(pPathStart); - /* we want to break out of the loop after this pass, so let - *pNextPath be '\0' */ - pNextPath = pPathEnd; - } - else - { - /* point to the next component in the path string */ - pNextPath = pPathEnd+1; - } - - PathLength = pPathEnd-pPathStart; - - if(0 == PathLength) - { - /* empty component : there were 2 consecutive ':' */ - continue; - } - - /* Construct a pathname by concatenating one path from lpPath, '/' - and lpFileName */ - FullPathLength = PathLength + FileNameLength; - FullPath = FullPathPS.OpenStringBuffer(FullPathLength+1); - if (NULL == FullPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - memcpy(FullPath, pPathStart, PathLength*sizeof(WCHAR)); - FullPath[PathLength] = '/'; - PAL_wcscpy(&FullPath[PathLength+1], lpFileName); - - FullPathPS.CloseBuffer(FullPathLength+1); - - /* Canonicalize the path to deal with back-to-back '/', etc. */ - length = MAX_LONGPATH; //Use it for first try - CanonicalPath = CanonicalPathPS.OpenStringBuffer(length); - if (NULL == CanonicalPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - dw = GetFullPathNameW(FullPath, length+1, - CanonicalPath, NULL); - CanonicalPathPS.CloseBuffer(dw); - - if (length+1 < dw) - { - CanonicalPath = CanonicalPathPS.OpenStringBuffer(dw-1); - if (NULL == CanonicalPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - dw = GetFullPathNameW(FullPath, dw, CanonicalPath, NULL); - CanonicalPathPS.CloseBuffer(dw); - } - - if (dw == 0) - { - /* Call failed - possibly low memory. Skip the path */ - WARN("couldn't canonicalize path <%S>, error is %#x. " - "skipping it\n", FullPath, GetLastError()); - continue; - } - - /* see if the file exists */ - CanonicalPathLength = (PAL_wcslen(CanonicalPath)+1) * MaxWCharToAcpLengthRatio; - AnsiPath = AnsiPathPS.OpenStringBuffer(CanonicalPathLength); - if (NULL == AnsiPath) - { - SetLastError(ERROR_NOT_ENOUGH_MEMORY); - goto done; - } - canonical_size = WideCharToMultiByte(CP_ACP, 0, CanonicalPath, -1, - AnsiPath, CanonicalPathLength, NULL, NULL); - AnsiPathPS.CloseBuffer(canonical_size); - - if(0 == access(AnsiPath, F_OK)) - { - /* found it */ - nRet = dw; - break; - } - } - } - - if (nRet == 0) - { - /* file not found anywhere; say so. in Windows, this always seems to say - FILE_NOT_FOUND, even if path doesn't exist */ - SetLastError(ERROR_FILE_NOT_FOUND); - } - else - { - /* find out the required buffer size, copy path to buffer if it's - large enough */ - nRet = PAL_wcslen(CanonicalPath)+1; - if(nRet <= nBufferLength) - { - if(NULL == lpBuffer) - { - /* Windows merily crashes here, but let's not */ - ERROR("caller told us buffer size was %d, but buffer is NULL\n", - nBufferLength); - SetLastError(ERROR_INVALID_PARAMETER); - nRet = 0; - goto done; - } - PAL_wcscpy(lpBuffer, CanonicalPath); - - /* don't include the null-terminator in the count if buffer was - large enough */ - nRet--; - - if(NULL != lpFilePart) - { - *lpFilePart = PAL_wcsrchr(lpBuffer, '/'); - if(NULL == *lpFilePart) - { - ASSERT("no '/' in full path!\n"); - } - else - { - /* point to character after last '/' */ - (*lpFilePart)++; - } - } - } - } -done: - LOGEXIT("SearchPathW returns DWORD %u\n", nRet); - PERF_EXIT(SearchPathW); - return nRet; -} diff --git a/src/coreclr/pal/src/include/pal/corunix.hpp b/src/coreclr/pal/src/include/pal/corunix.hpp index c4e44c9922991b..1fc99579a16a82 100644 --- a/src/coreclr/pal/src/include/pal/corunix.hpp +++ b/src/coreclr/pal/src/include/pal/corunix.hpp @@ -157,11 +157,7 @@ namespace CorUnix enum PalObjectTypeId { - otiFile = 0, - otiFileMapping, - otiSocket, - otiThread, - otiIOCompletionPort, + otiThread = 0, ObjectTypeIdCount // This entry must come last in the enumeration }; diff --git a/src/coreclr/pal/src/include/pal/file.h b/src/coreclr/pal/src/include/pal/file.h deleted file mode 100644 index 399c42cff18466..00000000000000 --- a/src/coreclr/pal/src/include/pal/file.h +++ /dev/null @@ -1,107 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - include/pal/file.h - -Abstract: - Header file for file utility functions. - -Revision History: - - - ---*/ - -#ifndef _PAL_FILE_H_ -#define _PAL_FILE_H_ - -#include "pal/stackstring.hpp" -#include -#include -#include - -#ifdef __cplusplus -extern "C" -{ -#endif // __cplusplus - -typedef struct _find_handle -{ - struct _find_handle *self_addr; /* for pointer verification */ - - char dir[_MAX_DIR]; - char fname[MAX_PATH_FNAME]; /* includes extension */ - glob_t gGlob; - char **next; -} find_obj; - -/*++ -FILECanonicalizePath - Removes all instances of '/./', '/../' and '//' from an absolute path. - -Parameters: - LPSTR lpUnixPath : absolute path to modify, in Unix format - -(no return value) - -Notes : --behavior is undefined if path is not absolute --the order of steps *is* important: /one/./../two would give /one/two - instead of /two if step 3 was done before step 2 --reason for this function is that GetFullPathName can't use realpath(), since - realpath() requires the given path to be valid and GetFullPathName does not. ---*/ -void FILECanonicalizePath(LPSTR lpUnixPath); - -/*++ -Function: - FILEGetLastErrorFromErrno - -Convert errno into the appropriate win32 error and return it. ---*/ -DWORD FILEGetLastErrorFromErrno( void ); - -/*++ -Function: - DIRGetLastErrorFromErrno - -Convert errno into the appropriate win32 error and return it. ---*/ -DWORD DIRGetLastErrorFromErrno( void ); - -/*++ -FILEInitStdHandles - -Create handle objects for stdin, stdout and stderr - -(no parameters) - -Return value: - TRUE on success, FALSE on failure ---*/ -BOOL FILEInitStdHandles(void); - -/*++ - -Function : - FILEGetProperNotFoundError - -Returns the proper error code, based on the -Windows behavoir. - - IN LPSTR lpPath - The path to check. - LPDWORD lpErrorCode - The error to set. -*/ -void FILEGetProperNotFoundError( LPCSTR lpPath, LPDWORD lpErrorCode ); - -#ifdef __cplusplus -} -#endif // __cplusplus - -#endif /* _PAL_FILE_H_ */ diff --git a/src/coreclr/pal/src/include/pal/file.hpp b/src/coreclr/pal/src/include/pal/file.hpp deleted file mode 100644 index f7b36f01572d90..00000000000000 --- a/src/coreclr/pal/src/include/pal/file.hpp +++ /dev/null @@ -1,203 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - include/pal/file.hpp - -Abstract: - Header file for file utility functions. - -Revision History: - - - ---*/ - -#ifndef _PAL_FILE_HPP_ -#define _PAL_FILE_HPP_ - -#include "corunix.hpp" -#include "pal/stackstring.hpp" -#include -#include -#include - - -namespace CorUnix -{ - extern CObjectType otFile; - extern CAllowedObjectTypes aotFile; - - class CFileProcessLocalData - { - public: - int unix_fd; - int open_flags; /* stores Unix file creation flags */ - BOOL open_flags_deviceaccessonly; - CHAR *unix_filename; - BOOL inheritable; - }; - - PAL_ERROR - InternalCreateFile( - CPalThread *pThread, - LPCSTR lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - LPSECURITY_ATTRIBUTES lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - HANDLE hTemplateFile, - HANDLE *pFileHandle - ); - - PAL_ERROR - InternalWriteFile( - CPalThread *pThread, - HANDLE hFile, - LPCVOID lpBuffer, - DWORD nNumberOfBytesToWrite, - LPDWORD lpNumberOfBytesWritten, - LPOVERLAPPED lpOverlapped - ); - - PAL_ERROR - InternalReadFile( - CPalThread *pThread, - HANDLE hFile, - LPVOID lpBuffer, - DWORD nNumberOfBytesToRead, - LPDWORD lpNumberOfBytesRead, - LPOVERLAPPED lpOverlapped - ); - - PAL_ERROR - InternalGetFileSize( - CPalThread *pThread, - HANDLE hFile, - DWORD *pdwFileSizeLow, - DWORD *pdwFileSizeHigh - ); - - PAL_ERROR - InternalFlushFileBuffers( - CPalThread *pThread, - HANDLE hFile - ); - - PAL_ERROR - InternalCreatePipe( - CPalThread *pThread, - HANDLE *phReadPipe, - HANDLE *phWritePipe, - LPSECURITY_ATTRIBUTES lpPipeAttributes, - DWORD nSize - ); - - PAL_ERROR - InternalSetFilePointer( - CPalThread *pThread, - HANDLE hFile, - LONG lDistanceToMove, - PLONG lpDistanceToMoveHigh, - DWORD dwMoveMethod, - PLONG lpNewFilePointerLow - ); - - BOOL - RealPathHelper(LPCSTR lpUnixPath, PathCharString& lpBuffer); - /*++ - InternalCanonicalizeRealPath - Wraps realpath() to hide platform differences. See the man page for - realpath(3) for details of how realpath() works. - - On systems on which realpath() allows the last path component to not - exist, this is a straight thunk through to realpath(). On other - systems, we remove the last path component, then call realpath(). - --*/ - PAL_ERROR - InternalCanonicalizeRealPath( - LPCSTR lpUnixPath, - PathCharString& lpBuffer - ); - - /*++ - InternalOpen - Wraps open - --*/ - int - InternalOpen( - const char *szFilename, - int nFlags, - ... - ); -} - -extern "C" -{ - -// -// These routines should all be separated out into something along the lines -// of fileutils.* (instead of being comingled with the core file object -// code). -// - -/*++ -FILECanonicalizePath - Removes all instances of '/./', '/../' and '//' from an absolute path. - -Parameters: - LPSTR lpUnixPath : absolute path to modify, in Unix format - -(no return value) - -Notes : --behavior is undefined if path is not absolute --the order of steps *is* important: /one/./../two would give /one/two - instead of /two if step 3 was done before step 2 --reason for this function is that GetFullPathName can't use realpath(), since - realpath() requires the given path to be valid and GetFullPathName does not. ---*/ -void FILECanonicalizePath(LPSTR lpUnixPath); - -/*++ -Function: - FILEGetLastErrorFromErrno - -Convert errno into the appropriate win32 error and return it. ---*/ -DWORD FILEGetLastErrorFromErrno( void ); - -/*++ -FILEInitStdHandles - -Create handle objects for stdin, stdout and stderr - -(no parameters) - -Return value: - TRUE on success, FALSE on failure ---*/ -BOOL FILEInitStdHandles(void); - -/*++ - -Function : - FILEGetProperNotFoundError - -Returns the proper error code, based on the -Windows behavoir. - - IN LPSTR lpPath - The path to check. - LPDWORD lpErrorCode - The error to set. -*/ -void FILEGetProperNotFoundError( LPCSTR lpPath, LPDWORD lpErrorCode ); - -} - -#endif /* _PAL_FILE_HPP_ */ diff --git a/src/coreclr/pal/src/include/pal/map.hpp b/src/coreclr/pal/src/include/pal/map.hpp deleted file mode 100644 index 10910eff44e0b3..00000000000000 --- a/src/coreclr/pal/src/include/pal/map.hpp +++ /dev/null @@ -1,153 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - include/pal/map.hpp - -Abstract: - - Header file for file mapping functions. - - - ---*/ - -#ifndef _PAL_MAP_H_ -#define _PAL_MAP_H_ - -#include "corunix.hpp" -#include "list.h" -#include - -extern "C" -{ -#ifndef NO_INO -#define NO_INO ((ino_t)-1) -#endif - - /*++ - Function : - MapInitialize - - Initialize the critical sections. - - Return value: - TRUE if initialization succeeded - FALSE otherwise - --*/ - BOOL MAPInitialize( void ); - - /*++ - Function : - MapCleanup - - Deletes the critical sections. - - --*/ - void MAPCleanup( void ); - -} - -namespace CorUnix -{ - extern CObjectType otFileMapping; - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - typedef struct _NativeMapHolder - { - Volatile ref_count; - LPVOID address; - SIZE_T size; - SIZE_T offset; /* for future use */ - } NativeMapHolder; -#endif - - /* Process specific information. This - structure is not stored in shared memory.*/ - typedef struct _MVL - { - LIST_ENTRY Link; - - // - // Each MVL entry holds a reference to its parent file - // mapping object. - // - - IPalObject *pFileMapping; - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - NativeMapHolder * pNMHolder; /* Ref-counted holder for memory mapping */ - dev_t MappedFileDevNum; /* ID of device containing the file to be mapped */ - ino_t MappedFileInodeNum; /* Inode number of file to be mapped. - These two fields are used used to uniquely - identify files on systems that do not allow - more than one shared mmapping per region of - physical file, per process */ -#endif - LPVOID lpAddress; /* The pointer to the mapped memory. */ - SIZE_T NumberOfBytesToMap; /* Number of bytes to map. */ - DWORD dwDesiredAccess; /* Desired access. */ - } MAPPED_VIEW_LIST, * PMAPPED_VIEW_LIST; - - class CFileMappingImmutableData - { - public: - CHAR *lpFileName; - UINT MaxSize; // The max size of the file mapping object - DWORD flProtect; // Protection desired for the file view - BOOL bPALCreatedTempFile; // TRUE if it's a PAL created file - DWORD dwDesiredAccessWhenOpened; // FILE_MAP_WRITE etc - }; - - class CFileMappingProcessLocalData - { - public: - INT UnixFd; /* File descriptor. */ - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - dev_t MappedFileDevNum; /* ID of device containing the file to be mapped */ - ino_t MappedFileInodeNum; /* Inode number of file to be mapped. - These two fields are used used to uniquely - identify files on systems that do not allow - more than one shared mmapping per region of - physical file, per process */ -#endif - }; - - PAL_ERROR - InternalCreateFileMapping( - CPalThread *pThread, - HANDLE hFile, - LPSECURITY_ATTRIBUTES lpFileMappingAttributes, - DWORD flProtect, - DWORD dwMaximumSizeHigh, - DWORD dwMaximumSizeLow, - LPCWSTR lpName, - HANDLE *phMapping - ); - - PAL_ERROR - InternalMapViewOfFile( - CPalThread *pThread, - HANDLE hFileMappingObject, - DWORD dwDesiredAccess, - DWORD dwFileOffsetHigh, - DWORD dwFileOffsetLow, - SIZE_T dwNumberOfBytesToMap, - LPVOID *ppvBaseAddress - ); - - PAL_ERROR - InternalUnmapViewOfFile( - CPalThread *pThread, - LPCVOID lpBaseAddress - ); - -} - -#endif /* _PAL_MAP_H_ */ diff --git a/src/coreclr/pal/src/include/pal/palinternal.h b/src/coreclr/pal/src/include/pal/palinternal.h index b76051e6e3bf5e..0f14fc3bee1788 100644 --- a/src/coreclr/pal/src/include/pal/palinternal.h +++ b/src/coreclr/pal/src/include/pal/palinternal.h @@ -213,14 +213,6 @@ function_name() to call the system's implementation #undef assert #define assert (Use__ASSERTE_instead_of_assert) assert -#ifndef __ANDROID__ -#define TEMP_DIRECTORY_PATH "/tmp/" -#else -// On Android, "/tmp/" doesn't exist; temporary files should go to -// /data/local/tmp/ -#define TEMP_DIRECTORY_PATH "/data/local/tmp/" -#endif - #ifdef __APPLE__ #define APPLICATION_CONTAINER_BASE_PATH_SUFFIX "/Library/Group Containers/" diff --git a/src/coreclr/pal/src/include/pal/stackstring.hpp b/src/coreclr/pal/src/include/pal/stackstring.hpp index 22e79a571502aa..558df988be9347 100644 --- a/src/coreclr/pal/src/include/pal/stackstring.hpp +++ b/src/coreclr/pal/src/include/pal/stackstring.hpp @@ -251,8 +251,3 @@ typedef StackString PathCharString; typedef StackString PathWCharString; #endif #endif - -// Some Helper Definitions -DWORD -GetCurrentDirectoryA( - PathCharString& lpBuffer); diff --git a/src/coreclr/pal/src/include/pal/utils.h b/src/coreclr/pal/src/include/pal/utils.h index 18298997e1c021..2636f04db4cf5f 100644 --- a/src/coreclr/pal/src/include/pal/utils.h +++ b/src/coreclr/pal/src/include/pal/utils.h @@ -141,29 +141,4 @@ void UTIL_SetLastErrorFromMach(kern_return_t MachReturn); #ifdef __cplusplus } #endif // __cplusplus -class StringHolder - { - private: - LPSTR data; - public: - StringHolder() : data(NULL) { } - ~StringHolder() - { - free( data); - } - - operator LPSTR () { return data;} - - StringHolder& operator= (LPSTR value) - { - data = value; - return *this; - } - - BOOL IsNull() - { - return data == NULL; - } - - }; #endif /* _PAL_UTILS_H_ */ diff --git a/src/coreclr/pal/src/init/pal.cpp b/src/coreclr/pal/src/init/pal.cpp index 0d9c9fb6359d53..e7ce5834ff974e 100644 --- a/src/coreclr/pal/src/init/pal.cpp +++ b/src/coreclr/pal/src/init/pal.cpp @@ -14,8 +14,6 @@ SET_DEFAULT_DEBUG_CHANNEL(PAL); // some headers have code with asserts, so do th #include "pal/thread.hpp" #include "pal/procobj.hpp" -#include "pal/file.hpp" -#include "pal/map.hpp" #include "../objmgr/listedobjectmanager.hpp" #include "pal/seh.hpp" #include "pal/palinternal.h" @@ -456,14 +454,6 @@ Initialize( palError = ERROR_GEN_FAILURE; - /* Initialize the File mapping critical section. */ - if (FALSE == MAPInitialize()) - { - ERROR("Unable to initialize file mapping support\n"); - palError = ERROR_PALINIT_MAP; - goto CLEANUP6; - } - if (flags & PAL_INITIALIZE_FLUSH_PROCESS_WRITE_BUFFERS) { // Initialize before first thread is created for faster load on Linux @@ -483,17 +473,6 @@ Initialize( goto CLEANUP10; } - if (flags & PAL_INITIALIZE_STD_HANDLES) - { - /* create file objects for standard handles */ - if (!FILEInitStdHandles()) - { - ERROR("Unable to initialize standard file handles\n"); - palError = ERROR_PALINIT_STD_HANDLES; - goto CLEANUP14; - } - } - TRACE("First-time PAL initialization complete.\n"); // Incrementing the init_count here serves as a synchronization point, // since it is a Volatile variable, and modifying it will have release semantics. @@ -515,11 +494,7 @@ Initialize( } goto done; -CLEANUP14: - SEHCleanup(); CLEANUP10: - MAPCleanup(); -CLEANUP6: // Cleanup initial process data CLEANUP2: free(exe_path); diff --git a/src/coreclr/pal/src/loader/module.cpp b/src/coreclr/pal/src/loader/module.cpp index d31ae4373a1cac..e1c9501da5021d 100644 --- a/src/coreclr/pal/src/loader/module.cpp +++ b/src/coreclr/pal/src/loader/module.cpp @@ -21,15 +21,12 @@ Module Name: SET_DEFAULT_DEBUG_CHANNEL(LOADER); // some headers have code with asserts, so do this first #include "pal/thread.hpp" -#include "pal/file.hpp" #include "pal/palinternal.h" #include "pal/module.h" #include "pal/process.h" -#include "pal/file.h" #include "pal/utils.h" #include "pal/init.h" #include "pal/environ.h" -#include "pal/map.hpp" #include "pal/stackstring.hpp" #include @@ -78,6 +75,9 @@ using namespace CorUnix; #define LIBC_NAME_WITHOUT_EXTENSION "libc" +// Upper bound on ACP bytes produced per WCHAR by WideCharToMultiByte. +static const int MaxWCharToAcpLengthFactor = 3; + /* static variables ***********************************************************/ /* critical section that regulates access to the module list */ @@ -90,8 +90,6 @@ MODSTRUCT *pal_module = nullptr; char * g_szCoreCLRPath = nullptr; bool g_running_in_exe = false; -int MaxWCharToAcpLength = 3; - /* static function declarations ***********************************************/ template static bool LOADVerifyLibraryPath(const TChar *libraryPath); @@ -189,7 +187,7 @@ LoadLibraryExW( goto done; } - lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength); + lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLengthFactor); if (nullptr == lpstr) { goto done; @@ -559,7 +557,7 @@ PAL_LoadLibraryDirect( goto done; } - lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLength); + lpstr = pathstr.OpenStringBuffer((PAL_wcslen(lpLibFileName)+1) * MaxWCharToAcpLengthFactor); if (nullptr == lpstr) { goto done; @@ -1294,7 +1292,7 @@ static bool LOADConvertLibraryPathWideStringToMultibyteString( _ASSERTE(multibyteLibraryPathLengthRef != nullptr); _ASSERTE(wideLibraryPath != nullptr); - size_t length = (PAL_wcslen(wideLibraryPath)+1) * MaxWCharToAcpLength; + size_t length = (PAL_wcslen(wideLibraryPath)+1) * MaxWCharToAcpLengthFactor; *multibyteLibraryPathLengthRef = WideCharToMultiByte(CP_ACP, 0, wideLibraryPath, -1, multibyteLibraryPath, length, nullptr, nullptr); diff --git a/src/coreclr/pal/src/locale/unicode.cpp b/src/coreclr/pal/src/locale/unicode.cpp index a66a0edc14d488..d163f851676c9d 100644 --- a/src/coreclr/pal/src/locale/unicode.cpp +++ b/src/coreclr/pal/src/locale/unicode.cpp @@ -13,7 +13,6 @@ Implementation of all functions related to Unicode support #include "pal/palinternal.h" #include "pal/dbgmsg.h" -#include "pal/file.h" #include #include #include "pal/cruntime.h" diff --git a/src/coreclr/pal/src/map/map.cpp b/src/coreclr/pal/src/map/map.cpp deleted file mode 100644 index d9220cc25dc238..00000000000000 --- a/src/coreclr/pal/src/map/map.cpp +++ /dev/null @@ -1,1715 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*++ - - - -Module Name: - - map.cpp - -Abstract: - - Implementation of file mapping API. - - - ---*/ - - -#include "pal/palinternal.h" -#include "pal/dbgmsg.h" -#include "pal/init.h" -#include "pal/map.hpp" -#include "pal/thread.hpp" -#include "pal/file.hpp" - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace CorUnix; - -SET_DEFAULT_DEBUG_CHANNEL(VIRTUAL); - -#include "pal/utils.h" - -// -// The mapping critical section guards access to the list -// of currently mapped views. If a thread needs to access -// both this critical section and the data for an object -// it must acquire the object data first. That is, a thread -// cannot acquire any other locks after taking hold of -// this critical section. -// - -minipal_mutex mapping_critsec; -LIST_ENTRY MappedViewList; - -#ifndef CORECLR -static PAL_ERROR MAPCreateTempFile(CPalThread *, PINT, PSZ); -#endif // !CORECLR -static PAL_ERROR MAPGrowLocalFile(INT, off_t); -static PMAPPED_VIEW_LIST MAPGetViewForAddress( LPCVOID ); -static PAL_ERROR MAPDesiredAccessAllowed( DWORD, DWORD, DWORD ); - -static INT MAPProtectionToFileOpenFlags( DWORD ); -static BOOL MAPIsRequestPermissible( DWORD, CFileProcessLocalData * ); -static BOOL MAPContainsInvalidFlags( DWORD ); -static DWORD MAPConvertProtectToAccess( DWORD ); -static INT MAPFileMapToMmapFlags( DWORD ); -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS -static NativeMapHolder * NewNativeMapHolder(CPalThread *pThread, LPVOID address, SIZE_T size, - SIZE_T offset, long init_ref_count); -static LONG NativeMapHolderAddRef(NativeMapHolder * thisPMH); -static LONG NativeMapHolderRelease(CPalThread *pThread, NativeMapHolder * thisPMH); -static PMAPPED_VIEW_LIST FindSharedMappingReplacement(CPalThread *pThread, dev_t deviceNum, ino_t inodeNum, - SIZE_T size, SIZE_T offset); -#endif - -/* We need MAP_ANON. However on some platforms like HP-UX, it is defined as MAP_ANONYMOUS */ -#if !defined(MAP_ANON) && defined(MAP_ANONYMOUS) -#define MAP_ANON MAP_ANONYMOUS -#endif - -void -FileMappingCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup, - bool fShutdown - ); - -void -CFileMappingImmutableDataCopyRoutine( - void *pImmData, - void *pImmDataTarget - ); - -void -CFileMappingImmutableDataCleanupRoutine( - void *pImmData - ); - -CObjectType CorUnix::otFileMapping( - otiFileMapping, - FileMappingCleanupRoutine, - sizeof(CFileMappingImmutableData), - CFileMappingImmutableDataCopyRoutine, - CFileMappingImmutableDataCleanupRoutine, - sizeof(CFileMappingProcessLocalData), - NULL // No process local data cleanup routine - ); - -CAllowedObjectTypes aotFileMapping(otiFileMapping); - -void -CFileMappingImmutableDataCopyRoutine( - void *pImmData, - void *pImmDataTarget - ) -{ - CFileMappingImmutableData *pImmutableData = (CFileMappingImmutableData *) pImmData; - CFileMappingImmutableData *pImmutableDataTarget = (CFileMappingImmutableData *) pImmDataTarget; - - if (NULL != pImmutableData->lpFileName) - { - pImmutableDataTarget->lpFileName = strdup(pImmutableData->lpFileName); - } -} - -void -CFileMappingImmutableDataCleanupRoutine( - void *pImmData - ) -{ - CFileMappingImmutableData *pImmutableData = (CFileMappingImmutableData *) pImmData; - - free(pImmutableData->lpFileName); -} - -void -FileMappingCleanupRoutine( - CPalThread *pThread, - IPalObject *pObjectToCleanup, - bool fShutdown - ) -{ - PAL_ERROR palError = NO_ERROR; - CFileMappingImmutableData *pImmutableData = NULL; - CFileMappingProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - bool fDataChanged = FALSE; - - // - // If we created a temporary file to back this mapping we need - // to unlink it now - // - - palError = pObjectToCleanup->GetImmutableData( - reinterpret_cast(&pImmutableData) - ); - - if (NO_ERROR != palError) - { - ASSERT("Unable to obtain immutable data for object to be reclaimed"); - return; - } - - if (pImmutableData->bPALCreatedTempFile) - { - unlink(pImmutableData->lpFileName); - } - - if (FALSE == fShutdown) - { - // - // We only need to close the object's descriptor if we're not - // shutting down - // - - palError = pObjectToCleanup->GetProcessLocalData( - pThread, - WriteLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - ASSERT("Unable to obtain process local data for object to be reclaimed"); - return; - } - - if (-1 != pLocalData->UnixFd) - { - close(pLocalData->UnixFd); - pLocalData->UnixFd = -1; - fDataChanged = TRUE; - } - - pLocalDataLock->ReleaseLock(pThread, fDataChanged); - } - - // - // Why don't we need to deal with any views that may have been created - // from this mapping? If the process is shutting down then there's nothing - // that we need to take care of, as the OS will remove the underlying - // mappings when the process goes away. If we're not shutting down then - // there's no way for a view to exist against this mapping, since each - // view holds a reference against the mapping object. - // -} - -/*++ -Function: - CreateFileMappingW - -Note: - File mapping are used to do inter-process communication. - -See MSDN doc. ---*/ -HANDLE -PALAPI -CreateFileMappingW( - IN HANDLE hFile, - IN LPSECURITY_ATTRIBUTES lpFileMappingAttributes, - IN DWORD flProtect, - IN DWORD dwMaximumSizeHigh, - IN DWORD dwMaximumSizeLow, - IN LPCWSTR lpName) -{ - HANDLE hFileMapping = NULL; - CPalThread *pThread = NULL; - PAL_ERROR palError = NO_ERROR; - - PERF_ENTRY(CreateFileMappingW); - ENTRY("CreateFileMappingW(hFile=%p, lpAttributes=%p, flProtect=%#x, " - "dwMaxSizeH=%u, dwMaxSizeL=%u, lpName=%p (%S))\n", - hFile, lpFileMappingAttributes, flProtect, dwMaximumSizeHigh, - dwMaximumSizeLow, lpName?lpName:W16_NULLSTRING, lpName?lpName:W16_NULLSTRING); - - pThread = InternalGetCurrentThread(); - - palError = InternalCreateFileMapping( - pThread, - hFile, - lpFileMappingAttributes, - flProtect, - dwMaximumSizeHigh, - dwMaximumSizeLow, - lpName, - &hFileMapping - ); - - // - // We always need to set last error, even on success: - // we need to protect ourselves from the situation - // where last error is set to ERROR_ALREADY_EXISTS on - // entry to the function - // - - pThread->SetLastError(palError); - - LOGEXIT( "CreateFileMappingW returning %p .\n", hFileMapping ); - PERF_EXIT(CreateFileMappingW); - return hFileMapping; -} - -PAL_ERROR -CorUnix::InternalCreateFileMapping( - CPalThread *pThread, - HANDLE hFile, - LPSECURITY_ATTRIBUTES lpFileMappingAttributes, - DWORD flProtect, - DWORD dwMaximumSizeHigh, - DWORD dwMaximumSizeLow, - LPCWSTR lpName, - HANDLE *phMapping - ) -{ - CObjectAttributes objectAttributes(lpName, lpFileMappingAttributes); - PAL_ERROR palError = NO_ERROR; - IPalObject *pMapping = NULL; - IPalObject *pRegisteredMapping = NULL; - CFileMappingProcessLocalData *pLocalData = NULL; - IDataLock *pLocalDataLock = NULL; - CFileMappingImmutableData *pImmutableData = NULL; - IPalObject *pFileObject = NULL; - CFileProcessLocalData *pFileLocalData = NULL; - IDataLock *pFileLocalDataLock = NULL; - - struct stat UnixFileInformation; - INT UnixFd = -1; - BOOL bPALCreatedTempFile = FALSE; - UINT nFileSize = 0; - off_t maximumSize; - - // - // Validate parameters - // - - if (lpName != nullptr) - { - ASSERT("lpName: Cross-process named objects are not supported in PAL"); - palError = ERROR_NOT_SUPPORTED; - goto ExitInternalCreateFileMapping; - } - - if (PAGE_READWRITE != flProtect - && PAGE_READONLY != flProtect - && PAGE_WRITECOPY != flProtect) - { - ASSERT( "invalid flProtect %#x, acceptable values are PAGE_READONLY " - "(%#x), PAGE_READWRITE (%#x) and PAGE_WRITECOPY (%#x).\n", - flProtect, PAGE_READONLY, PAGE_READWRITE, PAGE_WRITECOPY ); - palError = ERROR_INVALID_PARAMETER; - goto ExitInternalCreateFileMapping; - } - - if (hFile == INVALID_HANDLE_VALUE && - 0 == dwMaximumSizeLow && 0 == dwMaximumSizeHigh) - { - ERROR( "If hFile is INVALID_HANDLE_VALUE, then you must specify a size.\n" ); - palError = ERROR_INVALID_PARAMETER; - goto ExitInternalCreateFileMapping; - } - - if (hFile != INVALID_HANDLE_VALUE && NULL != lpName) - { - ASSERT( "If hFile is not -1, then lpName must be NULL.\n" ); - palError = ERROR_INVALID_PARAMETER; - goto ExitInternalCreateFileMapping; - } - - maximumSize = ((off_t)dwMaximumSizeHigh << 32) | (off_t)dwMaximumSizeLow; - - palError = g_pObjectManager->AllocateObject( - pThread, - &otFileMapping, - &objectAttributes, - &pMapping - ); - - if (NO_ERROR != palError) - { - goto ExitInternalCreateFileMapping; - } - - palError = pMapping->GetImmutableData(reinterpret_cast(&pImmutableData)); - if (NO_ERROR != palError) - { - goto ExitInternalCreateFileMapping; - } - - if (hFile == INVALID_HANDLE_VALUE -#ifndef CORECLR - && NULL == lpName -#endif // !CORECLR - ) - { - // - // Note: this path is what prevents us supporting the - // duplication of file mapping objects across processes, since - // there is no backing file that the other process can open. We can - // avoid this restriction by always using a temp backing file for - // anonymous mappings. - // - - /* Anonymous mapped files. */ - _ASSERTE(pImmutableData->lpFileName == NULL); - pImmutableData->lpFileName = strdup("/dev/zero"); - if (pImmutableData->lpFileName == NULL) - { - ASSERT("Unable to copy string\n"); - palError = ERROR_INTERNAL_ERROR; - goto ExitInternalCreateFileMapping; - } - - UnixFd = -1; /* will pass MAP_ANON to mmap() instead */ - } - else - { - if ( hFile != INVALID_HANDLE_VALUE ) - { - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFile, - &aotFile, - &pFileObject - ); - - if (NO_ERROR != palError) - { - ERROR("Unable to obtain file data.\n"); - palError = ERROR_INVALID_PARAMETER; - goto ExitInternalCreateFileMapping; - } - - palError = pFileObject->GetProcessLocalData( - pThread, - ReadLock, - &pFileLocalDataLock, - reinterpret_cast(&pFileLocalData) - ); - - if (NO_ERROR != palError) - { - goto ExitInternalCreateFileMapping; - } - - /* We need to check to ensure flProtect jives with - the permission on the file handle */ - if (!MAPIsRequestPermissible(flProtect, pFileLocalData)) - { - ERROR("File handle does not have the correct " - "permissions to create mapping\n" ); - palError = ERROR_ACCESS_DENIED; - if (NULL != pFileLocalDataLock) - { - pFileLocalDataLock->ReleaseLock(pThread, FALSE); - } - goto ExitInternalCreateFileMapping; - } - - // - // TODO: technically, the file mapping object should hold - // a reference to the passed in file object. This implementation - // only keeps the underlying native file structure (i.e., what - // the duplicated descriptors point to) open. There may be a risk - // here pertaining to the file lock information that the PAL must - // maintain (e.g,. if the passed in handle is closed immediately - // after the file mapping is opened then the lock information will - // be released, since we're not doing anything to keep it alive - // here). - // - // Having a direct reference to the underlying file object adds - // some complication, especially in cross-process cases. We may - // want to consider adding a reference to the PAL's file lock - // information, though... - // - -#ifdef TARGET_WASI - // WASI has no dup(); re-open by path with the same access mode - // so writable mappings still work. O_CLOEXEC isn't meaningful - // on WASI (no exec). Handles created by init_std_handle() - // (STDIN/STDOUT/STDERR) have no backing path, so there is nothing - // to re-open; fail gracefully instead of passing NULL to open(). - UnixFd = (pFileLocalData->unix_filename != NULL) - ? open(pFileLocalData->unix_filename, - pFileLocalData->open_flags & O_ACCMODE) - : -1; -#else - UnixFd = fcntl(pFileLocalData->unix_fd, F_DUPFD_CLOEXEC, 0); // dup, but with CLOEXEC -#endif - if (-1 == UnixFd) - { - ERROR( "Unable to duplicate the Unix file descriptor!\n" ); - palError = ERROR_INTERNAL_ERROR; - if (NULL != pFileLocalDataLock) - { - pFileLocalDataLock->ReleaseLock(pThread, FALSE); - } - goto ExitInternalCreateFileMapping; - } - - _ASSERTE(pImmutableData->lpFileName == NULL); - pImmutableData->lpFileName = strdup(pFileLocalData->unix_filename); - if (pImmutableData->lpFileName == NULL) - { - ASSERT("Unable to copy string\n"); - palError = ERROR_INTERNAL_ERROR; - if (NULL != pFileLocalDataLock) - { - pFileLocalDataLock->ReleaseLock(pThread, FALSE); - } - goto ExitInternalCreateFileMapping; - } - - if (NULL != pFileLocalDataLock) - { - pFileLocalDataLock->ReleaseLock(pThread, FALSE); - } - } - else - { -#ifndef CORECLR - TRACE( "INVALID_HANDLE_VALUE was the hFile, time to try to create a " - "temporary file" ); - - /* Create a temporary file on the filesystem in order to be - shared across processes. */ - palError = MAPCreateTempFile(pThread, &UnixFd, pImmutableData->lpFileName); - if (NO_ERROR != palError) - { - ERROR("Unable to create the temporary file.\n"); - goto ExitInternalCreateFileMapping; - } - bPALCreatedTempFile = TRUE; -#else // !CORECLR - ASSERT("should not get here\n"); - palError = ERROR_INTERNAL_ERROR; - goto ExitInternalCreateFileMapping; -#endif // !CORECLR - } - - if (-1 == fstat(UnixFd, &UnixFileInformation)) - { - ASSERT("fstat() failed for this reason %s.\n", strerror(errno)); - palError = ERROR_INTERNAL_ERROR; - goto ExitInternalCreateFileMapping; - } - - if ( 0 == UnixFileInformation.st_size && 0 == maximumSize ) - { - ERROR( "The file cannot be a zero length file.\n" ); - palError = ERROR_FILE_INVALID; - goto ExitInternalCreateFileMapping; - } - - if ( INVALID_HANDLE_VALUE != hFile && - maximumSize > UnixFileInformation.st_size && - ( PAGE_READONLY == flProtect || PAGE_WRITECOPY == flProtect ) ) - { - /* In this situation, Windows returns an error, because the - permissions requested do not allow growing the file */ - ERROR( "The file cannot be grown do to the map's permissions.\n" ); - palError = ERROR_NOT_ENOUGH_MEMORY; - goto ExitInternalCreateFileMapping; - } - - if ( UnixFileInformation.st_size < maximumSize ) - { - TRACE( "Growing the size of file on disk to match requested size.\n" ); - - /* Need to grow the file on disk to match size. */ - palError = MAPGrowLocalFile(UnixFd, maximumSize); - if (NO_ERROR != palError) - { - ERROR( "Unable to grow the file on disk.\n" ); - goto ExitInternalCreateFileMapping; - } - } - } - - nFileSize = ( 0 == maximumSize ) ? - UnixFileInformation.st_size : maximumSize; - - pImmutableData->MaxSize = nFileSize; - pImmutableData->flProtect = flProtect; - pImmutableData->bPALCreatedTempFile = bPALCreatedTempFile; - pImmutableData->dwDesiredAccessWhenOpened = MAPConvertProtectToAccess(flProtect); - - - // - // The local data isn't grabbed / modified until here so that we don't - // need to worry ourselves with locking issues with the passed in - // file handle -- all operations concerning the file handle are completed - // before we deal with the lock for the new object. - // - - palError = pMapping->GetProcessLocalData( - pThread, - WriteLock, - &pLocalDataLock, - reinterpret_cast(&pLocalData) - ); - - if (NO_ERROR != palError) - { - goto ExitInternalCreateFileMapping; - } - - pLocalData->UnixFd = UnixFd; - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - if (-1 == UnixFd) - { - pLocalData->MappedFileDevNum = (dev_t)-1; /* there is no standard NO_DEV */ - pLocalData->MappedFileInodeNum = NO_INO; - } - else - { - struct stat st; - - if (0 == fstat(UnixFd, &st)) - { - pLocalData->MappedFileDevNum = st.st_dev; - pLocalData->MappedFileInodeNum = st.st_ino; - } - else - { - ERROR("Couldn't get inode info for fd=%d to be stored in mapping object\n", UnixFd); - palError = ERROR_INTERNAL_ERROR; - goto ExitInternalCreateFileMapping; - } - } -#endif - - pLocalDataLock->ReleaseLock(pThread, TRUE); - pLocalDataLock = NULL; - - palError = g_pObjectManager->RegisterObject( - pThread, - pMapping, - &aotFileMapping, - phMapping, - &pRegisteredMapping - ); - - // - // pMapping is invalidated by the call to RegisterObject, so NULL it - // out here to ensure that we don't try to release a reference on - // it down the line. This also ensures that we won't attempt to release - // any data associated with the mapping object here, as if any cleanup is - // necessary due to a failure in RegisterObject (which includes another - // object by the same name already existing) the cleanup will take place - // when that routine releases the reference to pMapping. - // - - pMapping = NULL; - -ExitInternalCreateFileMapping: - - if (NULL != pLocalDataLock) - { - pLocalDataLock->ReleaseLock( - pThread, - TRUE - ); - } - - if (NULL != pMapping) - { - pMapping->ReleaseReference(pThread); - - if (bPALCreatedTempFile) - { - unlink(pImmutableData->lpFileName); - } - - if (-1 != UnixFd) - { - close(UnixFd); - } - } - - if (NULL != pRegisteredMapping) - { - pRegisteredMapping->ReleaseReference(pThread); - } - - if (NULL != pFileObject) - { - pFileObject->ReleaseReference(pThread); - } - - return palError; -} - -/*++ -Function: - MapViewOfFile - - Limitations: 1) Currently file mappings are supported only at file - offset 0. - 2) Some platforms (specifically HP-UX) do not support - multiple simultaneous shared mapping of the same file - region in the same process. On these platforms, in case - we are asked for a new view completely contained in an - existing one, we return an address within the existing - mapping. In case the new requested view is overlapping - with the existing one, but not contained in it, the - mapping is impossible, and MapViewOfFile will fail. - Since currently the mappings are supported only at file - offset 0, MapViewOfFile will succeed if the new view - is equal or smaller of the existing one, and the address - returned will be the same address of the existing - mapping. - Since the underlying mapping is always the same, all - the shared views of the same file region will share the - same protection, i.e. they will have the largest - protection requested. If any mapping asked for a - read-write access, all the read-only mappings of the - same region will silently get a read-write access to - it. - -See MSDN doc. ---*/ -LPVOID -PALAPI -MapViewOfFile( - IN HANDLE hFileMappingObject, - IN DWORD dwDesiredAccess, - IN DWORD dwFileOffsetHigh, - IN DWORD dwFileOffsetLow, - IN SIZE_T dwNumberOfBytesToMap) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread = NULL; - LPVOID pvMappedBaseAddress = NULL; - - PERF_ENTRY(MapViewOfFile); - ENTRY("MapViewOfFile(hFileMapping=%p, dwDesiredAccess=%u, " - "dwFileOffsetH=%u, dwFileOffsetL=%u, dwNumberOfBytes=%u)\n", - hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, - dwFileOffsetLow, dwNumberOfBytesToMap); - - pThread = InternalGetCurrentThread(); - - palError = InternalMapViewOfFile( - pThread, - hFileMappingObject, - dwDesiredAccess, - dwFileOffsetHigh, - dwFileOffsetLow, - dwNumberOfBytesToMap, - &pvMappedBaseAddress - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT( "MapViewOfFile returning %p.\n", pvMappedBaseAddress ); - PERF_EXIT(MapViewOfFile); - return pvMappedBaseAddress; -} - -LPVOID -PALAPI -MapViewOfFileEx( - IN HANDLE hFileMappingObject, - IN DWORD dwDesiredAccess, - IN DWORD dwFileOffsetHigh, - IN DWORD dwFileOffsetLow, - IN SIZE_T dwNumberOfBytesToMap, - IN LPVOID lpBaseAddress) -{ - PAL_ERROR palError = NO_ERROR; - CPalThread *pThread = NULL; - LPVOID pvMappedBaseAddress = NULL; - - PERF_ENTRY(MapViewOfFileEx); - ENTRY("MapViewOfFileEx(hFileMapping=%p, dwDesiredAccess=%u, " - "dwFileOffsetH=%u, dwFileOffsetL=%u, dwNumberOfBytes=%u, lpBaseAddress=%p)\n", - hFileMappingObject, dwDesiredAccess, dwFileOffsetHigh, - dwFileOffsetLow, dwNumberOfBytesToMap, lpBaseAddress); - - pThread = InternalGetCurrentThread(); - - if (lpBaseAddress == NULL) - { - palError = InternalMapViewOfFile( - pThread, - hFileMappingObject, - dwDesiredAccess, - dwFileOffsetHigh, - dwFileOffsetLow, - dwNumberOfBytesToMap, - &pvMappedBaseAddress - ); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - } - else - { - // TODO: Figure out if we can support mapping at a specific address on Linux. - pThread->SetLastError(ERROR_INVALID_PARAMETER); - } - - LOGEXIT( "MapViewOfFileEx returning %p.\n", pvMappedBaseAddress ); - PERF_EXIT(MapViewOfFileEx); - return pvMappedBaseAddress; -} - - -/*++ -Function: - UnmapViewOfFile - -See MSDN doc. ---*/ -BOOL -PALAPI -UnmapViewOfFile( - IN LPCVOID lpBaseAddress) noexcept -{ - PAL_ERROR palError; - CPalThread *pThread; - - PERF_ENTRY(UnmapViewOfFile); - ENTRY("UnmapViewOfFile(lpBaseAddress=%p)\n", lpBaseAddress); - - pThread = InternalGetCurrentThread(); - - palError = InternalUnmapViewOfFile(pThread, lpBaseAddress); - - if (NO_ERROR != palError) - { - pThread->SetLastError(palError); - } - - LOGEXIT( "UnmapViewOfFile returning %s.\n", (NO_ERROR == palError) ? "TRUE" : "FALSE" ); - PERF_EXIT(UnmapViewOfFile); - return (NO_ERROR == palError); -} - -PAL_ERROR -CorUnix::InternalMapViewOfFile( - CPalThread *pThread, - HANDLE hFileMappingObject, - DWORD dwDesiredAccess, - DWORD dwFileOffsetHigh, - DWORD dwFileOffsetLow, - SIZE_T dwNumberOfBytesToMap, - LPVOID *ppvBaseAddress - ) -{ - PAL_ERROR palError = NO_ERROR; - IPalObject *pMappingObject = NULL; - CFileMappingImmutableData *pImmutableData = NULL; - CFileMappingProcessLocalData *pProcessLocalData = NULL; - IDataLock *pProcessLocalDataLock = NULL; - INT64 offset = ((INT64)dwFileOffsetHigh << 32) | (INT64)dwFileOffsetLow; - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - PMAPPED_VIEW_LIST pReusedMapping = NULL; -#endif - LPVOID pvBaseAddress = NULL; - - /* Sanity checks */ - if ( MAPContainsInvalidFlags( dwDesiredAccess ) ) - { - ASSERT( "dwDesiredAccess can be one of FILE_MAP_WRITE, FILE_MAP_READ," - " FILE_MAP_COPY or FILE_MAP_ALL_ACCESS.\n" ); - palError = ERROR_INVALID_PARAMETER; - goto InternalMapViewOfFileExit; - } - - if (offset < 0) - { - ASSERT("dwFileOffsetHigh | dwFileOffsetLow should be non-negative.\n"); - palError = ERROR_INVALID_PARAMETER; - goto InternalMapViewOfFileExit; - } - - palError = g_pObjectManager->ReferenceObjectByHandle( - pThread, - hFileMappingObject, - &aotFileMapping, - &pMappingObject - ); - - if (NO_ERROR != palError) - { - ERROR( "Unable to reference handle %p.\n",hFileMappingObject ); - goto InternalMapViewOfFileExit; - } - - palError = pMappingObject->GetImmutableData( - reinterpret_cast(&pImmutableData) - ); - - if (NO_ERROR != palError) - { - ERROR( "Unable to obtain object immutable data"); - goto InternalMapViewOfFileExit; - } - - palError = pMappingObject->GetProcessLocalData( - pThread, - ReadLock, - &pProcessLocalDataLock, - reinterpret_cast(&pProcessLocalData) - ); - - if (NO_ERROR != palError) - { - ERROR( "Unable to obtain object process local data"); - goto InternalMapViewOfFileExit; - } - - /* If dwNumberOfBytesToMap is 0, we need to map the entire file. - * mmap doesn't do the same thing as Windows in that case, though, - * so we use the file size instead. */ - if (0 == dwNumberOfBytesToMap) - { - dwNumberOfBytesToMap = pImmutableData->MaxSize; - } - - palError = MAPDesiredAccessAllowed( - pImmutableData->flProtect, - dwDesiredAccess, - pImmutableData->dwDesiredAccessWhenOpened - ); - - if (NO_ERROR != palError) - { - goto InternalMapViewOfFileExit; - } - - minipal_mutex_enter(&mapping_critsec); - - if (FILE_MAP_COPY == dwDesiredAccess) - { - int flags = MAP_PRIVATE; - if (pProcessLocalData->UnixFd == -1) - { - flags |= MAP_ANON; - } - - pvBaseAddress = mmap( - NULL, - dwNumberOfBytesToMap, - PROT_READ|PROT_WRITE, - flags, - pProcessLocalData->UnixFd, - offset - ); - } - else - { - INT prot = MAPFileMapToMmapFlags(dwDesiredAccess); - if (prot != -1) - { - int flags = MAP_SHARED; - if (pProcessLocalData->UnixFd == -1) - { - flags |= MAP_ANON; - } - - pvBaseAddress = mmap( - NULL, - dwNumberOfBytesToMap, - prot, - flags, - pProcessLocalData->UnixFd, - offset - ); - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - if ((MAP_FAILED == pvBaseAddress) && (ENOMEM == errno)) - { - /* Search in list of MAPPED_MEMORY_INFO for a shared mapping - with the same inode number - */ - TRACE("Mmap() failed with errno=ENOMEM probably for multiple mapping " - "limitation. Searching for a replacement among existing mappings\n"); - - pReusedMapping = FindSharedMappingReplacement( - pThread, - pProcessLocalData->MappedFileDevNum, - pProcessLocalData->MappedFileInodeNum, - dwNumberOfBytesToMap, - 0 - ); - - if (pReusedMapping) - { - int ret; - - TRACE("Mapping @ %p {sz=%d offs=%d} fully " - "contains the requested one {sz=%d offs=%d}: reusing it\n", - pReusedMapping->pNMHolder->address, - (int)pReusedMapping->pNMHolder->size, - (int)pReusedMapping->pNMHolder->offset, - dwNumberOfBytesToMap, 0); - - /* Let's check the mapping's current protection */ - ret = mprotect(pReusedMapping->pNMHolder->address, - pReusedMapping->pNMHolder->size, - prot | PROT_CHECK); - if (0 != ret) - { - /* We need to raise the protection to the desired - one. That will give write access to any read-only - mapping sharing this native mapping, but there is - no way around this problem on systems that do not - allow more than one mapping per file region, per - process */ - TRACE("Raising protections on mapping @ %p to 0x%x\n", - pReusedMapping->pNMHolder->address, prot); - ret = mprotect(pReusedMapping->pNMHolder->address, - pReusedMapping->pNMHolder->size, - prot); - } - - if (ret != 0) - { - ERROR( "Failed setting protections on reused mapping\n"); - - NativeMapHolderRelease(pThread, pReusedMapping->pNMHolder); - free(pReusedMapping); - pReusedMapping = NULL; - } - } - } -#endif // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - } - else - { - ASSERT( "MapFileMapToMmapFlags failed!\n" ); - palError = ERROR_INTERNAL_ERROR; - goto InternalMapViewOfFileLeaveCriticalSection; - } - } - - if (MAP_FAILED == pvBaseAddress -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - && (pReusedMapping == NULL) -#endif // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - ) - { - ERROR( "mmap failed with code %s.\n", strerror( errno ) ); - palError = ERROR_NOT_ENOUGH_MEMORY; - goto InternalMapViewOfFileLeaveCriticalSection; - - } - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - if (pReusedMapping != NULL) - { - // - // Add a reference to the file mapping object the reused mapping - // points to (note that it may be different than the object this - // call was actually made against) and add the view to the global - // list. All other initialization took place in - // FindSharedMappingReplacement - // - - pvBaseAddress = pReusedMapping->lpAddress; - pReusedMapping->pFileMapping->AddReference(); - InsertTailList(&MappedViewList, &pReusedMapping->Link); - } - else -#endif // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - { - // - // Allocate and fill out a new view structure, and add it to - // the global list. - // - - PMAPPED_VIEW_LIST pNewView = (PMAPPED_VIEW_LIST)malloc(sizeof(*pNewView)); - if (NULL != pNewView) - { - pNewView->lpAddress = pvBaseAddress; - pNewView->NumberOfBytesToMap = dwNumberOfBytesToMap; - pNewView->dwDesiredAccess = dwDesiredAccess; - pNewView->pFileMapping = pMappingObject; - pNewView->pFileMapping->AddReference(); - InsertTailList(&MappedViewList, &pNewView->Link); - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - pNewView->MappedFileDevNum = pProcessLocalData->MappedFileDevNum; - pNewView->MappedFileInodeNum = pProcessLocalData->MappedFileInodeNum; - - pNewView->pNMHolder = NewNativeMapHolder( - pThread, - pvBaseAddress, - dwNumberOfBytesToMap, - 0, - 1 - ); - - if (NULL == pNewView->pNMHolder) - { - pNewView->pFileMapping->ReleaseReference(pThread); - RemoveEntryList(&pNewView->Link); - free(pNewView); - palError = ERROR_INTERNAL_ERROR; - } -#endif // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - } - else - { - palError = ERROR_INTERNAL_ERROR; - } - - if (NO_ERROR != palError) - { - if (-1 == munmap(pvBaseAddress, dwNumberOfBytesToMap)) - { - ERROR("Unable to unmap the file. Expect trouble.\n"); - goto InternalMapViewOfFileLeaveCriticalSection; - } - } - } - - if (NO_ERROR == palError) - { - TRACE( "Added %p to the list.\n", pvBaseAddress ); - *ppvBaseAddress = pvBaseAddress; - } - -InternalMapViewOfFileLeaveCriticalSection: - - minipal_mutex_leave(&mapping_critsec); - -InternalMapViewOfFileExit: - - if (NULL != pProcessLocalDataLock) - { - pProcessLocalDataLock->ReleaseLock(pThread, FALSE); - } - - if (NULL != pMappingObject) - { - pMappingObject->ReleaseReference(pThread); - } - - return palError; -} - - -PAL_ERROR -CorUnix::InternalUnmapViewOfFile( - CPalThread *pThread, - LPCVOID lpBaseAddress - ) -{ - PAL_ERROR palError = NO_ERROR; - PMAPPED_VIEW_LIST pView = NULL; - IPalObject *pMappingObject = NULL; - - minipal_mutex_enter(&mapping_critsec); - - pView = MAPGetViewForAddress(lpBaseAddress); - if (NULL == pView) - { - ERROR("lpBaseAddress has to be the address returned by MapViewOfFile[Ex]"); - palError = ERROR_INVALID_HANDLE; - goto InternalUnmapViewOfFileExit; - } - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - NativeMapHolderRelease(pThread, pView->pNMHolder); - pView->pNMHolder = NULL; -#else - if (-1 == munmap((LPVOID)lpBaseAddress, pView->NumberOfBytesToMap)) - { - ASSERT( "Unable to unmap the memory. Error=%s.\n", - strerror( errno ) ); - palError = ERROR_INTERNAL_ERROR; - - // - // Even if the unmap fails we want to continue removing the - // info for this view - // - } -#endif - - RemoveEntryList(&pView->Link); - pMappingObject = pView->pFileMapping; - free(pView); - -InternalUnmapViewOfFileExit: - - minipal_mutex_leave(&mapping_critsec); - - // - // We can't dereference the file mapping object until after - // we've released the mapping critical section, since it may - // start going down its cleanup path and we don't want to make - // any assumptions as to what locks that might grab... - // - - if (NULL != pMappingObject) - { - pMappingObject->ReleaseReference(pThread); - } - - return palError; -} - -/*++ -Function : - MAPInitialize - - Initialize the critical sections. - -Return value: - TRUE if initialization succeeded - FALSE otherwise ---*/ -BOOL -MAPInitialize( void ) -{ - TRACE( "Initialising the critical section.\n" ); - - minipal_mutex_init(&mapping_critsec); - - InitializeListHead(&MappedViewList); - - return TRUE; -} - -/*++ -Function : - MAPCleanup - - Deletes the critical sections. And all other necessary cleanup. - -Note: - This function is called after the handle manager is stopped. So - there shouldn't be any call that will cause an access to the handle - manager. - ---*/ -void MAPCleanup( void ) -{ - TRACE( "Deleting the critical section.\n" ); - minipal_mutex_destroy(&mapping_critsec); -} - -/*++ -Function : - MAPGetViewForAddress - - Returns the mapped view (if any) that is based at the passed in address. - - Callers to this function must hold mapping_critsec ---*/ -static PMAPPED_VIEW_LIST MAPGetViewForAddress( LPCVOID lpAddress ) -{ - if ( NULL == lpAddress ) - { - ERROR( "lpAddress cannot be NULL\n" ); - return NULL; - } - - for(LIST_ENTRY *pLink = MappedViewList.Flink; - pLink != &MappedViewList; - pLink = pLink->Flink) - { - PMAPPED_VIEW_LIST pView = CONTAINING_RECORD(pLink, MAPPED_VIEW_LIST, Link); - - if (pView->lpAddress == lpAddress) - { - return pView; - } - } - - WARN( "No match found.\n" ); - - return NULL; -} - -/*++ -Function : - - MAPDesiredAccessAllowed - - Determines if desired access is allowed based on the protection state. - - if dwDesiredAccess conflicts with flProtect then the error is - ERROR_INVALID_PARAMETER, if the dwDesiredAccess conflicts with - dwDesiredAccessWhenOpened, then the error code is ERROR_ACCESS_DENIED ---*/ -static PAL_ERROR MAPDesiredAccessAllowed( DWORD flProtect, - DWORD dwUserDesiredAccess, - DWORD dwDesiredAccessWhenOpened ) -{ - TRACE( "flProtect=%d, dwUserDesiredAccess=%d, dwDesiredAccessWhenOpened=%d\n", - flProtect, dwUserDesiredAccess, dwDesiredAccessWhenOpened ); - - /* check flProtect parameters*/ - if ( FILE_MAP_READ!= dwUserDesiredAccess && PAGE_READONLY == flProtect ) - { - ERROR( "map object is read-only, can't map a view with write access\n"); - return ERROR_INVALID_PARAMETER; - } - - if ( FILE_MAP_WRITE == dwUserDesiredAccess && PAGE_READWRITE != flProtect ) - { - ERROR( "map object not open read-write, can't map a view with write " - "access.\n" ); - return ERROR_INVALID_PARAMETER; - } - - if ( FILE_MAP_COPY == dwUserDesiredAccess && PAGE_WRITECOPY != flProtect ) - { - ERROR( "map object not open for copy-on-write, can't map copy-on-write " - "view.\n" ); - return ERROR_INVALID_PARAMETER; - } - - /* Check to see we don't confict with the desired access we - opened the mapping object with. */ - if ( ( dwUserDesiredAccess == FILE_MAP_READ ) && - !( ( dwDesiredAccessWhenOpened == FILE_MAP_READ ) || - ( dwDesiredAccessWhenOpened == FILE_MAP_ALL_ACCESS ) ) ) - { - ERROR( "dwDesiredAccess conflict : read access requested, object not " - "opened with read access.\n" ); - return ERROR_ACCESS_DENIED; - } - if ( ( dwUserDesiredAccess & FILE_MAP_WRITE ) && - !( ( dwDesiredAccessWhenOpened == FILE_MAP_WRITE ) || - ( dwDesiredAccessWhenOpened == FILE_MAP_ALL_ACCESS ) ) ) - { - ERROR( "dwDesiredAccess conflict : write access requested, object not " - "opened with write access.\n" ); - return ERROR_ACCESS_DENIED; - } - if ( ( dwUserDesiredAccess == FILE_MAP_COPY ) && - !( dwDesiredAccessWhenOpened == FILE_MAP_COPY ) ) - { - ERROR( "dwDesiredAccess conflict : copy-on-write access requested, " - "object not opened with copy-on-write access.\n" ); - return ERROR_ACCESS_DENIED; - } - - return NO_ERROR; -} - -/*++ -Function : - MAPConvertProtectToAccess - - Converts the PAGE_READONLY type flags to FILE_MAP_READ flags. - ---*/ -static DWORD MAPConvertProtectToAccess( DWORD flProtect ) -{ - if ( PAGE_READONLY == flProtect ) - { - return FILE_MAP_READ; - } - if ( PAGE_READWRITE == flProtect ) - { - return FILE_MAP_ALL_ACCESS; - } - if ( PAGE_WRITECOPY == flProtect ) - { - return FILE_MAP_COPY; - } - - ASSERT( "Unknown flag for flProtect. This line " - "should not have been executed.\n " ); - return (DWORD) -1; -} - -/*++ -Function : - MAPFileMapToMmapFlags - - Converts the mapping flags to unix protection flags. ---*/ -static INT MAPFileMapToMmapFlags( DWORD flags ) -{ - if ( FILE_MAP_READ == flags ) - { - TRACE( "FILE_MAP_READ\n" ); - return PROT_READ; - } - else if ( FILE_MAP_WRITE == flags ) - { - TRACE( "FILE_MAP_WRITE\n" ); - /* The limitation of x86 architecture - means you cant have writable but not readable - page. In Windows maps of FILE_MAP_WRITE can still be - read from. */ - return PROT_WRITE | PROT_READ; - } - else if ( (FILE_MAP_READ|FILE_MAP_WRITE) == flags ) - { - TRACE( "FILE_MAP_READ|FILE_MAP_WRITE\n" ); - return PROT_READ | PROT_WRITE; - } - else if( FILE_MAP_COPY == flags) - { - TRACE( "FILE_MAP_COPY\n"); - return PROT_READ | PROT_WRITE; - } - - ASSERT( "Unknown flag. This line should not have been executed.\n" ); - return -1; -} - -/*++ -Function : - - MAPGrowLocalFile - - Grows the file on disk to match the specified size. - ---*/ -static PAL_ERROR MAPGrowLocalFile( INT UnixFD, off_t NewSize ) -{ - PAL_ERROR palError = NO_ERROR; - INT TruncateRetVal = -1; - struct stat FileInfo; - TRACE( "Entered MapGrowLocalFile (UnixFD=%d,NewSize%d)\n", UnixFD, NewSize ); - - // - // TODO: can we add configure flags to model the behavior of ftruncate - // among our various target platforms? How much would that actually gain - // us? - // - - /* ftruncate is a standard function, but the behavior of enlarging files is - non-standard. So I will try to enlarge a file, and if that fails try the - less efficient way.*/ - TruncateRetVal = ftruncate( UnixFD, NewSize ); - fstat( UnixFD, &FileInfo ); - - if ( TruncateRetVal != 0 || FileInfo.st_size != NewSize ) - { - INT OrigSize; - CONST UINT BUFFER_SIZE = 128; - BYTE buf[BUFFER_SIZE]; - UINT x = 0; - UINT CurrentPosition = 0; - - TRACE( "Trying the less efficient way.\n" ); - - CurrentPosition = lseek( UnixFD, 0, SEEK_CUR ); - OrigSize = lseek( UnixFD, 0, SEEK_END ); - if ( OrigSize == -1 ) - { - ERROR( "Unable to locate the EOF marker. Reason=%s\n", - strerror( errno ) ); - palError = ERROR_INTERNAL_ERROR; - goto done; - } - - if (NewSize <= (UINT) OrigSize) - { - return TRUE; - } - - memset( buf, 0, BUFFER_SIZE ); - if (NewSize - OrigSize - BUFFER_SIZE >= 0 && BUFFER_SIZE > 0) - { - for ( x = 0; x < NewSize - OrigSize - BUFFER_SIZE; x += BUFFER_SIZE ) - { - if ( write( UnixFD, (LPVOID)buf, BUFFER_SIZE ) == -1 ) - { - ERROR( "Unable to grow the file. Reason=%s\n", strerror( errno ) ); - if((errno == ENOSPC) || (errno == EDQUOT)) - { - palError = ERROR_DISK_FULL; - } - else - { - palError = ERROR_INTERNAL_ERROR; - } - goto done; - } - } - } - else - { - //This will be an infinite loop because it did not pass the check. - palError = ERROR_INTERNAL_ERROR; - goto done; - } - /* Catch any left overs. */ - if ( x != NewSize ) - { - if ( write( UnixFD, (LPVOID)buf, NewSize - OrigSize - x) == -1 ) - { - ERROR( "Unable to grow the file. Reason=%s\n", strerror( errno ) ); - if((errno == ENOSPC) || (errno == EDQUOT)) - { - palError = ERROR_DISK_FULL; - } - else - { - palError = ERROR_INTERNAL_ERROR; - } - goto done; - } - } - - /* restore the file pointer position */ - lseek( UnixFD, CurrentPosition, SEEK_SET ); - } - -done: - return palError; -} - -/*++ -Function : - MAPContainsInvalidFlags - - Checks that only valid flags are in the parameter. - ---*/ -static BOOL MAPContainsInvalidFlags( DWORD flags ) -{ - - if ( (flags == FILE_MAP_READ) || - (flags == FILE_MAP_WRITE) || - (flags == FILE_MAP_ALL_ACCESS) || - (flags == FILE_MAP_COPY) ) - { - return FALSE; - } - else - { - return TRUE; - } -} - -/*++ -Function : - MAPProtectionToFileOpenFlags - - Converts the PAGE_* flags to the O_* flags. - - Returns the file open flags. ---*/ -static INT MAPProtectionToFileOpenFlags( DWORD flProtect ) -{ - INT retVal = 0; - switch(flProtect) - { - case PAGE_READONLY: - retVal = O_RDONLY; - break; - case PAGE_READWRITE: - retVal = O_RDWR; - break; - case PAGE_WRITECOPY: - retVal = O_RDONLY; - break; - default: - ASSERT("unexpected flProtect value %#x\n", flProtect); - retVal = 0; - break; - } - return retVal; -} - -/*++ -Function : - - MAPIsRequestPermissible - - DWORD flProtect - The requested file mapping protection . - file * pFileStruct - The file structure containing all the information. - ---*/ -static BOOL MAPIsRequestPermissible( DWORD flProtect, CFileProcessLocalData * pFileLocalData ) -{ - if ( ( (flProtect == PAGE_READONLY || flProtect == PAGE_WRITECOPY) && - (pFileLocalData->open_flags_deviceaccessonly == TRUE || - pFileLocalData->open_flags & O_WRONLY) ) - ) - { - /* - * PAGE_READONLY or PAGE_WRITECOPY access to a file must at least be - * readable. Contrary to what MSDN says, PAGE_WRITECOPY - * only needs to be readable. - */ - return FALSE; - } - else if ( flProtect == PAGE_READWRITE && !(pFileLocalData->open_flags & O_RDWR) ) - { - /* - * PAGE_READWRITE access to a file needs to be readable and writable - */ - return FALSE; - } - else - { - /* Action is permissible */ - return TRUE; - } -} - -#if ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS - -// -// Callers of FindSharedMappingReplacement must hold mapping_critsec -// - -static PMAPPED_VIEW_LIST FindSharedMappingReplacement( - CPalThread *pThread, - dev_t deviceNum, - ino_t inodeNum, - SIZE_T size, - SIZE_T offset) -{ - PMAPPED_VIEW_LIST pNewView = NULL; - - if (size == 0) - { - ERROR("Mapping size cannot be NULL\n"); - return NULL; - } - - for (LIST_ENTRY *pLink = MappedViewList.Flink; - pLink != &MappedViewList; - pLink = pLink->Flink) - { - PMAPPED_VIEW_LIST pView = CONTAINING_RECORD(pLink, MAPPED_VIEW_LIST, Link); - - if (pView->MappedFileDevNum != deviceNum - || pView->MappedFileInodeNum != inodeNum - || pView->dwDesiredAccess == FILE_MAP_COPY) - { - continue; - } - - // - // This is a shared mapping for the same indoe / device. Now, check - // to see if it overlaps with the range for the new view - // - - SIZE_T real_map_offs = pView->pNMHolder->offset; - SIZE_T real_map_sz = pView->pNMHolder->size; - - if (real_map_offs <= offset - && real_map_offs+real_map_sz >= offset) - { - // - // The views overlap. Even if this view is not reusable for the - // new once the search is over, as on - // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS systems there - // cannot be shared mappings of two overlapping regions of the - // same file, in the same process. Therefore, whether this view - // is reusable or not we cannot mmap the requested region of - // the specified file. - // - - if (real_map_offs+real_map_sz >= offset+size) - { - /* The new desired mapping is fully contained in the - one just found: we can reuse this one */ - - pNewView = (PMAPPED_VIEW_LIST)malloc(sizeof(MAPPED_VIEW_LIST)); - if (pNewView) - { - memcpy(pNewView, pView, sizeof(*pNewView)); - NativeMapHolderAddRef(pNewView->pNMHolder); - pNewView->lpAddress = (VOID*)((CHAR*)pNewView->pNMHolder->address + - offset - pNewView->pNMHolder->offset); - pNewView->NumberOfBytesToMap = size; - } - else - { - ERROR("No memory for new MAPPED_VIEW_LIST node\n"); - } - } - - break; - } - } - - TRACE ("FindSharedMappingReplacement returning %p\n", pNewView); - return pNewView; -} - -static NativeMapHolder * NewNativeMapHolder(CPalThread *pThread, LPVOID address, SIZE_T size, - SIZE_T offset, long init_ref_count) -{ - NativeMapHolder * pThisMapHolder; - - if (init_ref_count < 0) - { - ASSERT("Negative initial reference count for new map holder\n"); - return NULL; - } - - pThisMapHolder = - (NativeMapHolder *)malloc(sizeof(NativeMapHolder)); - - if (pThisMapHolder) - { - pThisMapHolder->ref_count = init_ref_count; - pThisMapHolder->address = address; - pThisMapHolder->size = size; - pThisMapHolder->offset = offset; - } - - return pThisMapHolder; -} - -static LONG NativeMapHolderAddRef(NativeMapHolder * thisNMH) -{ - LONG ret = InterlockedIncrement(&thisNMH->ref_count); - return ret; -} - -static LONG NativeMapHolderRelease(CPalThread *pThread, NativeMapHolder * thisNMH) -{ - LONG ret = InterlockedDecrement(&thisNMH->ref_count); - if (ret == 0) - { - if (-1 == munmap(thisNMH->address, thisNMH->size)) - { - ASSERT( "Unable to unmap memory. Error=%s.\n", - strerror( errno ) ); - } - else - { - TRACE( "Successfully unmapped %p (size=%lu)\n", - thisNMH->address, (unsigned long)thisNMH->size); - } - free (thisNMH); - } - else if (ret < 0) - { - ASSERT( "Negative reference count for map holder %p" - " {address=%p, size=%lu}\n", thisNMH->address, - (unsigned long)thisNMH->size); - } - - return ret; -} - -#endif // ONE_SHARED_MAPPING_PER_FILEREGION_PER_PROCESS diff --git a/src/coreclr/pal/src/misc/dbgmsg.cpp b/src/coreclr/pal/src/misc/dbgmsg.cpp index 8ec68fb5530a85..0b3c0181bc4839 100644 --- a/src/coreclr/pal/src/misc/dbgmsg.cpp +++ b/src/coreclr/pal/src/misc/dbgmsg.cpp @@ -13,12 +13,10 @@ Module Name: /* PAL headers */ #include "pal/thread.hpp" -#include "pal/file.hpp" #include "config.h" #include "pal/dbgmsg.h" #include "pal/cruntime.h" -#include "pal/file.h" #include "pal/environ.h" /* standard headers */ diff --git a/src/coreclr/pal/src/misc/tracepointprovider.cpp b/src/coreclr/pal/src/misc/tracepointprovider.cpp index dae1e0f73170c3..d15e296b2f5527 100644 --- a/src/coreclr/pal/src/misc/tracepointprovider.cpp +++ b/src/coreclr/pal/src/misc/tracepointprovider.cpp @@ -17,7 +17,6 @@ Revision History: #include "pal/palinternal.h" #include "pal/dbgmsg.h" -#include "pal/file.h" #include "pal/process.h" #include "pal/module.h" #include "pal/stackstring.hpp" diff --git a/src/coreclr/pal/src/misc/utils.cpp b/src/coreclr/pal/src/misc/utils.cpp index fb5b2273cb7fae..c9f5ba80a78d9b 100644 --- a/src/coreclr/pal/src/misc/utils.cpp +++ b/src/coreclr/pal/src/misc/utils.cpp @@ -23,7 +23,6 @@ SET_DEFAULT_DEBUG_CHANNEL(MISC); // some headers have code with asserts, so do t #endif //HAVE_VM_ALLOCATE #include "pal/utils.h" -#include "pal/file.h" #include #include @@ -130,7 +129,7 @@ LPWSTR UTIL_MBToWC_Alloc(LPCSTR lpMultiByteStr, int cbMultiByte) if(NULL == lpWideCharStr) { ERROR("malloc() failed! errno is %d (%s)\n", errno,strerror(errno)); - SetLastError(FILEGetLastErrorFromErrno()); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); return NULL; } diff --git a/src/coreclr/pal/src/thread/process.cpp b/src/coreclr/pal/src/thread/process.cpp index 05f5600db7b5ec..76cb1a6e38e2ee 100644 --- a/src/coreclr/pal/src/thread/process.cpp +++ b/src/coreclr/pal/src/thread/process.cpp @@ -14,7 +14,6 @@ SET_DEFAULT_DEBUG_CHANNEL(PROCESS); // some headers have code with asserts, so d #include "pal/procobj.hpp" #include "pal/thread.hpp" -#include "pal/file.hpp" #include "pal/handlemgr.hpp" #include "pal/module.h" #include "procprivate.hpp" @@ -572,6 +571,14 @@ static uint64_t HashSemaphoreName(uint64_t a, uint64_t b) static const char *const TwoWayNamedPipePrefix = "clr-debug-pipe"; static const char* IpcNameFormat = "%s-%d-%llu-%s"; +#ifndef __ANDROID__ +#define TEMP_DIRECTORY_PATH "/tmp/" +#else +// On Android, "/tmp/" doesn't exist; temporary files should go to +// /data/local/tmp/ +#define TEMP_DIRECTORY_PATH "/data/local/tmp/" +#endif + #ifdef ENABLE_RUNTIME_EVENTS_OVER_PIPES static const char* RuntimeStartupPipeName = "st"; static const char* RuntimeContinuePipeName = "co"; @@ -1152,7 +1159,6 @@ PAL_GetTransportName( IN const char *suffix) { *name = '\0'; - DWORD dwRetVal = 0; UINT64 disambiguationKey = 0; PathCharString formatBufferString; BOOL ret = GetProcessIdDisambiguationKey(id, &disambiguationKey); @@ -1179,7 +1185,7 @@ PAL_GetTransportName( } // In sandbox, all IPC files (locks, pipes) should be written to the application group - // container. The path returned by GetTempPathA will be unique for each process and cannot + // container. $TMPDIR will be unique for each process and cannot // be used for IPC between two different processes if (!GetApplicationContainerFolder(formatBufferString, applicationGroupId, applicationGroupIdLength)) { @@ -1197,16 +1203,18 @@ PAL_GetTransportName( else #endif // __APPLE__ { - // Get a temp file location - dwRetVal = ::GetTempPathA(MAX_TRANSPORT_NAME_LENGTH, formatBuffer); - if (dwRetVal == 0) + // Must match the out-of-process clients that compute the same names (Path.GetTempPath() rules). + const char* tmpDir = getenv("TMPDIR"); + if (tmpDir == nullptr || tmpDir[0] == '\0') { - ERROR("GetTempPath failed (0x%08x)", ::GetLastError()); - return; + tmpDir = TEMP_DIRECTORY_PATH; } - if (dwRetVal > MAX_TRANSPORT_NAME_LENGTH) + + const char* slash = (tmpDir[strlen(tmpDir) - 1] == '/') ? "" : "/"; + int len = snprintf(formatBuffer, MAX_TRANSPORT_NAME_LENGTH, "%s%s", tmpDir, slash); + if (len < 0 || (unsigned int)len >= MAX_TRANSPORT_NAME_LENGTH) { - ERROR("GetTempPath returned a path that was larger than MAX_TRANSPORT_NAME_LENGTH"); + ERROR("TMPDIR is longer than MAX_TRANSPORT_NAME_LENGTH"); return; } } diff --git a/src/coreclr/pal/tests/palsuite/CMakeLists.txt b/src/coreclr/pal/tests/palsuite/CMakeLists.txt index 28537e7882fdaa..e1362b3e39a900 100644 --- a/src/coreclr/pal/tests/palsuite/CMakeLists.txt +++ b/src/coreclr/pal/tests/palsuite/CMakeLists.txt @@ -153,16 +153,6 @@ add_executable_clr(paltests exception_handling/RaiseException/test1/test1.cpp exception_handling/RaiseException/test2/test2.cpp exception_handling/RaiseException/test3/test.cpp - filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/CreateFileMapping_neg.cpp - filemapping_memmgt/CreateFileMappingW/test1/CreateFileMappingW.cpp - #filemapping_memmgt/CreateFileMappingW/test2/CreateFileMappingW.cpp - filemapping_memmgt/CreateFileMappingW/test3/CreateFileMappingW.cpp - filemapping_memmgt/CreateFileMappingW/test4/CreateFileMappingW.cpp - filemapping_memmgt/CreateFileMappingW/test5/CreateFileMappingW.cpp - filemapping_memmgt/CreateFileMappingW/test6/CreateFileMappingW.cpp - filemapping_memmgt/CreateFileMappingW/test7/createfilemapping.cpp - filemapping_memmgt/CreateFileMappingW/test8/createfilemapping.cpp - filemapping_memmgt/CreateFileMappingW/test9/createfilemapping.cpp # filemapping_memmgt/FreeLibrary/test1/dlltest.cpp filemapping_memmgt/FreeLibrary/test1/FreeLibrary.cpp filemapping_memmgt/FreeLibrary/test2/test2.cpp @@ -174,50 +164,8 @@ add_executable_clr(paltests # filemapping_memmgt/GetProcAddress/test1/testlib.cpp filemapping_memmgt/GetProcAddress/test2/test2.cpp # filemapping_memmgt/GetProcAddress/test2/testlib.cpp - filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp - filemapping_memmgt/MapViewOfFile/test3/MapViewOfFile.cpp - filemapping_memmgt/MapViewOfFile/test4/mapviewoffile.cpp - filemapping_memmgt/MapViewOfFile/test5/mapviewoffile.cpp - filemapping_memmgt/MapViewOfFile/test6/mapviewoffile.cpp filemapping_memmgt/ProbeMemory/ProbeMemory_neg1/ProbeMemory_neg.cpp filemapping_memmgt/ProbeMemory/test1/ProbeMemory.cpp - filemapping_memmgt/UnmapViewOfFile/test1/UnmapViewOfFile.cpp - filemapping_memmgt/UnmapViewOfFile/test2/unmapviewoffile.cpp - file_io/CreateFileA/test1/CreateFileA.cpp - file_io/CreateFileW/test1/CreateFileW.cpp - file_io/errorpathnotfound/test1/test1.cpp - file_io/FILECanonicalizePath/FILECanonicalizePath.cpp - file_io/FlushFileBuffers/test1/FlushFileBuffers.cpp - file_io/GetFileSize/test1/GetFileSize.cpp - file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp - file_io/GetFullPathNameA/test1/GetFullPathNameA.cpp - file_io/GetFullPathNameA/test2/test2.cpp - file_io/GetFullPathNameA/test3/test3.cpp - file_io/GetFullPathNameA/test4/test4.cpp - file_io/GetFullPathNameW/test1/GetFullPathNameW.cpp - file_io/GetFullPathNameW/test2/test2.cpp - file_io/GetFullPathNameW/test3/test3.cpp - file_io/GetFullPathNameW/test4/test4.cpp - file_io/GetStdHandle/test1/GetStdHandle.cpp - file_io/GetStdHandle/test2/GetStdHandle.cpp - file_io/gettemppatha/test1/gettemppatha.cpp - file_io/ReadFile/test1/ReadFile.cpp - file_io/ReadFile/test2/ReadFile.cpp - file_io/ReadFile/test3/ReadFile.cpp - file_io/ReadFile/test4/readfile.cpp - file_io/SearchPathW/test1/SearchPathW.cpp - file_io/SetFilePointer/test1/SetFilePointer.cpp - file_io/SetFilePointer/test2/SetFilePointer.cpp - file_io/SetFilePointer/test3/SetFilePointer.cpp - file_io/SetFilePointer/test4/SetFilePointer.cpp - file_io/SetFilePointer/test5/SetFilePointer.cpp - file_io/SetFilePointer/test6/SetFilePointer.cpp - file_io/SetFilePointer/test7/SetFilePointer.cpp - file_io/WriteFile/test1/WriteFile.cpp - file_io/WriteFile/test2/WriteFile.cpp - file_io/WriteFile/test3/WriteFile.cpp - file_io/WriteFile/test4/writefile.cpp - file_io/WriteFile/test5/writefile.cpp loader/LoadLibraryA/test1/LoadLibraryA.cpp loader/LoadLibraryA/test2/LoadLibraryA.cpp loader/LoadLibraryA/test3/loadlibrarya.cpp @@ -244,7 +192,6 @@ add_executable_clr(paltests locale_info/WideCharToMultiByte/test3/test3.cpp locale_info/WideCharToMultiByte/test4/test4.cpp locale_info/WideCharToMultiByte/test5/test5.cpp - miscellaneous/CloseHandle/test1/test.cpp miscellaneous/CloseHandle/test2/test.cpp miscellaneous/FlushInstructionCache/test1/test1.cpp miscellaneous/FormatMessageW/test1/test.cpp @@ -310,8 +257,6 @@ add_executable_clr(paltests threading/CreateThread/test1/test1.cpp threading/CreateThread/test2/test2.cpp threading/CreateThread/test3/test3.cpp - threading/DuplicateHandle/test1/test1.cpp - threading/DuplicateHandle/test12/test12.cpp threading/DuplicateHandle/test7/test7.cpp threading/DuplicateHandle/test8/test8.cpp # threading/DuplicateHandle/test9/test9.cpp diff --git a/src/coreclr/pal/tests/palsuite/DisabledTests.txt b/src/coreclr/pal/tests/palsuite/DisabledTests.txt index 83b9bcc843cabf..6b665948ce27e1 100644 --- a/src/coreclr/pal/tests/palsuite/DisabledTests.txt +++ b/src/coreclr/pal/tests/palsuite/DisabledTests.txt @@ -31,6 +31,5 @@ pal_specific/pal_get_stdin/test1 : ======================================= This test case should be run manually. Requires user input. -filemapping_memmgt\MapViewOfFile\test1 ======================================= Refer this github issue https://github.com/dotnet/runtime/issues/5924 diff --git a/src/coreclr/pal/tests/palsuite/common/palsuite.cpp b/src/coreclr/pal/tests/palsuite/common/palsuite.cpp index 6d05884b5c28ee..1b5f826dd8d9f9 100644 --- a/src/coreclr/pal/tests/palsuite/common/palsuite.cpp +++ b/src/coreclr/pal/tests/palsuite/common/palsuite.cpp @@ -197,19 +197,3 @@ mkAbsoluteFilenameA ( return (sizeAPN); } - -BOOL -DeleteFileW( - IN LPCWSTR lpFileName) -{ - _ASSERTE(lpFileName != NULL); - - CHAR mbFileName[ MAX_PATH ]; - - if (WideCharToMultiByte( CP_ACP, 0, lpFileName, -1, mbFileName, sizeof(mbFileName), NULL, NULL ) != 0 ) - { - return remove(mbFileName) == 0; - } - - return FALSE; -} diff --git a/src/coreclr/pal/tests/palsuite/common/palsuite.h b/src/coreclr/pal/tests/palsuite/common/palsuite.h index 0c3591534e49ce..c53a8732f8e6c3 100644 --- a/src/coreclr/pal/tests/palsuite/common/palsuite.h +++ b/src/coreclr/pal/tests/palsuite/common/palsuite.h @@ -166,17 +166,6 @@ mkAbsoluteFilenameA ( DWORD dwFileLength, LPSTR absPathName ); -BOOL -CreatePipe( - OUT PHANDLE hReadPipe, - OUT PHANDLE hWritePipe, - IN LPSECURITY_ATTRIBUTES lpPipeAttributes, - IN DWORD nSize); - -BOOL -DeleteFileW( - IN LPCWSTR lpFileName); - #define wcstod PAL_wcstod #define wcstoul PAL_wcstoul #define wcscat PAL_wcscat diff --git a/src/coreclr/pal/tests/palsuite/compilableTests.txt b/src/coreclr/pal/tests/palsuite/compilableTests.txt index d2b04a50e94fe2..76c53595367098 100644 --- a/src/coreclr/pal/tests/palsuite/compilableTests.txt +++ b/src/coreclr/pal/tests/palsuite/compilableTests.txt @@ -91,15 +91,6 @@ debug_api/OutputDebugStringW/test1/paltest_outputdebugstringw_test1 exception_handling/RaiseException/test1/paltest_raiseexception_test1 exception_handling/RaiseException/test2/paltest_raiseexception_test2 exception_handling/RaiseException/test3/paltest_raiseexception_test3 -filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/paltest_createfilemappingw_createfilemapping_neg1 -filemapping_memmgt/CreateFileMappingW/test1/paltest_createfilemappingw_test1 -filemapping_memmgt/CreateFileMappingW/test3/paltest_createfilemappingw_test3 -filemapping_memmgt/CreateFileMappingW/test4/paltest_createfilemappingw_test4 -filemapping_memmgt/CreateFileMappingW/test5/paltest_createfilemappingw_test5 -filemapping_memmgt/CreateFileMappingW/test6/paltest_createfilemappingw_test6 -filemapping_memmgt/CreateFileMappingW/test7/paltest_createfilemappingw_test7 -filemapping_memmgt/CreateFileMappingW/test8/paltest_createfilemappingw_test8 -filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9 filemapping_memmgt/FreeLibrary/test1/paltest_freelibrary_test1 filemapping_memmgt/FreeLibrary/test2/paltest_freelibrary_test2 filemapping_memmgt/GetModuleFileNameA/test1/paltest_getmodulefilenamea_test1 @@ -108,50 +99,8 @@ filemapping_memmgt/GetModuleFileNameW/test1/paltest_getmodulefilenamew_test1 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 filemapping_memmgt/GetProcAddress/test1/paltest_getprocaddress_test1 filemapping_memmgt/GetProcAddress/test2/paltest_getprocaddress_test2 -filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 -filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 -filemapping_memmgt/MapViewOfFile/test4/paltest_mapviewoffile_test4 -filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5 -filemapping_memmgt/MapViewOfFile/test6/paltest_mapviewoffile_test6 filemapping_memmgt/ProbeMemory/ProbeMemory_neg1/paltest_probememory_probememory_neg1 filemapping_memmgt/ProbeMemory/test1/paltest_probememory_test1 -filemapping_memmgt/UnmapViewOfFile/test1/paltest_unmapviewoffile_test1 -filemapping_memmgt/UnmapViewOfFile/test2/paltest_unmapviewoffile_test2 -file_io/CreateFileA/test1/paltest_createfilea_test1 -file_io/CreateFileW/test1/paltest_createfilew_test1 -file_io/errorpathnotfound/test1/paltest_errorpathnotfound_test1 -file_io/FILECanonicalizePath/paltest_filecanonicalizepath_test1 -file_io/FlushFileBuffers/test1/paltest_flushfilebuffers_test1 -file_io/GetFileSize/test1/paltest_getfilesize_test1 -file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1 -file_io/GetFullPathNameA/test1/paltest_getfullpathnamea_test1 -file_io/GetFullPathNameA/test2/paltest_getfullpathnamea_test2 -file_io/GetFullPathNameA/test3/paltest_getfullpathnamea_test3 -file_io/GetFullPathNameA/test4/paltest_getfullpathnamea_test4 -file_io/GetFullPathNameW/test1/paltest_getfullpathnamew_test1 -file_io/GetFullPathNameW/test2/paltest_getfullpathnamew_test2 -file_io/GetFullPathNameW/test3/paltest_getfullpathnamew_test3 -file_io/GetFullPathNameW/test4/paltest_getfullpathnamew_test4 -file_io/GetStdHandle/test1/paltest_getstdhandle_test1 -file_io/GetStdHandle/test2/paltest_getstdhandle_test2 -file_io/gettemppatha/test1/paltest_gettemppatha_test1 -file_io/ReadFile/test1/paltest_readfile_test1 -file_io/ReadFile/test2/paltest_readfile_test2 -file_io/ReadFile/test3/paltest_readfile_test3 -file_io/ReadFile/test4/paltest_readfile_test4 -file_io/SearchPathW/test1/paltest_searchpathw_test1 -file_io/SetFilePointer/test1/paltest_setfilepointer_test1 -file_io/SetFilePointer/test2/paltest_setfilepointer_test2 -file_io/SetFilePointer/test3/paltest_setfilepointer_test3 -file_io/SetFilePointer/test4/paltest_setfilepointer_test4 -file_io/SetFilePointer/test5/paltest_setfilepointer_test5 -file_io/SetFilePointer/test6/paltest_setfilepointer_test6 -file_io/SetFilePointer/test7/paltest_setfilepointer_test7 -file_io/WriteFile/test1/paltest_writefile_test1 -file_io/WriteFile/test2/paltest_writefile_test2 -file_io/WriteFile/test3/paltest_writefile_test3 -file_io/WriteFile/test4/paltest_writefile_test4 -file_io/WriteFile/test5/paltest_writefile_test5 loader/LoadLibraryA/test1/paltest_loadlibrarya_test1 loader/LoadLibraryA/test2/paltest_loadlibrarya_test2 loader/LoadLibraryA/test3/paltest_loadlibrarya_test3 @@ -170,7 +119,6 @@ locale_info/WideCharToMultiByte/test2/paltest_widechartomultibyte_test2 locale_info/WideCharToMultiByte/test3/paltest_widechartomultibyte_test3 locale_info/WideCharToMultiByte/test4/paltest_widechartomultibyte_test4 locale_info/WideCharToMultiByte/test5/paltest_widechartomultibyte_test5 -miscellaneous/CloseHandle/test1/paltest_closehandle_test1 miscellaneous/CloseHandle/test2/paltest_closehandle_test2 miscellaneous/FlushInstructionCache/test1/paltest_flushinstructioncache_test1 miscellaneous/FormatMessageW/test1/paltest_formatmessagew_test1 @@ -231,8 +179,6 @@ samples/test2/paltest_samples_test2 threading/CreateThread/test1/paltest_createthread_test1 threading/CreateThread/test2/paltest_createthread_test2 threading/CreateThread/test3/paltest_createthread_test3 -threading/DuplicateHandle/test1/paltest_duplicatehandle_test1 -threading/DuplicateHandle/test12/paltest_duplicatehandle_test12 threading/DuplicateHandle/test7/paltest_duplicatehandle_test7 threading/DuplicateHandle/test8/paltest_duplicatehandle_test8 threading/DuplicateHandle/test9/paltest_duplicatehandle_test9 diff --git a/src/coreclr/pal/tests/palsuite/compileDisabledTests.txt b/src/coreclr/pal/tests/palsuite/compileDisabledTests.txt index 959509c0204672..6f826fc83fa0c8 100644 --- a/src/coreclr/pal/tests/palsuite/compileDisabledTests.txt +++ b/src/coreclr/pal/tests/palsuite/compileDisabledTests.txt @@ -27,7 +27,6 @@ exception_handling/PAL_TRY_EXCEPT_EX/test1/paltest_pal_try_except_ex_test1 exception_handling/PAL_TRY_EXCEPT_EX/test2/paltest_pal_try_except_ex_test2 exception_handling/PAL_TRY_EXCEPT_EX/test3/paltest_pal_try_except_ex_test3 exception_handling/PAL_TRY_LEAVE_FINALLY/test1/paltest_pal_try_leave_finally_test1 -filemapping_memmgt/CreateFileMappingW/test2/paltest_createfilemappingw_test2 loader/LoadLibraryA/test6/paltest_loadlibrarya_test6 loader/LoadLibraryA/test8/paltest_loadlibrarya_test8 locale_info/CompareStringA/test1/paltest_comparestringa_test1 diff --git a/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/CreateFileA.cpp b/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/CreateFileA.cpp deleted file mode 100644 index 4f95db199814fc..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/CreateFileA.cpp +++ /dev/null @@ -1,143 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: CreateFileA.c -** -** Purpose: Test the PAL implementation of the CreateFileA function -** -** -**===================================================================*/ - -#include - -BOOL Cleanup_CreateFileA_test1(void) -{ - char FileName[20]; - int i; - BOOL bRet = TRUE; // assume success - - // loop through all accesses, modes, dispositions and flags - for (i=0; i<4*8*4*4; ++i) { - sprintf_s(FileName, ARRAY_SIZE(FileName), "test%03d.txt", i); - if (DeleteFileA(FileName) == FALSE) { - if (GetLastError() != ERROR_FILE_NOT_FOUND) { - bRet = FALSE; - } - } - } - return bRet; -} - - -PALTEST(file_io_CreateFileA_test1_paltest_createfilea_test1, "file_io/CreateFileA/test1/paltest_createfilea_test1") -{ - BOOL bSuccess = TRUE; - int nCounter = 0; - HANDLE hFile; - char lpFileName[20]; - FILE *outFile = NULL; - char results[1024]; - int i, j, k, l; - DWORD dwDesiredAccess[4] = {0, // 0 - GENERIC_READ, // 1 - GENERIC_WRITE, // 2 - GENERIC_READ | GENERIC_WRITE}; // 3 - DWORD dwShareMode[8] = {0, // 0 - FILE_SHARE_READ, // 1 - FILE_SHARE_WRITE, // 2 - FILE_SHARE_DELETE, // 3 - FILE_SHARE_READ | FILE_SHARE_WRITE, // 4 - FILE_SHARE_READ | FILE_SHARE_DELETE, // 5 - FILE_SHARE_WRITE | FILE_SHARE_DELETE, // 6 - FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE}; // 7 - LPSECURITY_ATTRIBUTES lpAttr = NULL; - DWORD dwCreationDisp[4] = {CREATE_NEW, // 0 - CREATE_ALWAYS, // 1 - OPEN_EXISTING, // 2 - OPEN_ALWAYS}; // 3 - DWORD dwFlagsAttrib[4] = {FILE_ATTRIBUTE_NORMAL, // 0 - FILE_FLAG_SEQUENTIAL_SCAN, // 1 - FILE_FLAG_WRITE_THROUGH, // 2 - FILE_FLAG_RANDOM_ACCESS}; // 3 - HANDLE hTemplate = NULL; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - if (!Cleanup_CreateFileA_test1()) { - Trace("Pre-test Cleanup() failed. LastError=%d\n", GetLastError()); - return FAIL; - } - - /* open the file to read the expected results */ - outFile = fopen("winoutput", "r"); - memset (results, 0, 1024); - - fgets(results, 1024, outFile); - nCounter = (int)strlen(results); - fclose(outFile); - - nCounter = 0; - - // desired access loop - for (i = 0; i < 4; i++) - { - // share mode loop - for (j = 0; j < 8; j++) - { - // security attributes loop - for (k = 0; k < 4; k++) - { - // creation disp loop - for (l = 0; l < 4; l++) - { - sprintf_s(lpFileName, ARRAY_SIZE(lpFileName), "test%03d.txt", nCounter); - hFile = CreateFile(lpFileName, - dwDesiredAccess[i], - dwShareMode[j], - lpAttr, - dwCreationDisp[k], - dwFlagsAttrib[l], - hTemplate); - if (hFile == INVALID_HANDLE_VALUE) - { - if (results[nCounter] == '1') - { - Trace("CreateFile: ERROR: Failed when expected " - "to pass %s [%d][%d][%d][%d]\n", - lpFileName, i, j, k, l); - bSuccess = FALSE; - } - } - else - { - CloseHandle(hFile); - if (results[nCounter] == '0') - { - Trace("CreateFile: ERROR: Passed when expected " - "to fail %s [%d][%d][%d][%d]\n", - lpFileName, i, j, k, l); - bSuccess = FALSE; - } - } - nCounter ++; - } - } - } - } - - if (!Cleanup_CreateFileA_test1()) - { - Trace("Post-test Cleanup() failed. LastError=%d\n", GetLastError()); - return FAIL; - } - - int exitCode = bSuccess ? PASS : FAIL; - PAL_TerminateEx(exitCode); - return exitCode; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/winoutput b/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/winoutput deleted file mode 100644 index 3913b99427feeb..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/CreateFileA/test1/winoutput +++ /dev/null @@ -1 +0,0 @@ -1111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111 \ No newline at end of file diff --git a/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/CreateFileW.cpp b/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/CreateFileW.cpp deleted file mode 100644 index 42c4d12d228eed..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/CreateFileW.cpp +++ /dev/null @@ -1,150 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: CreateFileW.c -** -** Purpose: Test the PAL implementation of the CreateFileW function -** -** -**===================================================================*/ - -#include - -BOOL Cleanup_CreateFileW_test1(void) -{ - char FileName[20]; - int i; - BOOL bRet = TRUE; // assume success - - // loop through all accesses, modes, dispositions and flags - for (i=0; i<4*8*4*4; ++i) { - sprintf_s(FileName, ARRAY_SIZE(FileName), "test%03d.txt", i); - if (DeleteFileA(FileName) == FALSE) { - if (GetLastError() != ERROR_FILE_NOT_FOUND) { - bRet = FALSE; - } - } - } - return bRet; -} - - -PALTEST(file_io_CreateFileW_test1_paltest_createfilew_test1, "file_io/CreateFileW/test1/paltest_createfilew_test1") -{ - BOOL bSuccess = TRUE; - int nCounter = 0; - HANDLE hFile = NULL; - WCHAR *lpFileName = NULL; - char* pTemp = NULL; - char string[40]; - FILE *outFile = NULL; - char results[1024]; - int i, j, k, l; - DWORD dwDesiredAccess[4] = {0, // 0 - GENERIC_READ, // 1 - GENERIC_WRITE, // 2 - GENERIC_READ | GENERIC_WRITE}; // 3 - DWORD dwShareMode[8] = {0, // 0 - FILE_SHARE_READ, // 1 - FILE_SHARE_WRITE, // 2 - FILE_SHARE_DELETE, // 3 - FILE_SHARE_READ | FILE_SHARE_WRITE, // 4 - FILE_SHARE_READ | FILE_SHARE_DELETE, // 5 - FILE_SHARE_WRITE | FILE_SHARE_DELETE, // 6 - FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE}; // 7 - LPSECURITY_ATTRIBUTES lpAttr = NULL; - DWORD dwCreationDisp[4] = {CREATE_NEW, // 0 - CREATE_ALWAYS, // 1 - OPEN_EXISTING, // 2 - OPEN_ALWAYS}; // 3 - DWORD dwFlagsAttrib[4] = {FILE_ATTRIBUTE_NORMAL, // 0 - FILE_FLAG_SEQUENTIAL_SCAN, // 1 - FILE_FLAG_WRITE_THROUGH, // 2 - FILE_FLAG_RANDOM_ACCESS}; // 3 - HANDLE hTemplate = NULL; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - if (!Cleanup_CreateFileW_test1()) { - Trace("Pre-test Cleanup() failed. LastError=%d\n", GetLastError()); - return FAIL; - } - - /* open the file to read the expected results */ - outFile = fopen("winoutput", "r"); - memset (results, 0, 1024); - - fgets(results, 1024, outFile); - fclose(outFile); - - nCounter = 0; - - // desired access loop - for (i = 0; i < 4; i++) - { - // share mode loop - for (j = 0; j < 8; j++) - { - // security attributes loop - for (k = 0; k < 4; k++) - { - // creation disp loop - for (l = 0; l < 4; l++) - { - sprintf_s(string, ARRAY_SIZE(string), "test%03d.txt", nCounter); - lpFileName = convert(string); - hFile = CreateFileW(lpFileName, - dwDesiredAccess[i], - dwShareMode[j], - lpAttr, - dwCreationDisp[k], - dwFlagsAttrib[l], - hTemplate); - free(lpFileName); - if (hFile == INVALID_HANDLE_VALUE) - { - if (results[nCounter] == '1') - { - pTemp = convertC(lpFileName); - Trace("CreateFile: ERROR: Failed when expected " - "to pass %s [%d][%d][%d][%d]\n", - pTemp, i, j, k, l); - free(pTemp); - bSuccess = FALSE; - } - } - else - { - CloseHandle(hFile); - if (results[nCounter] == '0') - { - pTemp = convertC(lpFileName); - Trace("CreateFile: ERROR: Passed when expected " - "to fail %s [%d][%d][%d][%d]\n", - pTemp, i, j, k, l); - free(pTemp); - bSuccess = FALSE; - } - } - nCounter ++; - } - } - } - } - - if (!Cleanup_CreateFileW_test1()) - { - Trace("Post-test Cleanup() failed. LastError=%d\n", GetLastError()); - return FAIL; - } - - int exitCode = bSuccess ? PASS : FAIL; - PAL_TerminateEx(exitCode); - return exitCode; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/winoutput b/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/winoutput deleted file mode 100644 index 3913b99427feeb..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/CreateFileW/test1/winoutput +++ /dev/null @@ -1 +0,0 @@ -1111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111111111111100000111111111111111000001111111111111110000011111 \ No newline at end of file diff --git a/src/coreclr/pal/tests/palsuite/file_io/FILECanonicalizePath/FILECanonicalizePath.cpp b/src/coreclr/pal/tests/palsuite/file_io/FILECanonicalizePath/FILECanonicalizePath.cpp deleted file mode 100644 index 74daffe3a5ad0a..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/FILECanonicalizePath/FILECanonicalizePath.cpp +++ /dev/null @@ -1,82 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: FILECanonicalizePath.c (test 1) -** -** Purpose: Tests the PAL implementation of the FILECanonicalizePath function. -** -** -**===================================================================*/ - -#include - -extern "C" void FILECanonicalizePath(LPSTR lpUnixPath); - -void TestCase(LPSTR input, LPSTR expectedOutput); - -PALTEST(file_io_FILECanonicalizePath_paltest_filecanonicalizepath_test1, "file_io/FILECanonicalizePath/paltest_filecanonicalizepath_test1") -{ - if (PAL_Initialize(argc,argv) != 0) - { - return FAIL; - } - - // Case 01: / should not change - TestCase("/Test", "/Test"); - - // Case 02: // should not change - TestCase("/Test/Foo", "/Test/Foo"); - - // Case 03: // transforms to / - TestCase("//", "/"); - - // Case 04: /./ transforms to / - TestCase("/./", "/"); - - // Case 05: //../ transforms to / - TestCase("/Test/../", "/"); - - // Case 06: /Test/Foo/.. transforms to /Test - TestCase("/Test/Foo/..", "/Test"); - - // Case 07: /Test/.. transforms to / - TestCase("/Test/..", "/"); - - // Case 08: /. transforms to / - TestCase("/.", "/"); - - // Case 09: / - TestCase("/Test/.", "/Test"); - - // Case 10: //../. transforms to / - TestCase("/Test/../.", "/"); - - // Case 11: /.. transforms to / - TestCase("/..", "/"); - - PAL_Terminate(); - return PASS; -} - -void TestCase(LPSTR input, LPSTR expectedOutput) -{ - // Save the input for debug logging since the input is edited in-place - char* pOriginalInput = (char*)malloc(strlen(input) * sizeof(char) + 1); - strcpy(pOriginalInput, input); - - char* pInput = (char*)malloc(strlen(input) * sizeof(char) + 1); - strcpy(pInput, pOriginalInput); - - FILECanonicalizePath(pInput); - if (strcmp(pInput, expectedOutput) != 0) - { - free(pOriginalInput); - free(pInput); - Fail("FILECanonicalizePath error: input %s did not match expected output %s; got %s instead", pOriginalInput, expectedOutput, pInput); - } - - free(pOriginalInput); - free(pInput); -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/FlushFileBuffers/test1/FlushFileBuffers.cpp b/src/coreclr/pal/tests/palsuite/file_io/FlushFileBuffers/test1/FlushFileBuffers.cpp deleted file mode 100644 index 24e5be3c103425..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/FlushFileBuffers/test1/FlushFileBuffers.cpp +++ /dev/null @@ -1,129 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: FlushFileBuffers.c -** -** Purpose: Tests the PAL implementation of the FlushFileBuffers function -** This tests checks the return values of FlushFileBuffers -- once on an -** open handle and once on a closed handle. -** -** Depends: -** CreateFile -** WriteFile -** CloseHandle -** DeleteFileA -** -** -**===================================================================*/ - -#include - - -PALTEST(file_io_FlushFileBuffers_test1_paltest_flushfilebuffers_test1, "file_io/FlushFileBuffers/test1/paltest_flushfilebuffers_test1") -{ - - int TheReturn; - HANDLE TheFileHandle; - DWORD temp; - DWORD originalSize=10000; - DWORD finalSize=10000; - const char* fileName="the_file"; - - /* 1 2 3 4*/ - char * SomeText = "1234567890123456789012345678901234567890"; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - - /* Open the file to get a HANDLE */ - TheFileHandle = - CreateFile( - fileName, - GENERIC_READ|GENERIC_WRITE, - FILE_SHARE_READ, - NULL, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(TheFileHandle == INVALID_HANDLE_VALUE) - { - Fail("ERROR: CreateFile failed. Test depends on this function."); - } - - /* get the file size */ - originalSize = GetFileSize (TheFileHandle, NULL) ; - if(originalSize == INVALID_FILE_SIZE) - { - Fail("ERROR: call to GetFileSize failed with error " - "The GetLastError is %d.",GetLastError()); - } - - /* Write something too the HANDLE. Should be buffered */ - TheReturn = WriteFile(TheFileHandle, - SomeText, - strlen(SomeText), - &temp, - NULL); - - if(TheReturn == 0) - { - Fail("ERROR: WriteFile failed. Test depends on this function."); - } - - /* Test to see that FlushFileBuffers returns a success value */ - TheReturn = FlushFileBuffers(TheFileHandle); - if(TheReturn == 0) - { - Fail("ERROR: The FlushFileBuffers function returned 0, which " - "indicates failure, when trying to flush a valid HANDLE. " - "The GetLastError is %d.",GetLastError()); - } - - /* test if flush modified the file */ - finalSize = GetFileSize (TheFileHandle, NULL) ; - if(finalSize==INVALID_FILE_SIZE) - { - Fail("ERROR: call to GetFileSize faild with error " - "The GetLastError is %d.",GetLastError()); - } - if(finalSize!=(originalSize+strlen(SomeText))) - { - Fail("ERROR: FlushFileBuffers failed. data was not written to the file"); - } - - - /* Close the Handle */ - TheReturn = CloseHandle(TheFileHandle); - if(TheReturn == 0) - { - Fail("ERROR: CloseHandle failed. This function depends " - "upon it."); - } - - - /* Test to see that FlushFileBuffers returns a failure value */ - TheReturn = FlushFileBuffers(TheFileHandle); - if(TheReturn != 0) - { - Fail("ERROR: The FlushFileBuffers function returned non-zero, " - "which indicates success, when trying to flush an invalid " - "HANDLE."); - } - - /* make sure file does not exist */ - if(DeleteFileA(fileName)== 0 ) - { - Fail("ERROR: call to DeleteFileA faild with error " - "The GetLastError is %d.",GetLastError()); - } - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFileSize/test1/GetFileSize.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFileSize/test1/GetFileSize.cpp deleted file mode 100644 index aab5c9405e101e..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFileSize/test1/GetFileSize.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetFileSize.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetFileSize function. -** -** -**===================================================================*/ - -#include - - - -void CleanUp_GetFileSize_test1(HANDLE hFile) -{ - if (CloseHandle(hFile) != TRUE) - { - Fail("GetFileSize: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Fail("GetFileSize: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } -} - -PALTEST(file_io_GetFileSize_test1_paltest_getfilesize_test1, "file_io/GetFileSize/test1/paltest_getfilesize_test1") -{ - HANDLE hFile = NULL; - DWORD dwRc = 0; - DWORD dwRc2 = 0; - DWORD dwHighOrder = 0; - DWORD lpNumberOfBytesWritten; - char * data = "1234567890"; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - - /* test on a null file handle */ - dwRc = GetFileSize(hFile, NULL); - if (dwRc != INVALID_FILE_SIZE) - { - Fail("GetFileSize: ERROR -> A file size was returned for " - "a null handle.\n"); - } - - /* test on a null file handle using the high order option */ - dwRc = GetFileSize(hFile, &dwHighOrder); - if (dwRc != INVALID_FILE_SIZE) - { - Fail("GetFileSize: ERROR -> A file size was returned for " - "a null handle.\n"); - } - - /* test on an invalid file handle */ - dwRc = GetFileSize(INVALID_HANDLE_VALUE, NULL); - if (dwRc != INVALID_FILE_SIZE) - { - Fail("GetFileSize: ERROR -> A file size was returned for " - "an invalid handle.\n"); - } - - /* test on an invalid file handle using the high order option */ - dwRc = GetFileSize(INVALID_HANDLE_VALUE, &dwHighOrder); - if (dwRc != INVALID_FILE_SIZE) - { - Fail("GetFileSize: ERROR -> A file size was returned for " - "an invalid handle.\n"); - } - - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("GetFileSize: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - /* test if file size changes by writing to it. */ - /* get file size */ - dwRc = GetFileSize(hFile, NULL); - - /* test writing to the file */ - if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0) - { - Trace("GetFileSize: ERROR -> Call to WriteFile failed with %ld.\n", - GetLastError()); - CleanUp_GetFileSize_test1(hFile); - Fail(""); - } - - /* make sure the buffer flushed.*/ - if(FlushFileBuffers(hFile)==0) - { - Trace("GetFileSize: ERROR -> Call to FlushFileBuffers failed with %ld.\n", - GetLastError()); - CleanUp_GetFileSize_test1(hFile); - Fail(""); - } - - /* get file size after writing some chars */ - dwRc2 = GetFileSize(hFile, NULL); - if((dwRc2-dwRc) !=strlen(data)) - { - CleanUp_GetFileSize_test1(hFile); - Fail("GetFileSize: ERROR -> File size did not increase properly after.\n" - "writing %d chars\n", strlen(data)); - } - - CleanUp_GetFileSize_test1(hFile); - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp deleted file mode 100644 index b8aef40157c4ea..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFileSizeEx/test1/GetFileSizeEx.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetFileSizeEx.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetFileSizeEx function. -** -** -**===================================================================*/ - -#include - - - -void CleanUp_GetFileSizeEx_test1(HANDLE hFile) -{ - if (CloseHandle(hFile) != TRUE) - { - Fail("GetFileSizeEx: ERROR -> Unable to close file \"%s\".\n" - " Error is %d\n", - szTextFile, GetLastError()); - } - if (!DeleteFileA(szTextFile)) - { - Fail("GetFileSizeEx: ERROR -> Unable to delete file \"%s\".\n" - " Error is %d\n", - szTextFile, GetLastError()); - } -} - -PALTEST(file_io_GetFileSizeEx_test1_paltest_getfilesizeex_test1, "file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1") -{ - HANDLE hFile = NULL; - BOOL bRc = FALSE; - DWORD lpNumberOfBytesWritten; - LARGE_INTEGER qwFileSize; - LARGE_INTEGER qwFileSize2; - char * data = "1234567890"; - - qwFileSize.QuadPart = 0; - qwFileSize2.QuadPart = 0; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - - /* test on a null file */ - bRc = GetFileSizeEx(NULL, &qwFileSize); - if (bRc != FALSE) - { - Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " - "a null handle.\n"); - } - - - /* test on an invalid file */ - bRc = GetFileSizeEx(INVALID_HANDLE_VALUE, &qwFileSize); - if (bRc != FALSE) - { - Fail("GetFileSizeEx: ERROR -> Returned status as TRUE for " - "an invalid handle.\n"); - } - - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("GetFileSizeEx: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - /* test if file size changes by writing to it. */ - /* get file size */ - GetFileSizeEx(hFile, &qwFileSize); - - /* test writing to the file */ - if(WriteFile(hFile, data, strlen(data), &lpNumberOfBytesWritten, NULL)==0) - { - Trace("GetFileSizeEx: ERROR -> Call to WriteFile failed with %ld.\n", - GetLastError()); - CleanUp_GetFileSizeEx_test1(hFile); - Fail(""); - } - - /* make sure the buffer flushed.*/ - if(FlushFileBuffers(hFile)==0) - { - Trace("GetFileSizeEx: ERROR -> Call to FlushFileBuffers failed with %ld.\n", - GetLastError()); - CleanUp_GetFileSizeEx_test1(hFile); - Fail(""); - } - - /* get file size after writing some chars */ - GetFileSizeEx(hFile, &qwFileSize2); - if((qwFileSize2.QuadPart-qwFileSize.QuadPart) !=strlen(data)) - { - CleanUp_GetFileSizeEx_test1(hFile); - Fail("GetFileSizeEx: ERROR -> File size did not increase properly after.\n" - "writing %d chars\n", strlen(data)); - } - - CleanUp_GetFileSizeEx_test1(hFile); - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test1/GetFullPathNameA.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test1/GetFullPathNameA.cpp deleted file mode 100644 index 18aee4bba03818..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test1/GetFullPathNameA.cpp +++ /dev/null @@ -1,121 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetFullPathNameA.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetFullPathNameA function. -** -** -**===================================================================*/ - -#include - -PALTEST(file_io_GetFullPathNameA_test1_paltest_getfullpathnamea_test1, "file_io/GetFullPathNameA/test1/paltest_getfullpathnamea_test1") -{ - const char* szFileName = "testing.tmp"; - - DWORD dwRc = 0; - char szReturnedPath[_MAX_DIR+1]; - char szShortBuff[2]; - LPSTR pPathPtr; - HANDLE hFile = NULL; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* perform a short buffer test */ - if (GetFullPathNameA(szFileName, 2, szShortBuff, &pPathPtr) <= 2) - { - /* this test should have failed but didn't */ - Fail("GetFullPathNameA: ERROR -> The API was passed a buffer that was" - " too small for the path name and yet it apparently passed.\n"); - } - - memset(szReturnedPath, 0, _MAX_DIR+1); - dwRc = GetFullPathNameA(szFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - - if (dwRc == 0) - { - // this test should have passed but didn't - Fail("GetFullPathNameA: ERROR -> Function failed for the " - "file \"%s\" with error code: %ld.\n", szFileName, GetLastError()); - } - - // the returned value should be the current directory with the - // file name appended - hFile = CreateFileA(szFileName, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetFullPathNameA: ERROR -> CreateFileA failed to create " - "file \"%s\" with error code: %ld.\n", - szFileName, - GetLastError()); - } - if (CloseHandle(hFile) != TRUE) - { - Fail("GetFullPathNameA: ERROR -> CloseHandle failed with error " - "code: %ld.\n", GetLastError()); - } - - // now try to create the file based on the returned value with the - // CREATE_NEW option which should fail since the file should - // already exist - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile != INVALID_HANDLE_VALUE) - { - Fail("GetFullPathNameA: ERROR -> CreateFileA was able to " - "CREATE_NEW the returned file \"%s\". The returned file " - "name is therefore apparently wrong.\n", - szReturnedPath); - if (CloseHandle(hFile) != TRUE) - { - Fail("GetFullPathNameA: ERROR -> CloseHandle failed with " - "error code: %ld.\n", GetLastError()); - } - if ((DeleteFileA(szReturnedPath) != TRUE) || - (DeleteFileA(szFileName) != TRUE)) - { - Fail("GetFullPathNameA: ERROR -> DeleteFileA failed to " - "delete the test files with error code: %ld.\n", - GetLastError()); - } - } - - // now make sure the pPathPtr is the same as the file name - if (strcmp(pPathPtr, szFileName) != 0) - { - Fail("GetFullPathNameA: ERROR -> %s != %s\n", - pPathPtr, szFileName); - } - if (DeleteFileA(szFileName) != TRUE) - { - Fail("GetFullPathNameA: ERROR -> DeleteFileA failed to " - "delete \"%s\" with error code: %ld.\n", - szFileName, - GetLastError()); - } - - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test2/test2.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test2/test2.cpp deleted file mode 100644 index b63e61f33e60f0..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test2/test2.cpp +++ /dev/null @@ -1,142 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test2.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameA API. -** GetFullPathA will be passed a directory that contains '..'. -** To add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** The test will create a file with in the parent directory -** to verify that the returned directory is valid. -** -** -**===================================================================*/ - -#include - -PALTEST(file_io_GetFullPathNameA_test2_paltest_getfullpathnamea_test2, "file_io/GetFullPathNameA/test2/paltest_getfullpathnamea_test2") -{ - const char* szDotDot = "..\\"; - const char* szFileName = "testing.tmp"; - - DWORD dwRc = 0; - char szReturnedPath[_MAX_DIR+1]; - char szFullFileName[_MAX_DIR+1]; - LPSTR pPathPtr; - HANDLE hFile = NULL; - - /* Initialize the PAL. - */ - if (0 != PAL_Initialize(argc,argv)) - { - return (FAIL); - } - - /* change the directory */ - if (!SetCurrentDirectoryA(szDotDot)) - { - Fail("ERROR: SetCurrentDirectoryA failed with error code %u" - " when passed \"%s\".\n", - GetLastError(), - szDotDot); - } - - /* Initialize the receiving char buffers. - */ - memset(szReturnedPath, 0, _MAX_DIR+1); - memset(szFullFileName, 0, _MAX_DIR+1); - - /* Create Full filename to pass, will include '..\' - * as a pre-fix. */ - strcat(szFullFileName, szDotDot); - strcat(szFullFileName, szFileName); - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameA(szFullFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - if (dwRc == 0) - { - Fail("ERROR :%ld: GetFullPathName failed to " - "retrieve the path of \"%s\".\n", - GetLastError(), - szFileName); - } - - /* The returned value should be the parent directory with the - * file name appended. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR :%ld: CreateFileA failed to create \"%s\".\n", - GetLastError(), - szReturnedPath); - } - - /* Close the handle to the created file. - */ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n", - GetLastError()); - goto terminate; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Fail("ERROR :%ld: CreateFileA succeeded to create file " - "\"%s\", that already existed.\n", - GetLastError(), - szFullFileName); - } - - - /* Verify that the returned filename is the same as the supplied. - */ - if (strcmp(pPathPtr, szFileName) != 0) - { - Trace("ERROR : Returned filename \"%s\" is not equal to " - "supplied filename \"%s\".\n", - pPathPtr, - szFileName); - goto terminate; - } - -terminate: - /* Delete the create file. - */ - if (DeleteFileA(szReturnedPath) != TRUE) - { - Fail("ERROR :%ld: DeleteFileA failed to delete \"%s\".\n", - GetLastError(), - szFileName); - } - - /* Terminate the PAL.*/ - PAL_Terminate(); - return PASS; -} - - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test3/test3.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test3/test3.cpp deleted file mode 100644 index 350d187e3950e4..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test3/test3.cpp +++ /dev/null @@ -1,242 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test3.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameA API. -** GetFullPathA will be passed a directory that contains '..'. -** Example: test_directory\level1\..\testing.tmp. -** To add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** The test will create a file with in the parent directory -** to verify that the returned directory is valid. -** -** Depends: SetCurrentDirectory, -** CreateDirectory, -** strcat, -** memset, -** CreateFile, -** CloseHandle, -** strcmp, -** DeleteFileA, -** RemoveDirectory. -** - -** -**===================================================================*/ - -#include - - -PALTEST(file_io_GetFullPathNameA_test3_paltest_getfullpathnamea_test3, "file_io/GetFullPathNameA/test3/paltest_getfullpathnamea_test3") -{ -#ifdef WIN32 - const char* szSeparator = "\\"; -#else - const char* szSeparator = "/"; -#endif - - const char* szDotDot = "../"; - const char* szFileName = "testing.tmp"; - - DWORD dwRc = 0; - char szReturnedPath[_MAX_DIR+1]; - char szFullFileName[_MAX_DIR+1]; - char szDirectory[256]; - char* szCreatedDir = {"test_directory"}; - char* szCreatedNextDir = {"level1"}; - WCHAR *szCreatedDirW; - LPSTR pPathPtr; - HANDLE hFile = NULL; - BOOL bRetVal = FAIL; - - /* Initialize the PAL. - */ - if (0 != PAL_Initialize(argc,argv)) - { - return (FAIL); - } - - /* Initialize the buffer. - */ - memset(szDirectory, '\0', 256); - - /* Change the current working directory. - */ - if (!SetCurrentDirectoryA(szDotDot)) - { - Fail("ERROR: SetCurrentDirectoryA failed with error code %u" - " when passed \"%s\".\n", - GetLastError(), - szDotDot); - } - - /* Create the path to the next level of directory to create. - */ - strcat( szDirectory, szCreatedDir ); - - - /* Create a test directory. - */ - if ( !CreateDirectoryA( szDirectory, NULL ) ) - { - Fail("ERROR:%u: Unable to create directories \"%s\".\n", - GetLastError(), - szDirectory); - } - - /* Create the path to the next level of directory to create. - */ - strcat( szDirectory, szSeparator ); - strcat( szDirectory, szCreatedNextDir ); - - /* Create a test directory. - */ - if ( !CreateDirectoryA( szDirectory, NULL ) ) - { - Trace("ERROR:%u: Unable to create directories \"%s\".\n", - GetLastError(), - szDirectory); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* Initialize the receiving char buffers. - */ - memset(szReturnedPath, 0, _MAX_DIR+1); - memset(szFullFileName, 0, _MAX_DIR+1); - - /* Create Full filename to pass, will include '..\' - * in the middle of the path. - */ - strcat(szFullFileName, szCreatedDir); - strcat(szFullFileName, szSeparator); - strcat(szFullFileName, szDotDot); - strcat(szFullFileName, szFileName); - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameA(szFullFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - if (dwRc == 0) - { - Trace("ERROR :%ld: GetFullPathName failed to " - "retrieve the path of \"%s\".\n", - GetLastError(), - szFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* The returned value should be the parent directory with the - * file name appended. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Trace("ERROR :%ld: CreateFileA failed to create \"%s\".\n", - GetLastError(), - szReturnedPath); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Close the handle to the created file. - */ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n", - GetLastError()); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Trace("ERROR :%ld: CreateFileA succeeded to create file " - "\"%s\", that already existed.\n", - GetLastError(), - szFullFileName); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Verify that the returned filename is the same as the supplied. - */ - if (strcmp(pPathPtr, szFileName) != 0) - { - Trace("ERROR : Returned filename \"%s\" is not equal to " - "supplied filename \"%s\".\n", - pPathPtr, - szFileName); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Successful test. - */ - bRetVal = PASS; - -cleanUpThree: - - /* Delete the create file. - */ - if (DeleteFileA(szReturnedPath) != TRUE) - { - Fail("ERROR :%ld: DeleteFileA failed to delete \"%s\".\n", - GetLastError(), - szFileName); - } - -cleanUpTwo: - - /* Remove the empty directory. - */ - szCreatedDirW = convert((LPSTR)szDirectory); - if (!RemoveDirectoryW(szCreatedDirW)) - { - free (szCreatedDirW); - Fail("ERROR:%u: Unable to remove directory \"%s\".\n", - GetLastError(), - szCreatedDir); - } - free (szCreatedDirW); - -cleanUpOne: - - /* Remove the empty directory. - */ - szCreatedDirW = convert((LPSTR)szCreatedDir); - if (!RemoveDirectoryW(szCreatedDirW)) - { - free (szCreatedDirW); - Fail("ERROR:%u: Unable to remove directory \"%s\".\n", - GetLastError(), - szCreatedDir); - } - free (szCreatedDirW); - - /* Terminate the PAL.*/ - PAL_TerminateEx(bRetVal); - return bRetVal; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test4/test4.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test4/test4.cpp deleted file mode 100644 index 99dc826971161b..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameA/test4/test4.cpp +++ /dev/null @@ -1,203 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test4.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameA API. -** GetFullPathA will be passed a directory that begins with '..'. -** Example: ..\test_directory\testing.tmp. -** To add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** The test will create a file with in the parent directory -** to verify that the returned directory is valid. -** -** Depends: SetCurrentDirectory, -** CreateDirectory, -** strcat, -** memset, -** CreateFile, -** CloseHandle, -** strcmp, -** DeleteFileA, -** RemoveDirectory. -** - -** -**===================================================================*/ - -#include - - -PALTEST(file_io_GetFullPathNameA_test4_paltest_getfullpathnamea_test4, "file_io/GetFullPathNameA/test4/paltest_getfullpathnamea_test4") -{ -#ifdef WIN32 - const char* szSeparator = "\\"; -#else - const char* szSeparator = "//"; -#endif - - const char* szDotDot = ".."; - const char* szFileName = "testing.tmp"; - - DWORD dwRc = 0; - char szReturnedPath[_MAX_DIR+1]; - char szFullFileName[_MAX_DIR+1]; - char szDirectory[256]; - char* szCreatedDir = {"test_directory"}; - WCHAR *szCreatedDirW; - LPSTR pPathPtr; - HANDLE hFile = NULL; - BOOL bRetVal = FAIL; - - /* Initialize the PAL. - */ - if (0 != PAL_Initialize(argc,argv)) - { - return (FAIL); - } - - /* Initialize the buffer. - */ - memset(szDirectory, '\0', 256); - - /* Create the path to the next level of directory to create. - */ - strcat( szDirectory, szDotDot ); /* .. */ - strcat( szDirectory, szSeparator ); /* ../ */ - strcat( szDirectory, szCreatedDir ); /* ../test_directory */ - - /* Create a test directory. - */ - if ( !CreateDirectoryA( szDirectory, NULL ) ) - { - Fail("ERROR:%u: Unable to create directories \"%s\".\n", - GetLastError(), - szDirectory); - } - - /* Initialize the receiving char buffers. - */ - memset(szReturnedPath, 0, _MAX_DIR+1); - memset(szFullFileName, 0, _MAX_DIR+1); - - /* Create Full filename to pass, will include '..\' - * in the middle of the path. - */ - strcat( szFullFileName, szDotDot ); /* .. */ - strcat( szFullFileName, szSeparator ); /* ../ */ - strcat( szFullFileName, szCreatedDir ); /* ../test_directory */ - strcat( szFullFileName, szSeparator ); /* ../test_directory/ */ - strcat( szFullFileName, szFileName ); /* ../test_directory/testing.tmp */ - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameA(szFullFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - if (dwRc == 0) - { - Trace("ERROR :%ld: GetFullPathName failed to " - "retrieve the path of \"%s\".\n", - GetLastError(), - szFileName); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* The returned value should be the parent directory with the - * file name appended. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Trace("ERROR :%ld: CreateFileA failed to create \"%s\".\n", - GetLastError(), - szReturnedPath); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* Close the handle to the created file. - */ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n", - GetLastError()); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileA(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Trace("ERROR :%ld: CreateFileA succeeded to create file " - "\"%s\", that already existed.\n", - GetLastError(), - szFullFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Verify that the returned filename is the same as the supplied. - */ - if (strcmp(pPathPtr, szFileName) != 0) - { - Trace("ERROR : Returned filename \"%s\" is not equal to " - "supplied filename \"%s\".\n", - pPathPtr, - szFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Successful test. - */ - bRetVal = PASS; - -cleanUpTwo: - - /* Delete the create file. - */ - if (DeleteFileA(szReturnedPath) != TRUE) - { - Fail("ERROR :%ld: DeleteFileA failed to delete \"%s\".\n", - GetLastError(), - szFileName); - } - -cleanUpOne: - - /* Remove the empty directory. - */ - szCreatedDirW = convert((LPSTR)szDirectory); - if (!RemoveDirectoryW(szCreatedDirW)) - { - free (szCreatedDirW); - Fail("ERROR:%u: Unable to remove directory \"%s\".\n", - GetLastError(), - szCreatedDir); - } - free (szCreatedDirW); - - /* Terminate the PAL.*/ - PAL_TerminateEx(bRetVal); - return bRetVal; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test1/GetFullPathNameW.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test1/GetFullPathNameW.cpp deleted file mode 100644 index 281c2023016bb9..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test1/GetFullPathNameW.cpp +++ /dev/null @@ -1,156 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetFullPathNameW.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetFullPathNameW function. -** -** -**===================================================================*/ - -#include - -PALTEST(file_io_GetFullPathNameW_test1_paltest_getfullpathnamew_test1, "file_io/GetFullPathNameW/test1/paltest_getfullpathnamew_test1") -{ - const char* szFileName = "testing.tmp"; - - DWORD dwRc = 0; - WCHAR szwReturnedPath[_MAX_DIR+1]; - WCHAR szwShortBuff[2]; - LPWSTR pPathPtr; - HANDLE hFile = NULL; - WCHAR* szwFileName = NULL; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - szwFileName = convert((char*)szFileName); - - /* perform a short buffer test */ - if (GetFullPathNameW(szwFileName, 2, szwShortBuff, &pPathPtr) <= 2) - { - free(szwFileName); - /* this test should have failed but didn't */ - Fail("GetFullPathNameW: ERROR -> The API was passed a buffer that was" - " too small for the path name and yet it apparently passed.\n"); - } - - - memset(szwReturnedPath, 0, sizeof(szwReturnedPath)); - dwRc = GetFullPathNameW(szwFileName, - _MAX_DIR, - szwReturnedPath, - &pPathPtr); - - if (dwRc == 0) - { - /* this test should have passed but didn't */ - free(szwFileName); - Fail("GetFullPathNameW: ERROR -> Function failed for the " - "file \"%s\" with error code: %ld.\n", szFileName, GetLastError()); - } - /* - * the returned value should be the current directory with the - * file name appended - */ - hFile = CreateFileW(szwFileName, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - free(szwFileName); - Fail("GetFullPathNameW: ERROR -> CreateFileW failed to create " - "file \"%s\" with error code: %ld.\n", - szFileName, - GetLastError()); - } - if (CloseHandle(hFile) != TRUE) - { - free(szwFileName); - Trace("GetFullPathNameW: ERROR -> CloseHandle failed with error " - "code: %ld.\n", GetLastError()); - if (DeleteFileA(szFileName) != TRUE) - { - Trace("GetFullPathNameW: ERROR -> DeleteFileW failed to " - "delete the test file with error code: %ld.\n", - GetLastError()); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* - * now try to create the file based on the returned value with the - * CREATE_NEW option which should fail since the file should - * already exist - */ - hFile = CreateFileW(szwReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile != INVALID_HANDLE_VALUE) - { - Trace("GetFullPathNameW: ERROR -> CreateFileW was able to " - "CREATE_NEW the returned file \"%s\". The returned file " - "name is therefore apparently wrong.\n", - szwReturnedPath); - if (CloseHandle(hFile) != TRUE) - { - Trace("GetFullPathNameW: ERROR -> CloseHandle failed with " - "error code: %ld.\n", GetLastError()); - } - if ((DeleteFileW(szwReturnedPath) != TRUE) || - (DeleteFileW(szwFileName) != TRUE)) - { - Trace("GetFullPathNameW: ERROR -> DeleteFileW failed to " - "delete the test files with error code: %ld.\n", - GetLastError()); - } - free(szwFileName); - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* now make sure the pPathPtr is the same as the file name */ - if (wcsncmp(pPathPtr, szwFileName, wcslen(szwFileName)) != 0) - { - Trace("GetFullPathNameW: ERROR -> %s != %s\n", - pPathPtr, szFileName); - if ((DeleteFileW(szwReturnedPath) != TRUE) || - (DeleteFileW(szwFileName) != TRUE)) - { - Trace("GetFullPathNameW: ERROR -> DeleteFileW failed to " - "delete the test files with error code: %ld.\n", - GetLastError()); - } - free(szwFileName); - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* clean up */ - free(szwFileName); - if (DeleteFileA(szFileName) != TRUE) - { - Fail("GetFullPathNameW: ERROR -> DeleteFileW failed to " - "delete \"%s\" with error code: %ld.\n", - szFileName, - GetLastError()); - } - - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test2/test2.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test2/test2.cpp deleted file mode 100644 index 2ed9e1279f487d..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test2/test2.cpp +++ /dev/null @@ -1,158 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test2.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameW function. -** Get the full path for a file name and verify the results. -** This test will use a relative path, containing '..\'. To -** add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** -** -**===================================================================*/ - -#include - -PALTEST(file_io_GetFullPathNameW_test2_paltest_getfullpathnamew_test2, "file_io/GetFullPathNameW/test2/paltest_getfullpathnamew_test2") -{ - WCHAR szwDotDot[] = {'.','.','/','\0'}; - WCHAR szwFileName[] = {'t','e','s','t','i','n','g','.','t','m','p','\0'}; - - DWORD dwRc = 0; - WCHAR szwReturnedPath[_MAX_DIR+1]; - WCHAR szwFullFileName[_MAX_DIR+1]; - char *szReturnedPath; - char *szFileName; - LPWSTR pPathPtr; - HANDLE hFile = NULL; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* change the directory */ - if (!SetCurrentDirectoryW(szwDotDot)) - { - Fail("ERROR: SetCurrentDirectoryW failed with error code %u" - " when passed \"%S\".\n", - GetLastError(), - szwDotDot); - } - - /* Initialize the receiving char buffers. - */ - memset(szwReturnedPath, 0, sizeof(szwReturnedPath)); - memset(szwFullFileName, 0, sizeof(szwFullFileName)); - - /* Create Full filename to pass, will include '..\' - * as a pre-fix. */ - wcscat(szwFullFileName, szwDotDot); - wcscat(szwFullFileName, szwFileName); - - /* Convert wide char strings to multibyte, to us - * incase of error messages.*/ - szFileName = convertC(szwFileName); - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameW(szwFullFileName, - _MAX_DIR, - szwReturnedPath, - &pPathPtr); - - szReturnedPath = convertC(szwReturnedPath); - - if (dwRc == 0) - { - Trace("ERROR :%ld: Failed to get path to \"%s\".\n", - GetLastError(), - szReturnedPath); - free(szReturnedPath); - free(szFileName); - Fail(""); - } - - /* - * The returned value should be the parent directory with the - * file name appended. - */ - hFile = CreateFileW(szwReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Trace("ERROR :%ld: CreateFileW failed to create file \"%s\".\n", - GetLastError(), - szReturnedPath); - free(szFileName); - free(szReturnedPath); - Fail(""); - } - - /* Close the handle to the create file.*/ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: Failed to close handle hFile=0x%lx.\n", - GetLastError(), - hFile); - goto terminate; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileW(szwReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Trace("ERROR :%ld: CreateFileW succeeded to create file " - "\"%s\", that already existed.\n", - GetLastError(), - szReturnedPath); - goto terminate; - } - - /* Verify that the returned filename is the same as the supplied. - */ - if (wcsncmp(pPathPtr, szwFileName, wcslen(szwFileName)) != 0) - { - Trace("ERROR : Returned filename is not equal to \"%s\".\n", - szFileName); - goto terminate; - } - -terminate: - /* Delete the create file. - */ - if (DeleteFileW(szwFullFileName) != TRUE) - { - Trace("ERROR :%ld: DeleteFileW failed to delete \"%s\".\n", - szFileName, - GetLastError()); - free(szFileName); - free(szReturnedPath); - Fail(""); - } - - free(szFileName); - free(szReturnedPath); - - /* Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test3/test3.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test3/test3.cpp deleted file mode 100644 index c6b83a2c217d94..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test3/test3.cpp +++ /dev/null @@ -1,239 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test3.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameW API. -** GetFullPathW will be passed a directory that contains '..'. -** Example: test_directory\level1\..\testing.tmp. -** To add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** The test will create a file with in the parent directory -** to verify that the returned directory is valid. -** -** Depends: SetCurrentDirectory, -** CreateDirectory, -** strcat, -** memset, -** CreateFile, -** CloseHandle, -** strcmp, -** DeleteFileW, -** RemoveDirectory. -** - -** -**===================================================================*/ -#define UNICODE -#include - -PALTEST(file_io_GetFullPathNameW_test3_paltest_getfullpathnamew_test3, "file_io/GetFullPathNameW/test3/paltest_getfullpathnamew_test3") -{ -#ifdef WIN32 - const WCHAR szSeparator[] = {'\\','\\','\0'}; -#else - const WCHAR szSeparator[] = {'/','/','\0'}; -#endif - - const WCHAR szDotDot[] = {'.','.','\0'}; - const WCHAR szFileName[] = {'t','e','s','t','i','n','g','.','t','m','p','\0'}; - - DWORD dwRc = 0; - - WCHAR szReturnedPath[_MAX_DIR+1]; - WCHAR szFullFileName[_MAX_DIR+1]; - WCHAR szDirectory[256]; - WCHAR szCreatedDir[] = {'t','e','s','t','_','d','i','r','\0'}; - WCHAR szCreatedNextDir[] = {'l','e','v','e','l','1','\0'}; - - LPWSTR pPathPtr; - HANDLE hFile = NULL; - BOOL bRetVal = FAIL; - - /* Initialize the PAL. - */ - if ( 0 != PAL_Initialize(argc,argv) ) - { - return (FAIL); - } - - /* Initialize the buffer. - */ - memset( szDirectory, '\0', 256 * sizeof(szDirectory[0]) ); - - /* Change the current working directory. - */ - if ( !SetCurrentDirectoryW(szDotDot) ) - { - Fail("ERROR: SetCurrentDirectoryA failed with error code %u " - "when passed \"%S\".\n", - GetLastError(), - szDotDot); - } - - /* Create the path to the next level of directory to create. - */ - wcscat(szDirectory, szCreatedDir); /* test_dir */ - - - /* Create a test directory. - */ - if (!CreateDirectoryW(szDirectory, NULL)) - { - Fail("ERROR:%u: Unable to create directories \"%S\".\n", - GetLastError(), - szDirectory); - } - - /* Create the path to the next level of directory to create. - */ - wcscat(szDirectory, szSeparator); /* / */ - wcscat(szDirectory, szCreatedNextDir); /* /level1 */ - - /* Create a test directory. - */ - if (!CreateDirectoryW(szDirectory, NULL)) - { - Trace("ERROR:%u: Unable to create directories \"%S\".\n", - GetLastError(), - szDirectory); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* Initialize the receiving char buffers. - */ - memset(szReturnedPath, 0, sizeof(szReturnedPath)); - memset(szFullFileName, 0, sizeof(szFullFileName)); - - /* Create Full filename to pass, will include '..\' - * in the middle of the path. - */ - wcscat(szFullFileName, szCreatedDir); /*test_dir */ - wcscat(szFullFileName, szSeparator); /*test_dir/ */ - wcscat(szFullFileName, szCreatedNextDir);/*test_dir/level1 */ - wcscat(szFullFileName, szSeparator); /*test_dir/level1/ */ - wcscat(szFullFileName, szDotDot); /*test_dir/level1/.. */ - wcscat(szFullFileName, szSeparator); /*test_dir/level1/../ */ - wcscat(szFullFileName, szFileName); /*test_dir/level1/../testing.tmp */ - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameW(szFullFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - if (dwRc == 0) - { - Trace("ERROR :%ld: GetFullPathNameW failed to " - "retrieve the path of \"%S\".\n", - GetLastError(), - szFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* The returned value should be the parent directory with the - * file name appended. */ - hFile = CreateFileW(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Trace("ERROR :%ld: CreateFileA failed to create \"%S\".\n", - GetLastError(), - szReturnedPath); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Close the handle to the created file. - */ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n", - GetLastError()); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileW(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Trace("ERROR :%ld: CreateFileA succeeded to create file " - "\"%S\", that already existed.\n", - GetLastError(), - szFullFileName); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Verify that the returned filename is the same as the supplied. - */ - if (wcscmp(pPathPtr, szFileName) != 0) - { - Trace("ERROR : Returned filename \"%s\" is not equal to " - "supplied filename \"%s\".\n", - pPathPtr, - szFileName); - bRetVal = FAIL; - goto cleanUpThree; - } - - /* Successful test. - */ - bRetVal = PASS; - -cleanUpThree: - - /* Delete the create file. - */ - if (DeleteFileW(szReturnedPath) != TRUE) - { - Fail("ERROR :%ld: DeleteFileA failed to delete \"%S\".\n", - GetLastError(), - szFileName); - } - -cleanUpTwo: - - /* Remove the empty directory. - */ - if (!RemoveDirectoryW(szDirectory)) - { - Fail("ERROR:%u: Unable to remove directory \"%S\".\n", - GetLastError(), - szCreatedDir); - } - -cleanUpOne: - - /* Remove the empty directory. - */ - if (!RemoveDirectoryW(szCreatedDir)) - { - Fail("ERROR:%u: Unable to remove directory \"%s\".\n", - GetLastError(), - szCreatedDir); - } - - /* Terminate the PAL.*/ - PAL_TerminateEx(bRetVal); - return bRetVal; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test4/test4.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test4/test4.cpp deleted file mode 100644 index 7bc7fceed80d85..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetFullPathNameW/test4/test4.cpp +++ /dev/null @@ -1,200 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test4.c -** -** Purpose: Tests the PAL implementation of the GetFullPathNameW API. -** GetFullPathNameW will be passed a directory that begins with '..'. -** Example: ..\test_directory\testing.tmp. -** To add to this test, we will also call SetCurrentDirectory to -** ensure this is handled properly. -** The test will create a file with in the parent directory -** to verify that the returned directory is valid. -** -** Depends: SetCurrentDirectory, -** CreateDirectory, -** strcat, -** memset, -** CreateFile, -** CloseHandle, -** strcmp, -** DeleteFileW, -** RemoveDirectory. -** - -** -**===================================================================*/ -#define UNICODE -#include - -PALTEST(file_io_GetFullPathNameW_test4_paltest_getfullpathnamew_test4, "file_io/GetFullPathNameW/test4/paltest_getfullpathnamew_test4") -{ -#ifdef WIN32 - const WCHAR szSeparator[] = {'\\','\\','\0'}; -#else - const WCHAR szSeparator[] = {'/','/','\0'}; -#endif - - const WCHAR szDotDot[] = {'.','.','\0'}; - const WCHAR szFileName[] = {'t','e','s','t','i','n','g','.','t','m','p','\0'}; - - DWORD dwRc = 0; - - WCHAR szReturnedPath[_MAX_DIR+1]; - WCHAR szFullFileName[_MAX_DIR+1]; - WCHAR szDirectory[256]; - WCHAR szCreatedDir[] = {'t','e','s','t','_','d','i','r','\0'}; - - LPWSTR pPathPtr; - HANDLE hFile = NULL; - BOOL bRetVal = FAIL; - - /* Initialize the PAL. - */ - if (0 != PAL_Initialize(argc,argv)) - { - return (FAIL); - } - - /* Initialize the buffer. - */ - memset(szDirectory, '\0', 256 * sizeof(szDirectory[0])); - - /* Create the path to the next level of directory to create. - */ - wcscat(szDirectory, szDotDot); /* .. */ - wcscat(szDirectory, szSeparator); /* ../ */ - wcscat(szDirectory, szCreatedDir); /* ../test_directory */ - - /* Create a test directory. - */ - if (!CreateDirectoryW(szDirectory, NULL)) - { - Fail("ERROR:%u: Unable to create directories \"%S\".\n", - GetLastError(), - szDirectory); - } - - /* Initialize the receiving char buffers. - */ - memset(szReturnedPath, 0, sizeof(szFullFileName)); - memset(szFullFileName, 0, sizeof(szFullFileName)); - - /* Create Full filename to pass, will include '..\' - * in the middle of the path. - */ - wcscat( szFullFileName, szDotDot ); /* .. */ - wcscat( szFullFileName, szSeparator ); /* ../ */ - wcscat( szFullFileName, szCreatedDir ); /* ../test_directory */ - wcscat( szFullFileName, szSeparator ); /* ../test_directory/ */ - wcscat( szFullFileName, szFileName ); /* ../test_directory/testing.tmp */ - - /* Get the full path to the filename. - */ - dwRc = GetFullPathNameW(szFullFileName, - _MAX_DIR, - szReturnedPath, - &pPathPtr); - if (dwRc == 0) - { - Trace("ERROR :%ld: GetFullPathName failed to " - "retrieve the path of \"%S\".\n", - GetLastError(), - szFileName); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* The returned value should be the parent directory with the - * file name appended. */ - hFile = CreateFileW(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Trace("ERROR :%ld: CreateFileA failed to create \"%S\".\n", - GetLastError(), - szReturnedPath); - bRetVal = FAIL; - goto cleanUpOne; - } - - /* Close the handle to the created file. - */ - if (CloseHandle(hFile) != TRUE) - { - Trace("ERROR :%ld: CloseHandle failed close hFile=0x%lx.\n", - GetLastError()); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Verify that the file was created, attempt to create - * the file again. */ - hFile = CreateFileW(szReturnedPath, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_NEW, - FILE_ATTRIBUTE_NORMAL, - NULL); - if ((hFile != INVALID_HANDLE_VALUE) && - (GetLastError() != ERROR_ALREADY_EXISTS)) - { - Trace("ERROR :%ld: CreateFileA succeeded to create file " - "\"%S\", that already existed.\n", - GetLastError(), - szFullFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Verify that the returned filename is the same as the supplied. - */ - if (wcscmp(pPathPtr, szFileName) != 0) - { - Trace("ERROR : Returned filename \"%S\" is not equal to " - "supplied filename \"%S\".\n", - pPathPtr, - szFileName); - bRetVal = FAIL; - goto cleanUpTwo; - } - - /* Successful test. - */ - bRetVal = PASS; - -cleanUpTwo: - - /* Delete the create file. - */ - if (DeleteFileW(szReturnedPath) != TRUE) - { - Fail("ERROR :%ld: DeleteFileA failed to delete \"%S\".\n", - GetLastError(), - szFileName); - } - -cleanUpOne: - - /* Remove the empty directory. - */ - if (!RemoveDirectoryW(szDirectory)) - { - Fail("ERROR:%u: Unable to remove directory \"%s\".\n", - GetLastError(), - szCreatedDir); - } - - /* Terminate the PAL.*/ - PAL_TerminateEx(bRetVal); - return bRetVal; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test1/GetStdHandle.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test1/GetStdHandle.cpp deleted file mode 100644 index ac68e4938c0ba4..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test1/GetStdHandle.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetStdHandle.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetStdHandle function. -** -** -**===================================================================*/ - -#include - - -PALTEST(file_io_GetStdHandle_test1_paltest_getstdhandle_test1, "file_io/GetStdHandle/test1/paltest_getstdhandle_test1") -{ - HANDLE hFile = NULL; - DWORD dwBytesWritten = 0; - DWORD dwFileType; - BOOL bRc = FALSE; - const char* szText = "this is a test of GetStdHandle\n"; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* - * attempt to get an invalid handle - */ - hFile = GetStdHandle(-2); - if (hFile != INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE " - "returned an invalid handle.\n"); - } - - - /* - * test the STD_INPUT_HANDLE handle - */ - hFile = GetStdHandle(STD_INPUT_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE " - "returned an invalid handle.\n"); - } - - /* an attempt to write to the input handle should fail */ - /* I don't know how to automate a read from the input handle */ - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwBytesWritten, NULL); - if (bRc != FALSE) - { - Fail("GetStdHandle: ERROR -> WriteFile was able to write to " - "STD_INPUT_HANDLE when it should have failed.\n"); - } - - - /* - * test the STD_OUTPUT_HANDLE handle - */ - hFile = GetStdHandle(STD_OUTPUT_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_OUTPUT_HANDLE " - "returned an invalid handle.\n"); - } - - /* try to write to the output handle */ - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwBytesWritten, NULL); - if (bRc != TRUE) - { - Fail("GetStdHandle: ERROR -> WriteFile failed to write to " - "STD_OUTPUT_HANDLE with the error %ld\n", - GetLastError()); - } - - - /* test the STD_ERROR_HANDLE handle */ - hFile = GetStdHandle(STD_ERROR_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_ERROR_HANDLE " - "returned an invalid handle.\n"); - } - - /* try to write to the error handle */ - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwBytesWritten, NULL); - if (bRc != TRUE) - { - Fail("GetStdHandle: ERROR -> WriteFile failed to write to " - "STD_ERROR_HANDLE with the error %ld\n", - GetLastError()); - } - - /* check to see if we can CloseHandle works on the STD_ERROR_HANDLE */ - if (!CloseHandle(hFile)) - { - Fail("GetStdHandle: ERROR -> CloseHandle failed. GetLastError " - "returned %u.\n", - GetLastError()); - } - - /* try to write to the closed error handle */ - bRc = WriteFile(hFile, - szText, - (DWORD)strlen(szText), - &dwBytesWritten, - NULL); - if (bRc) - { - Fail("GetStdHandle: ERROR -> WriteFile was able to write to the closed" - " STD_ERROR_HANDLE handle.\n"); - } - - - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp b/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp deleted file mode 100644 index 65879cd9153c6d..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp +++ /dev/null @@ -1,78 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: GetStdHandle.c (test 2) -** -** Purpose: Smoke Tests the PAL implementation of the GetStdHandle function. -** -** -**===================================================================*/ - -#include - - -PALTEST(file_io_GetStdHandle_test2_paltest_getstdhandle_test2, "file_io/GetStdHandle/test2/paltest_getstdhandle_test2") -{ - HANDLE hFile = NULL; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* - * attempt to get an invalid handle - */ - hFile = GetStdHandle(-2); - if (hFile != INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE " - "returned an invalid handle.\n"); - } - - - /* - * test the STD_INPUT_HANDLE handle - */ - hFile = GetStdHandle(STD_INPUT_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE " - "returned an invalid handle.\n"); - } - - - /* - * test the STD_OUTPUT_HANDLE handle - */ - hFile = GetStdHandle(STD_OUTPUT_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_OUTPUT_HANDLE " - "returned an invalid handle.\n"); - } - - /* test the STD_ERROR_HANDLE handle */ - hFile = GetStdHandle(STD_ERROR_HANDLE); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("GetStdHandle: ERROR -> A request for the STD_ERROR_HANDLE " - "returned an invalid handle.\n"); - } - - - /* check to see if we can CloseHandle works on the STD_ERROR_HANDLE */ - if (!CloseHandle(hFile)) - { - Fail("GetStdHandle: ERROR -> CloseHandle failed. GetLastError " - "returned %u.\n", - GetLastError()); - } - - - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/NonReadableFile.txt b/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/NonReadableFile.txt deleted file mode 100644 index a8a940627d1326..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/NonReadableFile.txt +++ /dev/null @@ -1 +0,0 @@ -this is a test \ No newline at end of file diff --git a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/ReadFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/ReadFile.cpp deleted file mode 100644 index 822531db4b8717..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test1/ReadFile.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: ReadFile.c (test 1) -** -** Purpose: Tests the PAL implementation of the ReadFile function. -** This test will attempt to read from a NULL handle and from -** a file without read permissions set. -** -** -**===================================================================*/ - -#include - - -PALTEST(file_io_ReadFile_test1_paltest_readfile_test1, "file_io/ReadFile/test1/paltest_readfile_test1") -{ - HANDLE hFile = NULL; - DWORD dwByteCount = 0; - DWORD dwBytesRead = 0; - BOOL bRc = FALSE; - char szBuffer[256]; - char* szNonReadableFile = {"nonreadablefile.txt"}; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - memset(szBuffer, 0, 256); - - /* Read from a NULL handle - */ - - bRc = ReadFile(hFile, szBuffer, 20, &dwBytesRead, NULL); - - if (bRc == TRUE) - { - Fail("ReadFile: ERROR -> Able to read from a NULL handle\n"); - } - - - /* Read from a file without read permissions - */ - -#if WIN32 - -#else - /* attempt to read from the unreadable file - * open a file without read permissions - */ - hFile = CreateFile(szNonReadableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - dwByteCount = GetLastError(); - Fail("ReadFile: ERROR -> Unable to create file \"%s\".\n", - szNonReadableFile); - } - - bRc = ReadFile(hFile, szBuffer, 20, &dwBytesRead, NULL); - - if (bRc == TRUE) - { - Fail("ReadFile: ERROR -> Able to read from a file without read " - "permissions\n"); - } -#endif - - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test2/ReadFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test2/ReadFile.cpp deleted file mode 100644 index c7664448f965e8..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test2/ReadFile.cpp +++ /dev/null @@ -1,195 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: ReadFile.c (test 2) -** -** Purpose: Tests the PAL implementation of the ReadFile function. -** Creates a test file and performs an array of read tests. -** -** Assumes successful: -** CreateFile -** CloseHandle -** WriteFile -** GetLastError -** -**===================================================================*/ - - -#include -#include - - -#define szStringTest "The quick fox jumped over the lazy dog's back.\0" -#define szEmptyString "" -#define szReadableFile "Readable.txt" -#define szResultsFile "Results.txt" - -//Previously number of tests was 6, now 4 refer VSW 312690 -#define NOOFTESTS 4 - -char *readBuffer_ReadFile_test2; - -BOOL validateResults_ReadFile_test2(const char* szString, // string read - DWORD dwByteCount, // amount requested - DWORD dwBytesRead) // amount read -{ - // were the correct number of bytes read? - if (dwBytesRead > dwByteCount) - { - Trace("bytes read > bytes asked for\n"); - return FALSE; - } - if (dwBytesRead != strlen(szString)) - { - Trace("bytes read != length of read string\n"); - return FALSE; - } - - // - // compare results - // - - if (memcmp(szString, szStringTest, dwBytesRead) != 0) - { - Trace("read = %s string = %s", szString, szStringTest); - return FALSE; - } - - return TRUE; -} - -BOOL readTest_ReadFile_test2(DWORD dwByteCount, char cResult) -{ - HANDLE hFile = NULL; - DWORD dwBytesRead; - BOOL bRc = FALSE; - - // open the test file - hFile = CreateFile(szReadableFile, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - if(hFile == INVALID_HANDLE_VALUE) - { - Trace("ReadFile: ERROR -> Unable to open file \"%s\".\n", - szReadableFile); - return FALSE; - } - - SYSTEM_INFO sysInfo; - GetSystemInfo(&sysInfo); - long pageSize = sysInfo.dwPageSize; - memset(readBuffer_ReadFile_test2, 0, pageSize); - - bRc = ReadFile(hFile, readBuffer_ReadFile_test2, dwByteCount, &dwBytesRead, NULL); - - if (bRc == FALSE) - { - // if it failed, was it supposed to fail? - if (cResult == '1') - { - Trace("\nbRc = %d\n", bRc); - Trace("readBuffer = [%s] dwByteCount = %d dwBytesRead = %d\n", readBuffer_ReadFile_test2, dwByteCount, dwBytesRead); - Trace("cresult = 1\n"); - Trace("getlasterror = %d\n", GetLastError()); - CloseHandle(hFile); - return FALSE; - } - } - else - { - CloseHandle(hFile); - // if it passed, was it supposed to pass? - if (cResult == '0') - { - Trace("cresult = 0\n"); - return FALSE; - } - else - { - return (validateResults_ReadFile_test2(readBuffer_ReadFile_test2, dwByteCount, dwBytesRead)); - } - } - - CloseHandle(hFile); - return TRUE; -} - -PALTEST(file_io_ReadFile_test2_paltest_readfile_test2, "file_io/ReadFile/test2/paltest_readfile_test2") -{ - HANDLE hFile = NULL; - - SYSTEM_INFO sysInfo; - GetSystemInfo(&sysInfo); - long pageSize = sysInfo.dwPageSize; - long bufferSize = 2 * pageSize; - - DWORD dwByteCount[] = { 0, - 10, - (DWORD)strlen(szStringTest), - (DWORD)pageSize - // Commented out two negative test cases : Refer VSW 312690 - // 2 * pageSize, - // -1 - }; - - char szResults[] = "1111"; // Was "111100": Refer VSW 312690 - int i; - BOOL bRc = FALSE; - DWORD dwBytesWritten = 0; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - readBuffer_ReadFile_test2 = (char*)mmap(NULL, bufferSize, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); - if (readBuffer_ReadFile_test2 == MAP_FAILED) - { - Fail("mmap failed for readBuffer\n"); - return FAIL; - } - - if (mprotect(&readBuffer_ReadFile_test2[pageSize], pageSize, PROT_NONE) != 0) - { - Fail("mprotect failed for readBuffer\n"); - return FAIL; - } - - // create the test file - hFile = CreateFile(szReadableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("ReadFile: ERROR -> Unable to create file \"%s\" (%d).\n", - szReadableFile, GetLastError()); - } - - bRc = WriteFile(hFile, szStringTest, strlen(szStringTest), &dwBytesWritten, NULL); - CloseHandle(hFile); - - - for (i = 0; i< NOOFTESTS; i++) - { - bRc = readTest_ReadFile_test2(dwByteCount[i], szResults[i]); - if (bRc != TRUE) - { - Fail("ReadFile: ERROR -> Failed on test[%d]\n", i); - } - } - - munmap(readBuffer_ReadFile_test2, bufferSize); - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test3/ReadFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test3/ReadFile.cpp deleted file mode 100644 index e9762552d90e2b..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test3/ReadFile.cpp +++ /dev/null @@ -1,183 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: ReadFile.c (test 3) -** -** Purpose: Tests the PAL implementation of the ReadFile function. -** Creates a test file and performs an array of sequential read -** tests. -** -** Assumes successful: -** CreateFile -** CloseHandle -** memset -** WriteFile -** CreateFile -** CloseHandle -** GetLastError -** -** -**===================================================================*/ - -#include - -#define szStringTest "The quick fox jumped over the lazy dog's back.\0" -#define szEmptyString "" -#define szReadableFile "Readable.txt" -#define szResultsFile "Results.txt" - - -BOOL validateResults_ReadFile_test3(const char* szString, // string read - DWORD dwByteCount, // amount requested - DWORD dwBytesRead) // amount read -{ - // were the correct number of bytes read? - if (dwBytesRead > dwByteCount) - { - Trace("bytes read > bytes asked for\n"); - return FALSE; - } - if (dwBytesRead != strlen(szString)) - { - Trace("bytes read != length of read string\n"); - return FALSE; - } - - - // - // compare results - // - - if (memcmp(szString, szStringTest, dwByteCount) != 0) - { - Trace("read = %s string = %s", szString, szStringTest); - return FALSE; - } - - return TRUE; -} - - - - -BOOL readTest_ReadFile_test3(DWORD dwByteCount, char cResult) -{ - HANDLE hFile = NULL; - DWORD dwBytesRead = 0; - DWORD dwTotal = 0; - DWORD dwRequested = 0; - BOOL bRc = FALSE; - char szString[100]; - char* szPtr = szString; - int i = 0; - - // open the test file - hFile = CreateFile(szReadableFile, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - if(hFile == INVALID_HANDLE_VALUE) - { - Trace("ReadFile: ERROR -> Unable to open file \"%s\".\n", - szReadableFile); - return FALSE; - } - - memset(szString, 0, 100); - - for (i = 0; i < 5; i++) - { - bRc = ReadFile(hFile, szPtr, dwByteCount, &dwBytesRead, NULL); - szPtr += dwByteCount; - dwTotal += dwBytesRead; - dwRequested += dwByteCount; - } - - if (bRc == FALSE) - { - // if it failed, was it supposed to fail? - if (cResult == '1') - { - Trace("\nbRc = %d\n", bRc); - Trace("szString = [%s] dwByteCount = %d dwBytesRead = %d\n", - szString, - dwByteCount, - dwBytesRead); - Trace ("cresult = 1\n"); - Trace ("getlasterror = %d\n", GetLastError()); - CloseHandle(hFile); - return FALSE; - } - } - else - { - CloseHandle(hFile); - // if it passed, was it supposed to pass? - if (cResult == '0') - { - Trace ("cresult = 0\n"); - return FALSE; - } - else - { - return (validateResults_ReadFile_test3(szString, dwRequested, dwTotal)); - } - } - - CloseHandle(hFile); - return TRUE; -} - - - -PALTEST(file_io_ReadFile_test3_paltest_readfile_test3, "file_io/ReadFile/test3/paltest_readfile_test3") -{ - HANDLE hFile = NULL; - DWORD dwByteCount[4] = {0, 1, 2, 3}; - char szResults[4] = {'1', '1', '1', '1'}; - int i; - BOOL bRc = FALSE; - DWORD dwBytesWritten = 0; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - - // create the test file - hFile = CreateFile(szReadableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("ReadFile: ERROR -> Unable to create file \"%s\".\n", - szReadableFile); - } - - bRc = WriteFile(hFile, szStringTest, strlen(szStringTest), - &dwBytesWritten, - NULL); - CloseHandle(hFile); - - for (i = 0; i < 4; i++) - { - bRc = readTest_ReadFile_test3(dwByteCount[i], szResults[i]); - if (bRc != TRUE) - { - Fail("ReadFile: ERROR -> Failed on test[%d]\n", i); - } - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test4/readfile.cpp b/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test4/readfile.cpp deleted file mode 100644 index cef8ec291b3d2e..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/ReadFile/test4/readfile.cpp +++ /dev/null @@ -1,146 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: ReadFile.c (test 4) -** -** Purpose: Tests the PAL implementation of the ReadFile function. -** Creates a file and writes a small string to it, attempt -** to read many more characters that exist. The returned -** number of chars should be the amount written originally -** not the number requested. -** -** -**===================================================================*/ -#include - -PALTEST(file_io_ReadFile_test4_paltest_readfile_test4, "file_io/ReadFile/test4/paltest_readfile_test4") -{ - HANDLE hFile = NULL; - DWORD dwBytesWritten; - BOOL bRc = FALSE; - char szBuffer[256]; - DWORD dwBytesRead = 0; - int szRequestSize = 256; - char testFile[] = "testfile.tmp"; - char testString[] = "people stop and stare"; - DWORD res = 0; - - /* Initialize the PAL. - */ - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* Initialize the buffer. - */ - memset(szBuffer, 0, 256); - - /* Create a file to test with. - */ - hFile = CreateFile(testFile, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_WRITE|FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR:%u: Unable to create file \"%s\".\n", - GetLastError(), - testFile); - } - - /* Write to the File handle. - */ - bRc = WriteFile(hFile, - testString, - strlen(testString), - &dwBytesWritten, - NULL); - - if (bRc == FALSE) - { - Trace("ERROR:%u: Unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - if (!CloseHandle(hFile)) - { - Trace("ERROR:%u%: Unable to close handle 0x%lx.\n", - GetLastError(), - hFile); - } - Fail(""); - } - - /* Set the file pointer to beginning of file. - */ - res = SetFilePointer(hFile, 0, NULL, FILE_BEGIN); - - if( (res == INVALID_SET_FILE_POINTER) && - (GetLastError() != NO_ERROR)) - { - Trace("ERROR:%u: Unable to set file pointer to the beginning of file.", - GetLastError()); - - if (!CloseHandle(hFile)) - { - Trace("ERROR:%u%: Unable to close handle 0x%lx.\n", - GetLastError(), - hFile); - } - Fail(""); - } - - - /* Attempt to read 256 characters from a file - * that does not contain that many. - */ - bRc = ReadFile(hFile, - szBuffer, - szRequestSize, - &dwBytesRead, - NULL); - - if (bRc == FALSE) - { - Trace("ERROR:%u: Unable to read from file handle 0x%lx.\n", - GetLastError(), - hFile); - if (!CloseHandle(hFile)) - { - Trace("ERROR:%u%: Unable to close handle 0x%lx.\n", - GetLastError(), - hFile); - } - Fail(""); - } - - /* Confirm the number of bytes read with that requested. - */ - if (dwBytesRead != strlen(testString)) - { - Trace("ERROR: The number of bytes read \"%d\" is not equal to the " - "number originally written \"%d\" to the file.\n", - dwBytesRead, - strlen(testString)); - if (!CloseHandle(hFile)) - { - Trace("ERROR:%u%: Unable to close handle 0x%lx.\n", - GetLastError(), - hFile); - } - Fail(""); - } - - /* Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/file_io/SearchPathW/test1/SearchPathW.cpp b/src/coreclr/pal/tests/palsuite/file_io/SearchPathW/test1/SearchPathW.cpp deleted file mode 100644 index 4b851a46385955..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SearchPathW/test1/SearchPathW.cpp +++ /dev/null @@ -1,193 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SearchPathW.c -** -** Purpose: Tests the PAL implementation of the SearchFileW function. -** -** -** TODO: Write a test where complete path is passed (say c:\?) -**===================================================================*/ -//SearchPath -// -//The SearchPath function searches for the specified file in the specified path. -// -// -//DWORD SearchPath( -// LPCTSTR lpPath, -// LPCTSTR lpFileName, -// LPCTSTR lpExtension, -// DWORD nBufferLength, -// LPTSTR lpBuffer, -// LPTSTR* lpFilePart -//); -// -//Parameters -//lpPath -//[in] Pointer to a null-terminated string that specifies the path to be searched for the file. If this parameter is NULL, the function searches for a matching file in the following directories in the following sequence: -//The directory from which the application loaded. -//The current directory. -//The system directory. Use the GetSystemDirectory function to get the path of this directory. -//The 16-bit system directory. There is no function that retrieves the path of this directory, but it is searched. -//The Windows directory. Use the GetWindowsDirectory function to get the path of this directory. -//The directories that are listed in the PATH environment variable. - -//lpFileName -//[in] Pointer to a null-terminated string that specifies the name of the file to search for. - -//lpExtension -//[in] Pointer to a null-terminated string that specifies an extension to be added to the file name when searching for the file. The first character of the file name extension must be a period (.). The extension is added only if the specified file name does not end with an extension. -//If a file name extension is not required or if the file name contains an extension, this parameter can be NULL. -// -//nBufferLength -//[in] Size of the buffer that receives the valid path and file name, in TCHARs. - -//lpBuffer -//[out] Pointer to the buffer that receives the path and file name of the file found. - -//lpFilePart -//[out] Pointer to the variable that receives the address (within lpBuffer) of the last component of the valid path and file name, which is the address of the character immediately following the final backslash (\) in the path. - -//Return Values -//If the function succeeds, the value returned is the length, in TCHARs, of the string copied to the buffer, not including the terminating null character. If the return value is greater than nBufferLength, the value returned is the size of the buffer required to hold the path. -// -//If the function fails, the return value is zero. To get extended error information, call GetLastError. - - -#include -#define szDir "." - -#define szNoFileName "333asdf" -#define szNoFileNameExt ".x77t" - -#define szFileNameExists "searchpathw" -#define szFileNameExtExists ".c" - -#define szFileNameExistsWithExt "searchpathw.c" - -char fileloc_SearchPathW_test1[MAX_PATH]; - -void removeFileHelper_SearchPathW_test1(LPSTR pfile, int location) -{ - FILE *fp; - fp = fopen( pfile, "r"); - - if (fp != NULL) - { - if(fclose(fp)) - { - Fail("ERROR: Failed to close the file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location); - } - - if(!DeleteFileA(pfile)) - { - Fail("ERROR: Failed to delete file [%s], Error Code [%d], location [%d]\n", pfile, GetLastError(), location); - } - else - { - // Trace("Success: deleted file [%S], Error Code [%d], location [%d]\n", wfile, GetLastError(), location); - } - } - -} - -void RemoveAll_SearchPathW_test1() -{ - removeFileHelper_SearchPathW_test1(fileloc_SearchPathW_test1, 1); -} - -PALTEST(file_io_SearchPathW_test1_paltest_searchpathw_test1, "file_io/SearchPathW/test1/paltest_searchpathw_test1") -{ - - WCHAR* lpPath = NULL; - WCHAR* lpFileName = NULL; - WCHAR* lpExtension = NULL; - DWORD nBufferLength = 0; - WCHAR lpBuffer[MAX_PATH]; - WCHAR** lpFilePart = NULL; - DWORD error = 0; - DWORD result = 0; - - HANDLE hsearchfile; - char fname[_MAX_FNAME]; - char ext[_MAX_EXT]; - char fullPath[_MAX_DIR]; - char drive[_MAX_DRIVE]; - char dir[_MAX_DIR]; - - - if(0 != (PAL_Initialize(argc, argv))) - { - return FAIL; - } - - /* Initialize the buffer. - */ - memset(fullPath, 0, _MAX_DIR); - - if (GetTempPathA(_MAX_DIR, fullPath) == 0) - { - Fail("ERROR: GetTempPathA failed to get a path\n"); - } - - memset(fileloc_SearchPathW_test1, 0, MAX_PATH); - sprintf_s(fileloc_SearchPathW_test1, ARRAY_SIZE(fileloc_SearchPathW_test1), "%s%s", fullPath, szFileNameExistsWithExt); - - RemoveAll_SearchPathW_test1(); - - hsearchfile = CreateFileA(fileloc_SearchPathW_test1, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, 0); - - if (hsearchfile == NULL) - { - Trace("ERROR[%ul]: couldn't create %s\n", GetLastError(), fileloc_SearchPathW_test1); - return FAIL; - } - - CloseHandle(hsearchfile); - - // - // find a file that doesn't exist - // - ZeroMemory( lpBuffer, sizeof(lpBuffer)); - lpPath = convert((LPSTR)fullPath); - lpFileName = convert((LPSTR)szNoFileName); - lpExtension = NULL; - - if( SearchPathW( lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, lpFilePart) != 0 ){ - error = GetLastError(); - free(lpPath); - free(lpFileName); - Fail ("SearchPathW: ERROR1 -> Found invalid file[%s][%s][%s][%d]\n", lpPath, szNoFileName, szNoFileNameExt, error); - } - - free(lpPath); - free(lpFileName); - - // - // find a file that exists, when path is mentioned explicitly - // - ZeroMemory( lpBuffer, sizeof(lpBuffer)); - lpPath = convert((LPSTR)fullPath); - lpFileName = convert((LPSTR)szFileNameExistsWithExt); - lpExtension = NULL; - - result = SearchPathW( lpPath, lpFileName, lpExtension, nBufferLength, lpBuffer, lpFilePart); - - if( result == 0 ){ - error = GetLastError(); - free(lpPath); - free(lpFileName); - Fail ("SearchPathW: ERROR2 -> Did not Find valid file[%s][%s][%d]\n", lpPath, szFileNameExistsWithExt, error); - } - - free(lpPath); - free(lpFileName); - - RemoveAll_SearchPathW_test1(); - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test1/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test1/SetFilePointer.cpp deleted file mode 100644 index b19f174d57d9be..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test1/SetFilePointer.cpp +++ /dev/null @@ -1,122 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 1) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Set the file pointer using a NULL handle and other invalid -** options. -** -** -**===================================================================*/ - -#include - - - - - -PALTEST(file_io_SetFilePointer_test1_paltest_setfilepointer_test1, "file_io/SetFilePointer/test1/paltest_setfilepointer_test1") -{ - HANDLE hFile = NULL; - DWORD dwByteCount = 0; - DWORD dwOffset = 25; - DWORD dwRc = 0; - BOOL bRc = FALSE; - char buffer[100]; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* set the file pointer on a NULL file handle */ - dwRc = SetFilePointer(NULL, dwOffset, NULL, FILE_BEGIN); - if (dwRc != INVALID_SET_FILE_POINTER) - { - Fail("SetFilePointer: ERROR -> Call to SetFilePointer succeeded " - "with a NULL pointer\n"); - } - - - /* create a test file without proper permission */ - hFile = CreateFile(szTextFile, - 0, - 0, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - /* ReadFile fails as expected */ - bRc = ReadFile(hFile, buffer, 1, &dwByteCount, NULL); - if (bRc != FALSE) - { - Trace("SetFilePointer: ERROR -> ReadFile was successful when it was " - "expected to fail\n"); - if (!CloseHandle(hFile)) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the file pointer before the beginning of the file */ - dwRc = SetFilePointer(hFile, -1, NULL, FILE_BEGIN); - if (dwRc != INVALID_SET_FILE_POINTER) - { - Trace("SetFilePointer: ERROR -> Was able to move the pointer before " - "the beginning of the file.\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test2/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test2/SetFilePointer.cpp deleted file mode 100644 index cc2cc6dc82f6ca..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test2/SetFilePointer.cpp +++ /dev/null @@ -1,313 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 2) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_BEGIN option -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - -const char * const szText = - "The quick brown fox jumped over the lazy dog's back."; - - - -PALTEST(file_io_SetFilePointer_test2_paltest_setfilepointer_test2, "file_io/SetFilePointer/test2/paltest_setfilepointer_test2") -{ - HANDLE hFile = NULL; - DWORD dwByteCount = 0; - DWORD dwRc = 0; - BOOL bRc = FALSE; - char szBuffer[100]; - const char *szPtr; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwByteCount, NULL); - if (bRc == FALSE) - { - Trace("SetFilePointer: ERROR -> Unable to write to file \"%s\".\n", - szTextFile); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - - /* move -1 from beginning which should fail */ - dwRc = SetFilePointer(hFile, -1, NULL, FILE_BEGIN); - if ((dwRc != INVALID_SET_FILE_POINTER) || - (GetLastError() == ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Succeeded to move the pointer " - "before the beginning of the file.\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the file pointer 0 bytes from the beginning and verify */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_BEGIN); - if (dwRc != 0) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the pointer ahead in the file and verify */ - dwRc = SetFilePointer(hFile, 20, NULL, FILE_BEGIN); - if (dwRc != 20) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - memset(szBuffer, 0, 100); - bRc = ReadFile(hFile, szBuffer, (DWORD)strlen(szText)-20, &dwByteCount, - NULL); - if ((bRc != TRUE) || (dwByteCount != strlen(szText)-20)) - { - Trace("SetFilePointer: ERROR -> ReadFile failed to read correctly"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - "\"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - "\"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - szPtr = szText + 20; - if (strcmp(szPtr, szBuffer) != 0) - { - Trace("SetFilePointer: ERROR -> Apparently failed to move the " - "pointer properly\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - /* move the file pointer back to the beginning and verify */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_BEGIN); - if (dwRc != 0) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - memset(szBuffer, 0, 100); - bRc = ReadFile(hFile, szBuffer, (DWORD)strlen(szText), &dwByteCount, - NULL); - if ((bRc != TRUE) || (dwByteCount != strlen(szText))) - { - Trace("SetFilePointer: ERROR -> ReadFile failed to read correctly"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - if (strcmp(szText, szBuffer) != 0) - { - Trace("SetFilePointer: ERROR -> Failed to return the pointer " - "properly to the beginning of the file\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - /* return the pointer to the beginning of the file */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_BEGIN); - if (dwRc != 0) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* set the pointer past the end of the file and verify */ - dwRc = SetFilePointer(hFile, (DWORD)strlen(szText)+20, NULL, FILE_BEGIN); - if ((dwRc == INVALID_SET_FILE_POINTER) && (GetLastError() != ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Failed to move pointer past EOF.\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test3/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test3/SetFilePointer.cpp deleted file mode 100644 index 8c230996322a0a..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test3/SetFilePointer.cpp +++ /dev/null @@ -1,349 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 3) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_CURRENT option -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - -const char* const szText = - "The quick brown fox jumped over the lazy dog's back."; - - - -PALTEST(file_io_SetFilePointer_test3_paltest_setfilepointer_test3, "file_io/SetFilePointer/test3/paltest_setfilepointer_test3") -{ - HANDLE hFile = NULL; - DWORD dwByteCount = 0; - DWORD dwRc = 0; - BOOL bRc = FALSE; - char szBuffer[100]; - const char* szPtr; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwByteCount, NULL); - if (bRc == FALSE) - { - Trace("SetFilePointer: ERROR -> Unable to write to file \"%s\".\n", - szTextFile); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* reset the pointer to the beginning */ - if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER) - { - if (GetLastError() != ERROR_SUCCESS) - { - Trace("SetFilePointer: ERROR -> Unable to reset the pointer to the " - "beginning of the file"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - /* move -1 from beginning which should fail */ - dwRc = SetFilePointer(hFile, -1, NULL, FILE_CURRENT); - if ((dwRc != INVALID_SET_FILE_POINTER) || - (GetLastError() == ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Succeeded to move the pointer " - "before the beginning of the file.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - - /* move the file pointer 0 bytes from the beginning and verify */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); - if (dwRc != 0) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the pointer ahead in the file and verify */ - dwRc = SetFilePointer(hFile, 20, NULL, FILE_CURRENT); - if (dwRc != 20) - { - Trace("SetFilePointer: ERROR -> Asked to move 20 bytes from the " - "beginning of the file but moved %ld bytes.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - memset(szBuffer, 0, 100); - bRc = ReadFile(hFile, szBuffer, (DWORD)strlen(szText)-20, &dwByteCount, - NULL); - if ((bRc != TRUE) || (dwByteCount != strlen(szText)-20)) - { - Trace("SetFilePointer: ERROR -> ReadFile failed to read correctly"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - szPtr = szText + 20;; - if (strcmp(szPtr, szBuffer) != 0) - { - Trace("SetFilePointer: ERROR -> Apparently failed to move the" - " pointer properly\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - - /* get the current file pointer position (should be 52) */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_CURRENT); - if (dwRc != 52) - { - Trace("SetFilePointer: ERROR -> Asked for current position." - " Should be 52 but was %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - - /* move the pointer backwards in the file and verify */ - dwRc = SetFilePointer(hFile, -10, NULL, FILE_CURRENT); - if (dwRc != 42) - { - Trace("SetFilePointer: ERROR -> Asked to move back 10 bytes from the" - "end of the file but moved it to position %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - memset(szBuffer, 0, 100); - bRc = ReadFile(hFile, szBuffer, 10, &dwByteCount, NULL); - if ((bRc != TRUE) || (dwByteCount != 10)) - { - Trace("SetFilePointer: ERROR -> ReadFile failed to read correctly"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - szPtr = szText + 42; - if (strcmp(szPtr, szBuffer) != 0) - { - Trace("SetFilePointer: ERROR -> Apparently failed to move the" - " pointer properly\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - /* - * the file pointer is currently at the end of the file so... - * set the pointer past the end of the file and verify - */ - dwRc = SetFilePointer(hFile, 20, NULL, FILE_CURRENT); - if ((dwRc == INVALID_SET_FILE_POINTER) && (GetLastError() != ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Failed to move pointer past EOF.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - if (SetFilePointer(hFile, 0, NULL, FILE_CURRENT) != strlen(szText)+20) - { - Trace("SetFilePointer: ERROR -> Failed to move pointer past" - " EOF.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test4/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test4/SetFilePointer.cpp deleted file mode 100644 index 4695d7ecba86a4..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test4/SetFilePointer.cpp +++ /dev/null @@ -1,215 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 4) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_END option -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - -const char* szText = "The quick brown fox jumped over the lazy dog's back."; - - - -PALTEST(file_io_SetFilePointer_test4_paltest_setfilepointer_test4, "file_io/SetFilePointer/test4/paltest_setfilepointer_test4") -{ - HANDLE hFile = NULL; - DWORD dwByteCount = 0; - DWORD dwOffset = 0; - DWORD dwRc = 0; - BOOL bRc = FALSE; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - bRc = WriteFile(hFile, szText, (DWORD)strlen(szText), &dwByteCount, NULL); - if (bRc == FALSE) - { - Trace("SetFilePointer: ERROR -> Unable to write to file \"%s\".\n", - szTextFile); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - - /* - * move -1 from the end - */ - dwRc = SetFilePointer(hFile, -1, NULL, FILE_END); - if (dwRc == INVALID_SET_FILE_POINTER) - { - if (GetLastError() != ERROR_SUCCESS) - { - Trace("SetFilePointer: ERROR -> Failed to move the pointer " - "back one character from EOF.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - else - { - /* verify */ - if ((dwRc != strlen(szText)-1)) - { - Trace("SetFilePointer: ERROR -> Failed to move the pointer" - " -1 bytes from EOF\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - /* - * move the file pointer 0 bytes from the end and verify - */ - dwRc = SetFilePointer(hFile, 0, NULL, FILE_END); - if (dwRc != strlen(szText)) - { - Trace("SetFilePointer: ERROR -> Asked to move 0 bytes from the " - "end of the file. Function returned %ld instead of 52.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* - * move the pointer past the end of the file and verify - */ - dwRc = SetFilePointer(hFile, 20, NULL, FILE_END); - if (dwRc != strlen(szText)+20) - { - Trace("SetFilePointer: ERROR -> Asked to move 20 bytes past the " - "end of the file. Function returned %ld instead of %d.\n", - dwRc, - strlen(szText)+20); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* - * move the pointer backwards to before the start of the file and verify - */ - - dwOffset = (dwRc + 20) * -1; - dwRc = SetFilePointer(hFile, dwOffset, NULL, FILE_END); - if ((dwRc != INVALID_SET_FILE_POINTER) || - (GetLastError() == ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Was able to move the pointer " - "to before the beginning of the file.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test5/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test5/SetFilePointer.cpp deleted file mode 100644 index 71680a60e064e0..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test5/SetFilePointer.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 5) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_BEGIN option using the high word parameter -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - - - -PALTEST(file_io_SetFilePointer_test5_paltest_setfilepointer_test5, "file_io/SetFilePointer/test5/paltest_setfilepointer_test5") -{ - HANDLE hFile = NULL; - DWORD dwOffset = 1; - LONG dwHighWord = 1; - DWORD dwReturnedOffset = 0; - DWORD dwReturnedHighWord = 0; - DWORD dwRc = 0; - DWORD dwError = 0; - BOOL bRc = FALSE; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - dwError = GetLastError(); - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n with " - "error %ld", - szTextFile, - GetLastError()); - } - - - - /* move -1 from beginning which should fail */ - dwRc = SetFilePointer(hFile, -1, &dwHighWord, FILE_BEGIN); - if (dwRc != INVALID_SET_FILE_POINTER) - { - Trace("SetFilePointer: ERROR -> Succeeded to move the pointer " - "before the beginning of the file using the high word.\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* set the pointer past the end of the file and verify */ - dwRc = SetFilePointer(hFile, dwOffset, &dwHighWord, FILE_BEGIN); - if ((dwRc == INVALID_SET_FILE_POINTER) && - ((dwError = GetLastError()) != ERROR_SUCCESS)) - { - Trace("SetFilePointer: ERROR -> Failed to move pointer past EOF.\n"); - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test6/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test6/SetFilePointer.cpp deleted file mode 100644 index f128133c4344d7..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test6/SetFilePointer.cpp +++ /dev/null @@ -1,172 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 6) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_CURRENT option with high order support -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - - - - -PALTEST(file_io_SetFilePointer_test6_paltest_setfilepointer_test6, "file_io/SetFilePointer/test6/paltest_setfilepointer_test6") -{ - HANDLE hFile = NULL; - DWORD dwOffset = 0; - LONG dwHighOrder = 0; - DWORD dwReturnedOffset = 0; - LONG dwReturnedHighOrder = 0; - DWORD dwRc = 0; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - - /* move waaaay before the beginning which should fail */ - dwHighOrder = -1; - dwOffset = 0; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT); - if (dwRc != INVALID_SET_FILE_POINTER) - { - Trace("SetFilePointer: ERROR -> Succeeded to move the pointer " - "before the beginning of the file.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the pointer ahead in the file and verify */ - dwHighOrder = 1; - dwOffset = 10; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT); - if ((dwRc != 10) || (dwHighOrder != 1)) - { - Trace("SetFilePointer: ERROR -> Asked to move 2GB plus 10 bytes from " - "the beginning of the file but didn't.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* - * move the pointer backwards in the file and verify - */ - dwOffset = 0; - dwHighOrder = -1; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_CURRENT); - if (dwRc != 10) - { - Trace("SetFilePointer: ERROR -> Asked to move back to 10 bytes from the" - "beginning of the file but moved it to position %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - dwReturnedHighOrder = 0; - dwRc = SetFilePointer(hFile, 0, &dwReturnedHighOrder, FILE_CURRENT); - if (dwRc != 10) - { - Trace("SetFilePointer: ERROR -> Asked for current position. " - "Should be 10 but was %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - - /* clean up, clean up, everybody do their share... */ - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test7/SetFilePointer.cpp b/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test7/SetFilePointer.cpp deleted file mode 100644 index 64796bc54fdbbc..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/SetFilePointer/test7/SetFilePointer.cpp +++ /dev/null @@ -1,203 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: SetFilePointer.c (test 7) -** -** Purpose: Tests the PAL implementation of the SetFilePointer function. -** Test the FILE_END option with high order support -** -** Assumes Successful: -** CreateFile -** ReadFile -** WriteFile -** strlen -** CloseHandle -** strcmp -** GetFileSize -** -** -**===================================================================*/ - -#include - - - - -PALTEST(file_io_SetFilePointer_test7_paltest_setfilepointer_test7, "file_io/SetFilePointer/test7/paltest_setfilepointer_test7") -{ - HANDLE hFile = NULL; - DWORD dwOffset = 0; - LONG dwHighOrder = 0; - DWORD dwReturnedOffset = 0; - LONG dwReturnedHighOrder = 0; - DWORD dwRc = 0; - - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create a test file */ - hFile = CreateFile(szTextFile, - GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("SetFilePointer: ERROR -> Unable to create file \"%s\".\n", - szTextFile); - } - - - /* move -1 from beginning which should fail */ - dwHighOrder = -1; - dwOffset = 0; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_END); - if (dwRc != INVALID_SET_FILE_POINTER) - { - Trace("SetFilePointer: ERROR -> Succeeded to move the pointer " - "before the beginning of the file.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* move the pointer ahead in the file and verify */ - dwHighOrder = 1; - dwOffset = 10; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_END); - if ((dwRc != 10) || (dwHighOrder != 1)) - { - Trace("SetFilePointer: ERROR -> Asked to move 4GB plus 10 bytes from " - "the beginning of the file but didn't.\n"); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - dwReturnedHighOrder = 0; - dwReturnedOffset = SetFilePointer(hFile, 0, &dwReturnedHighOrder, FILE_CURRENT); - if ((dwReturnedOffset != dwOffset) || (dwReturnedHighOrder != dwHighOrder)) - { - Trace("SetFilePointer: ERROR -> Asked to move far past the " - "end of the file. low order sent: %ld low order returned: %ld " - "high order sent: %ld high order returned: %ld", - dwOffset, dwReturnedOffset, - dwHighOrder, dwReturnedHighOrder); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - DWORD bytesWritten = 0; - char ch = ' '; - if (!WriteFile(hFile, &ch, 1, &bytesWritten, NULL)) - { - Trace("WriteFile: ERROR\n"); - PAL_TerminateEx(FAIL); - return FAIL; - } - - /* - * move the pointer backwards in the file and verify - */ - dwOffset = -1; - dwHighOrder = -1; - dwRc = SetFilePointer(hFile, dwOffset, &dwHighOrder, FILE_END); - if (dwRc != 10) - { - Trace("SetFilePointer: ERROR -> Asked to move back to 10 bytes from the" - "beginning of the file but moved it to position %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - else - { - /* verify results */ - dwReturnedHighOrder = 0; - dwRc = SetFilePointer(hFile, 0, &dwReturnedHighOrder, FILE_CURRENT); - if (dwRc != 10) - { - Trace("SetFilePointer: ERROR -> Asked for current position. " - "Should be 10 but was %ld.\n", dwRc); - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file" - " \"%s\".\n", szTextFile); - } - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file" - " \"%s\".\n", szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - } - - - /* clean up, clean up, everybody do their share... */ - if (CloseHandle(hFile) != TRUE) - { - Trace("SetFilePointer: ERROR -> Unable to close file \"%s\".\n", - szTextFile); - if (!DeleteFileA(szTextFile)) - { - Trace("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - PAL_TerminateEx(FAIL); - return FAIL; - } - - if (!DeleteFileA(szTextFile)) - { - Fail("SetFilePointer: ERROR -> Unable to delete file \"%s\".\n", - szTextFile); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test1/WriteFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test1/WriteFile.cpp deleted file mode 100644 index be2017c6d523bb..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test1/WriteFile.cpp +++ /dev/null @@ -1,112 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: WriteFile.c (test 1) -** -** Purpose: Tests the PAL implementation of the WriteFile function. -** This test will attempt to write to a NULL handle and a -** read-only file -** -** -**===================================================================*/ - -#include - - -#define szStringTest "The quick fox jumped over the lazy dog's back." -#define szReadOnlyFile "ReadOnly.txt" - -void do_cleanup_WriteFile_test1() -{ - BOOL bRc = FALSE; - bRc = DeleteFileA(szReadOnlyFile); - if (bRc != TRUE) - { - Fail ("DeleteFileA: ERROR[%ld]: During Cleanup: Couldn't delete WriteFile's" - " \"ReadOnly.txt\"\n", GetLastError()); - } - -} - -PALTEST(file_io_WriteFile_test1_paltest_writefile_test1, "file_io/WriteFile/test1/paltest_writefile_test1") -{ - HANDLE hFile = NULL; - DWORD dwBytesWritten; - BOOL bRc = FALSE; - DWORD last_error; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - // - // Write to a NULL handle - // - - bRc = WriteFile(hFile, szStringTest, 20, &dwBytesWritten, NULL); - - if (bRc == TRUE) - { - last_error = GetLastError(); - Fail("WriteFile: ERROR[%ld] -> Able to write to a NULL handle\n", last_error); - } - - - // - // Write to a file with read-only permissions - // - - // create a file without write permissions - hFile = CreateFile(szReadOnlyFile, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - last_error = GetLastError(); - Fail("WriteFile: ERROR[%ld] -> Unable to create file \"%s\".\n", - last_error, szReadOnlyFile); - } - - if ((last_error = chmod(szReadOnlyFile, S_IRUSR | S_IRGRP | S_IROTH)) != 0) - { - Trace("WriteFile: ERROR[%ld] -> Unable to make the file read-only.\n", last_error); - do_cleanup_WriteFile_test1(); - Fail("WriteFile: ERROR[%ld] -> Unable to make the file read-only.\n", last_error); - } - - bRc = WriteFile(hFile, szStringTest, 20, &dwBytesWritten, NULL); - if (bRc == TRUE) - { last_error = GetLastError(); - Trace("WriteFile: ERROR[%ld] -> Able to write to a read-only file.\n", last_error); - do_cleanup_WriteFile_test1(); - Fail("WriteFile: ERROR[%ld] -> Able to write to a read-only file.\n", last_error); - } - - - bRc = CloseHandle(hFile); - if (bRc != TRUE) - { last_error = GetLastError(); - Trace("WriteFile: ERROR[%ld] -> Unable to close file \"%s\".\n", last_error, szReadOnlyFile); - do_cleanup_WriteFile_test1(); - Fail("WriteFile: ERROR -> Unable to close file \"%s\".\n", - szReadOnlyFile); - } - - //To delete file need to make it normal - if ((last_error = chmod(szReadOnlyFile, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) != 0) - { - Fail("WriteFile: ERROR[%ld] -> Unable to make the file attribute NORMAL.\n", last_error); - - } - do_cleanup_WriteFile_test1(); - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/Results.txt b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/Results.txt deleted file mode 100644 index 1c4c37885a5dc1..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/Results.txt +++ /dev/null @@ -1 +0,0 @@ -0011100111 \ No newline at end of file diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/WriteFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/WriteFile.cpp deleted file mode 100644 index f7bdb5941e84e8..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test2/WriteFile.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: WriteFile.c (test 2) -** -** Purpose: Tests the PAL implementation of the WriteFile function. -** Creates a number of files and writes different amounts of -** data and verifies the writes. -** -** -**===================================================================*/ - - -#include -#include - - - -char* writeBuffer_WriteFile_test2; -#define szWritableFile "Writeable.txt" -#define szResultsFile "Results.txt" - -#ifndef PAGESIZE -#define PAGESIZE 4096 -#endif // PAGESIZE - -BOOL writeTest_WriteFile_test2(DWORD dwByteCount, DWORD dwBytesWrittenResult, BOOL bResult) -{ - HANDLE hFile = NULL; - DWORD dwBytesWritten; - BOOL bRc = FALSE; - - /* create the test file */ - remove(szWritableFile); - hFile = CreateFile(szWritableFile, GENERIC_WRITE, FILE_SHARE_WRITE, - NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Trace("WriteFile: ERROR -> Unable to create file \"%s\".\n", - szWritableFile); - return FALSE; - } - - bRc = WriteFile(hFile, writeBuffer_WriteFile_test2, dwByteCount, &dwBytesWritten, NULL); - CloseHandle(hFile); - - if ((bRc != bResult) || (dwBytesWrittenResult != dwBytesWritten)) - { - Trace("WriteFile returned BOOL:%d and dwWritten:%d what we do expect is" - " BOOL:%d and dwWritten:%d\n", bRc, dwBytesWritten, bResult, - dwBytesWrittenResult); - return FALSE; - } - - return TRUE; -} - -PALTEST(file_io_WriteFile_test2_paltest_writefile_test2, "file_io/WriteFile/test2/paltest_writefile_test2") -{ - const char * testString = "The quick fox jumped over the lazy dog's back."; - const DWORD testStringLen = (DWORD)strlen(testString); - - DWORD dwByteCount[4] = {(DWORD)-1, 10, testStringLen, 0}; - DWORD dwByteWritten[4] = {0, 10, testStringLen, 0}; - BOOL bResults[] = {FALSE, TRUE, TRUE, TRUE}; - - const int BUFFER_SIZE = 2 * PAGESIZE; - int j; - BOOL bRc = FALSE; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - writeBuffer_WriteFile_test2 = (char*)mmap(NULL, BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); - if (writeBuffer_WriteFile_test2 == MAP_FAILED) - { - Fail("mmap failed for writeBuffer\n"); - return FAIL; - } - - memset((void*) writeBuffer_WriteFile_test2, '.', BUFFER_SIZE); - strcpy(writeBuffer_WriteFile_test2, testString); - - if (mprotect(&writeBuffer_WriteFile_test2[PAGESIZE], PAGESIZE, PROT_NONE) != 0) - { - Fail("mprotect failed for writeBuffer\n"); - return FAIL; - } - - for (j = 0; j< 4; j++) - { - bRc = writeTest_WriteFile_test2(dwByteCount[j], dwByteWritten[j], bResults[j]); - if (bRc != TRUE) - { - Fail("WriteFile: ERROR -> Failed on test[%d]\n", j); - } - } - - munmap(writeBuffer_WriteFile_test2, BUFFER_SIZE); - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test3/WriteFile.cpp b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test3/WriteFile.cpp deleted file mode 100644 index ec51d5d5c88af5..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test3/WriteFile.cpp +++ /dev/null @@ -1,135 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: WriteFile.c (test 3) -** -** Purpose: Tests the PAL implementation of the WriteFile function. -** Performs multiple writes to a file and verifies the results. -** -** -**===================================================================*/ - - -#include - - -#define szStringTest "The quick fox jumped over the lazy dog's back.\0" -#define szWritableFile "writeable.txt" - - -BOOL validateResults_WriteFile_test3(const char* szString) -{ - FILE *pFile = NULL; - char szReadString[100]; - DWORD dwBytesRead; - DWORD dwStringLength = strlen(szString); - - - - memset(szReadString, 0, 100); - - /* open the file */ - pFile = fopen(szWritableFile, "r"); - if (pFile == NULL) - { - Trace("couldn't open test file\n"); - return FALSE; - } - - dwBytesRead = fread(szReadString, sizeof(char), dwStringLength, pFile); - fclose(pFile); - - if(dwBytesRead != dwStringLength) - { - Trace("dwbyteread != string length\n"); - return FALSE; - } - - if (strcmp(szReadString, szString)) - { - Trace("read = %s string = %s", szReadString, szString); - return FALSE; - } - return TRUE; -} - - - - -BOOL writeTest_WriteFile_test3(const char* szString) -{ - HANDLE hFile = NULL; - DWORD dwBytesWritten; - BOOL bRc = FALSE; - BOOL bAllPassed = TRUE; - int nStringLength = 0; - char* szPtr = NULL; - int i = 0; - - // create the test file - hFile = CreateFile(szWritableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Trace("WriteFile: ERROR -> Unable to create file \"%s\".\n", - szWritableFile); - return FALSE; - } - - nStringLength = strlen(szString); - szPtr = (char*) szString; - - for (i = 0; i < nStringLength; i++) - { - bRc = WriteFile(hFile, szPtr++, 1, &dwBytesWritten, NULL); - if ((bRc == FALSE) || (dwBytesWritten != 1)) - { - bAllPassed = FALSE; - } - } - CloseHandle(hFile); - - if (bAllPassed == FALSE) - { - Trace ("WriteFile: ERROR: Failed to write data.\n"); - return FALSE; - } - else - { - return (validateResults_WriteFile_test3(szString)); - } - - return TRUE; -} - - - - -PALTEST(file_io_WriteFile_test3_paltest_writefile_test3, "file_io/WriteFile/test3/paltest_writefile_test3") -{ - const char *pString = szStringTest; - BOOL bRc = FALSE; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - - bRc = writeTest_WriteFile_test3(pString); - if (bRc != TRUE) - { - Fail("WriteFile: ERROR -> Failed\n"); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test4/writefile.cpp b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test4/writefile.cpp deleted file mode 100644 index 34ab48103533ca..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test4/writefile.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: WriteFile.c (test 4) -** -** Purpose: Tests the PAL implementation of the WriteFile function. -** Performs multiple writes to a file at different locations -** then verifies the results with GetFileSize. -** -** dependency: -** CreateFile. -** GetFileSize. -** FlushFileBuffers -** SetFilePointer. -** CloseHandle. -** DeleteFile. -** -** -** -**===================================================================*/ - - -#include - -BOOL CleanUp_WriteFile_test4(HANDLE hFile, const char * fileName) -{ - BOOL bRc = TRUE; - if (CloseHandle(hFile) != TRUE) - { - bRc = FALSE; - Trace("WriteFile: ERROR -> Unable to close file \"%s\"," - " error: %ld.\n", fileName, GetLastError()); - } - if (!DeleteFileA(fileName)) - { - bRc = FALSE; - Trace("WriteFile: ERROR -> Unable to delete file \"%s\"," - " error: %ld.\n", fileName, GetLastError()); - } - return bRc; -} - -PALTEST(file_io_WriteFile_test4_paltest_writefile_test4, "file_io/WriteFile/test4/paltest_writefile_test4") -{ - const char* szStringTest = "1234567890"; - const char* szWritableFile = "writeable.txt"; - HANDLE hFile = NULL; - DWORD dwBytesWritten; - - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create the test file */ - hFile = CreateFile(szWritableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("WriteFile: ERROR -> Unable to create file \"%s\".\n", - szWritableFile); - } - - - /* test wtriting to the file */ - if( WriteFile(hFile, /* HANDLE handle to file */ - szStringTest, /* data buffer */ - strlen(szStringTest), /* number of bytes to write */ - &dwBytesWritten, /* number of bytes written */ - NULL) /* overlapped buffer */ - ==0) - { - Trace("WriteFile: ERROR -> Unable to write to file error: %ld \n", - GetLastError()); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - if(!FlushFileBuffers(hFile)) - { Trace("WriteFile: ERROR -> Call to FlushFile Buffers failed " - "error %ld \n",GetLastError()); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - /* check the file size */ - if(GetFileSize(hFile, NULL)!=strlen(szStringTest)) - { - Trace("WriteFile: ERROR -> writing %u chars to empty file " - "caused its size to become %u\n",strlen(szStringTest), - GetFileSize(hFile, NULL)); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - /* test writing to the file at position 5. */ - SetFilePointer( - hFile, /* handle to file */ - 0x5, /* bytes to move pointer */ - NULL, /* bytes to move pointer */ - FILE_BEGIN /* starting point */ - ); - - - if( WriteFile(hFile, /* HANDLE handle to file */ - szStringTest, /* data buffer */ - strlen(szStringTest), /* number of bytes to write */ - &dwBytesWritten, /* number of bytes written */ - NULL) /* overlapped buffer */ - ==0) - { - Trace("WriteFile: ERROR -> Unable to write to file after " - " moiving the file poiner to 5 error: %ld \n", - GetLastError()); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - - if(!FlushFileBuffers(hFile)) - { - Trace("WriteFile: ERROR -> Call to FlushFile Buffers failed " - "error %ld \n",GetLastError()); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - /* Check the file size */ - if(GetFileSize(hFile, NULL)!=(strlen(szStringTest)+5)) - { - Trace("WriteFile: ERROR -> writing %u chars to the file after " - "sitting the file pointer to 5 resulted in wrong file size; " - "Expected %u resulted %u.",strlen(szStringTest), - (strlen(szStringTest)+5),GetFileSize(hFile, NULL)); - CleanUp_WriteFile_test4(hFile,szWritableFile); - Fail(""); - } - - if (!CleanUp_WriteFile_test4(hFile,szWritableFile)) - { - Fail(""); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test5/writefile.cpp b/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test5/writefile.cpp deleted file mode 100644 index a9f1af7baa8d36..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/WriteFile/test5/writefile.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: WriteFile.c (test 5) -** -** Purpose: Tests the PAL implementation of the WriteFile function. -** Performs writing a huge file. -** -** dependency: -** CreateFile. -** GetFileSize. -** FlushFileBuffers -** CloseHandle -** DeleteFile -** -** -**===================================================================*/ - - -#include - -BOOL CleanUp_WriteFile_test5(HANDLE hFile, const char * fileName) -{ - BOOL bRc = TRUE; - if (CloseHandle(hFile) != TRUE) - { - bRc = FALSE; - Trace("WriteFile: ERROR -> Unable to close file \"%s\"," - " error: %ld.\n", fileName, GetLastError()); - } - if (!DeleteFileA(fileName)) - { - bRc = FALSE; - Trace("WriteFile: ERROR -> Unable to delete file \"%s\"," - " error: %ld.\n", fileName, GetLastError()); - } - return bRc; -} - - -PALTEST(file_io_WriteFile_test5_paltest_writefile_test5, "file_io/WriteFile/test5/paltest_writefile_test5") -{ - - HANDLE hFile = NULL; - DWORD dwBytesWritten; - const char* hugeStringTest = - "1234567890123456789012345678901234567890"; - const char* szWritableFile = "writeable.txt"; - int i =0; - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - /* create the test file */ - hFile = CreateFile(szWritableFile, - GENERIC_WRITE, - FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if(hFile == INVALID_HANDLE_VALUE) - { - Fail("WriteFile: ERROR -> Unable to create file \"%s\".\n", - szWritableFile); - } - - /* write 4000 000 chars to the file.*/ - for (i=0; i<100000;i++) - { - if( WriteFile(hFile, /* HANDLE handle to file */ - hugeStringTest, /* data buffer */ - strlen(hugeStringTest), /* number of bytes to write */ - &dwBytesWritten, /* number of bytes written */ - NULL) /* overlapped buffer */ - ==0) - { - Trace("WriteFile: ERROR -> Unable to write to file error: %ld \n", - GetLastError()); - CleanUp_WriteFile_test5(hFile,szWritableFile); - Fail(""); - - } - } - - if(!FlushFileBuffers(hFile)) - { - Trace("WriteFile: ERROR -> Call to FlushFileBuffers failed" - "error %ld \n",GetLastError()); - CleanUp_WriteFile_test5(hFile,szWritableFile); - Fail(""); - } - - /* test if the size changed properly. */ - if(GetFileSize(hFile,NULL) != 4000000) - { - Trace("WriteFile: ERROR -> file size did not change properly" - " after writing 4000 000 chars to it ( size= %u )\n", - GetFileSize(hFile,NULL)); - CleanUp_WriteFile_test5(hFile,szWritableFile); - Fail(""); - - } - - if (!CleanUp_WriteFile_test5(hFile,szWritableFile)) - { - Fail(""); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/file_io/errorpathnotfound/test1/test1.cpp b/src/coreclr/pal/tests/palsuite/file_io/errorpathnotfound/test1/test1.cpp deleted file mode 100644 index d3551a773a5ae8..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/errorpathnotfound/test1/test1.cpp +++ /dev/null @@ -1,626 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== - -** - -** Source: test1.c - -** - -** Purpose: Test the return value of GetLastError() after calling - -** some file_io functions with an invalid path. - -** - -** Functions covered by this test are: - -** CreateFileA,CreateFileW, - -** DeleteFileA and DeleteFileW. - -** -** - - - -** - -**===================================================================*/ - - - -#include - - - -PALTEST(file_io_errorpathnotfound_test1_paltest_errorpathnotfound_test1, "file_io/errorpathnotfound/test1/paltest_errorpathnotfound_test1") - -{ - - - - BOOL testPass = TRUE; - - BOOL bRc = TRUE; - - HANDLE hFile; - - - - const char* sBadFilePath = "bad/badPath.tmp"; - - const char* sBadFileName = "badName.tmp"; - - const char* sDest = "dest.tmp"; - - const WCHAR wBadFilePath[] = - - {'w','b','a','d','/','b','a', - - 'd','.','t','m','p','\0'}; - - const WCHAR wBadFileName[] = - - {'w','B','a','d','.','t','m','p','\0'}; - - const WCHAR wDest[] = - - {'w','d','e','s','t','.','t','m','p','\0'}; - - - - - - if (0 != PAL_Initialize(argc,argv)) - - { - - return FAIL; - - } - - - - - - - - /*............. Test CreateFileA..................................*/ - - - - /* test with an invalid file name */ - - hFile = CreateFileA(sBadFileName, - - 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("CreateFileA: calling GetLastError() returned [%u] " - - "while it should return [%u] for a bad File Name\n", - - GetLastError(),ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - } - - - - } - - else - - { - - Trace("CreateFileA: managed to create a file with an incorrect " - - "filename\n"); - - testPass = FALSE; - - - - if(!CloseHandle(hFile)) - - { - - Trace("CreateFileA: Call to CloseHandle failed with ErrorCode " - - "[%u]\n", GetLastError()); - - - - } - - if(!remove(sBadFileName)) - - { - - Trace("CreateFileA: Call to remove failed with ErrorCode " - - "[%u]\n", errno); - - } - - } - - - - /* test with an invalid path */ - - hFile = CreateFileA(sBadFilePath, - - 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_PATH_NOT_FOUND) - - { - - Trace("CreateFileA: calling GetLastError() returned [%u] " - - "while it should return [%u] for a bad file path name\n", - - GetLastError(), ERROR_PATH_NOT_FOUND); - - testPass = FALSE; - - } - - - - } - - else - - { - - Trace("CreateFileA: managed to create a file with an incorrect " - - "filename\n"); - - testPass = FALSE; - - /*this should not happen*/ - - if(!CloseHandle(hFile)) - - { - - Trace("CreateFileA: Call to CloseHandle Failed with ErrorCode " - - "[%u]\n", GetLastError()); - - - - } - - if(!remove(sBadFilePath)) - - { - - Trace("CreateFileA: Call to remove Failed with ErrorCode " - - "[%u]\n", errno); - - } - - } - - - - - - - - - - /*............. 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; - - } - - - - } - - else - - { - - Trace("CreateFileW: managed to create a file with an incorrect " - - "filename\n"); - - testPass = FALSE; - - - - if(!CloseHandle(hFile)) - - { - - Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode " - - "[%u]\n", GetLastError()); - - - - } - - - - if(!DeleteFileW(wBadFileName)) - - { - - Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode " - - "[%u]\n", GetLastError()); - - } - - } - - - - - - - - /* test with an invalid path */ - - hFile = CreateFileW(wBadFilePath, - - 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_PATH_NOT_FOUND) - - { - - Trace("CreateFileW: calling GetLastError() returned [%u] " - - "while it should return [%u] for a bad file path \n", - - GetLastError(), ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - } - - - - } - - else - - { - - Trace("CreateFileW: managed to create a file with an incorrect " - - "filename\n"); - - testPass = FALSE; - - - - if(!CloseHandle(hFile)) - - { - - Trace("CreateFileW: Call to CloseHandle Failed with ErrorCode " - - "[%u]\n", GetLastError()); - - - - } - - if(!DeleteFileW(wBadFilePath)) - - { - - Trace("CreateFileW: Call to DeleteFile Failed with ErrorCode " - - "[%u]\n", GetLastError()); - - } - - } - - - - - - - - /* ............. DeleteFileW..................................*/ - - - - /* test with an invalid path */ - - if(DeleteFileW(wBadFilePath)) - - { - - Trace("DeleteFileW: Call to DeleteFileW to delete a file" - - " that does not exist succeeded\n"); - - testPass = FALSE; - - - - } - - else - - { - - if(GetLastError() != ERROR_PATH_NOT_FOUND) - - { - - Trace("DeleteFileW: Call GetLastError()returned " - - "[%u] while it should return ERROR_PATH_NOT_FOUND [%u]\n", - - GetLastError(),ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - - - } - - - - } - - - - /* test with an invalid file name */ - - if(DeleteFileW(wBadFileName)) - - { - - Trace("DeleteFileW: Call to DeleteFileW to delete a file" - - " that does not exist succeeded\n"); - - testPass = FALSE; - - - - } - - else - - { - - if(GetLastError() != ERROR_FILE_NOT_FOUND) - - { - - Trace("DeleteFileW: Call GetLastError()returned [%u]" - - " while it should return ERROR_FILE_NOT_FOUND [%u]\n", - - GetLastError(),ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - - - } - - - - } - - - - - - /* ............. DeleteFileA..................................*/ - - - - /* test with an invalid path */ - - if(DeleteFileA(sBadFilePath)) - - { - - Trace("DeleteFileA: Call to DeleteFileA to delete a file" - - " that does not exist succeeded\n"); - - testPass = FALSE; - - - - } - - else - - { - - if(GetLastError() != ERROR_PATH_NOT_FOUND) - - { - - Trace("DeleteFileA: Call GetLastError() returned [%u]" - - " while it should return ERROR_PATH_NOT_FOUND [%u]\n", - - GetLastError(),ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - - - } - - - - } - - - - /* test with an invalid file name */ - - if(DeleteFileA(sBadFileName)) - - { - - Trace("DeleteFileA: Call to DeleteFileA to delete a file" - - " that does not exist succeeded\n"); - - testPass = FALSE; - - - - } - - else - - { - - if(GetLastError() != ERROR_FILE_NOT_FOUND) - - { - - Trace("DeleteFileA: Call GetLastError() returned [%u]" - - " while it should return ERROR_FILE_NOT_FOUND [%u]\n", - - GetLastError(),ERROR_FILE_NOT_FOUND); - - testPass = FALSE; - - - - } - - - - } - - - - - - - - if(! testPass) - - { - - Fail(""); - - } - - PAL_Terminate(); - - return PASS; - -} - - - diff --git a/src/coreclr/pal/tests/palsuite/file_io/gettemppatha/test1/gettemppatha.cpp b/src/coreclr/pal/tests/palsuite/file_io/gettemppatha/test1/gettemppatha.cpp deleted file mode 100644 index 07ef39bd718722..00000000000000 --- a/src/coreclr/pal/tests/palsuite/file_io/gettemppatha/test1/gettemppatha.cpp +++ /dev/null @@ -1,102 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: gettemppatha.c (test 1) -** -** Purpose: Tests the PAL implementation of the GetTempPathA function. -** -** -**===================================================================*/ - -#include - -static void SetTmpDir(CHAR path[]) -{ - DWORD result = SetEnvironmentVariableA("TMPDIR", path); - if (!result) - { - Fail("ERROR -> SetEnvironmentVariableA failed with result %d and error code %d.\n", - result, GetLastError()); - } -} - -static void SetAndCompare(CHAR tmpDirPath[], CHAR expected[]) -{ - const DWORD dwBufferLength = _MAX_DIR; - CHAR path[dwBufferLength]; - - SetTmpDir(tmpDirPath); - - DWORD dwResultLen = GetTempPathA(dwBufferLength, path); - if (dwResultLen <= 0) - { - Fail("ERROR: GetTempPathA returned %d with error code %d.\n", dwResultLen, GetLastError()); - } - if (dwResultLen >= dwBufferLength) - { - Fail("ERROR: Buffer of length %d passed to GetTempPathA was too small to hold %d chars..\n", dwBufferLength, dwResultLen); - } - if (strcmp(expected, path) != 0) - { - Fail("ERROR: GetTempPathA expected to get '%s' but instead got '%s'.\n", expected, path); - } - if (expected[dwResultLen - 1] != '/') - { - Fail("ERROR: GetTempPathA returned '%s', which should have ended in '/'.\n", path); - } -} - -static void SetAndCheckLength(CHAR tmpDirPath[], int bufferLength, int expectedResultLength) -{ - CHAR* path = (CHAR*)alloca(bufferLength); - - SetTmpDir(tmpDirPath); - DWORD dwResultLen = GetTempPathA(bufferLength, path); - - if (dwResultLen != expectedResultLength) - { - Fail("GetTempPathA(%d, %s) expected to return %d but returned %d.\n", - bufferLength, tmpDirPath?tmpDirPath:"NULL", expectedResultLength, dwResultLen); - } -} - -PALTEST(file_io_gettemppatha_test1_paltest_gettemppatha_test1, "file_io/gettemppatha/test1/paltest_gettemppatha_test1") -{ - if (0 != PAL_Initialize(argc,argv)) - { - return FAIL; - } - - SetAndCompare("/tmp", "/tmp/"); - SetAndCompare("/tmp/", "/tmp/"); - SetAndCompare("", "/tmp/"); - SetAndCompare(NULL, "/tmp/"); - SetAndCompare("/", "/"); - SetAndCompare("/var/tmp", "/var/tmp/"); - SetAndCompare("/var/tmp/", "/var/tmp/"); - SetAndCompare("~", "~/"); - SetAndCompare("~/", "~/"); - SetAndCompare(".tmp", ".tmp/"); - SetAndCompare("./tmp", "./tmp/"); - SetAndCompare("/home/someuser/sometempdir", "/home/someuser/sometempdir/"); - SetAndCompare(NULL, "/tmp/"); - - DWORD dwResultLen = GetTempPathA(0, NULL); - if (dwResultLen != 0 || GetLastError() != ERROR_INVALID_PARAMETER) - { - Fail("GetTempPath(NULL, ...) returned %d with error code %d but " - "should have failed with ERROR_INVALID_PARAMETER (%d).\n", - dwResultLen, GetLastError(), ERROR_INVALID_PARAMETER); - } - - SetAndCheckLength("abc/", 5, 4); - SetAndCheckLength("abcd", 5, 6); - SetAndCheckLength("abcde", 5, 7); - SetAndCheckLength("abcdef/", 5, 9); - SetAndCheckLength(NULL, 5, 6); - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/CreateFileMapping_neg.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/CreateFileMapping_neg.cpp deleted file mode 100644 index 061a8cfff974e8..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/CreateFileMapping_neg.cpp +++ /dev/null @@ -1,92 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemapping_neg.c -** -** Purpose: Negative test the CreateFileMapping API. -** Call CreateFileMapping to create a unnamed -** file-mapping object with PAGE_READONLY -** protection and try to map a zero length file -** in UNICODE -** -** -**============================================================*/ -#define UNICODE -#include - -PALTEST(filemapping_memmgt_CreateFileMappingW_CreateFileMapping_neg1_paltest_createfilemappingw_createfilemapping_neg1, "filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/paltest_createfilemappingw_createfilemapping_neg1") -{ - - HANDLE FileHandle; - HANDLE FileMappingHandle; - int err; - WCHAR *lpFileName = NULL; - - //Initialize the PAL environment - err = PAL_Initialize(argc, argv); - if(0 != err) - { - ExitProcess(FAIL); - } - - //conver string to a unicode one - lpFileName = convert("temp.txt"); - - - //create a file and return the file handle - FileHandle = CreateFile(lpFileName, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - //free this memory - free(lpFileName); - - if(INVALID_HANDLE_VALUE == FileHandle) - { - Fail("Failed to call CreateFile to create a file\n"); - } - - //create a unnamed file-mapping object with file handle FileHandle - //and with PAGE_READONLY protection - //try to map a file which is zero length. - FileMappingHandle = CreateFileMapping( - FileHandle, //File Handle - NULL, //not inherited - PAGE_READONLY, //access protection - 0, //high-order of object size - 0, //low-orger of object size - NULL); //unnamed object - - - if(NULL != FileMappingHandle || ERROR_FILE_INVALID != GetLastError()) - {//no error occurred - Trace("\nFailed to call CreateFileMapping API for a negative test!\n"); - err = CloseHandle(FileHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API\n"); - } - err = CloseHandle(FileMappingHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API\n"); - } - Fail(""); - } - - //close the file handle - err = CloseHandle(FileHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API\n"); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test1/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test1/CreateFileMappingW.cpp deleted file mode 100644 index 316320949a4cc5..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test1/CreateFileMappingW.cpp +++ /dev/null @@ -1,173 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 1) -** -** Purpose: Positive test the CreateFileMappingW API. -** Call CreateFileMappingW with access PAGE_READONLY. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test1_paltest_createfilemappingw_test1, "filemapping_memmgt/CreateFileMappingW/test1/paltest_createfilemappingw_test1") -{ - - HANDLE hFile; - char buf[] = "this is a test string"; - char ch[2048]; - WCHAR lpFileName[] = {'t','e','s','t','.','t','m','p','\0'}; - DWORD dwBytesWritten; - BOOL err; - int RetVal = PASS; - - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Initialize the buffers. - */ - memset(ch, 0, MAPPINGSIZE); - - /* Write to the File handle. - */ - err = WriteFile(hFile, - buf, - strlen(buf), - &dwBytesWritten, - NULL); - - if (err == FALSE) - { - Trace("ERROR: %u :unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - RetVal = FAIL; - goto CleanUpOne; - } - - /* Flush to the hard-drive. - */ - FlushFileBuffers(hFile); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READONLY, /*read and wite*/ - 0, /*high-order size*/ - 0, /*low-order size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_READ, /* access code */ - 0, /*high order offset*/ - 0, /*low order offset*/ - 0); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* Copy the MapViewOfFile to buffer, so we can - * compare with value read from file directly. - */ - memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE); - if (memcmp(ch, buf, strlen(buf))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - ch, buf); - RetVal = FAIL; - goto CleanUpThree; - } - -CleanUpThree: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewAddress) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewAddress); - RetVal = FAIL; - } - -CleanUpTwo: - - /* Close Handle to opend file mapping. - */ - if ( CloseHandle(hFileMapping) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapping); - RetVal = FAIL; - } - -CleanUpOne: - - /* Close Handle to create file mapping. - */ - if ( CloseHandle(hFile) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFile); - RetVal = FAIL; - } - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test2/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test2/CreateFileMappingW.cpp deleted file mode 100644 index efea083074bc63..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test2/CreateFileMappingW.cpp +++ /dev/null @@ -1,123 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c -** -** Purpose: Positive test the CreateFileMapping API. -** Call CreateFileMapping to create a unnamed -** file-mapping object with PAGE_READONLY -** protection and SEC_IMAGE attribute in UNICODE -** -** -**============================================================*/ -#define UNICODE -#include - -PALTEST(filemapping_memmgt_CreateFileMappingW_test2_paltest_createfilemappingw_test2, "filemapping_memmgt/CreateFileMappingW/test2/paltest_createfilemappingw_test2") -{ - - HANDLE FileHandle; - HANDLE FileMappingHandle; - int err; - WCHAR *wpFileName = NULL; - char executableFileName[256]=""; - - - //Initialize the PAL environment - err = PAL_Initialize(argc, argv); - if(0 != err) - { - ExitProcess(FAIL); - } - -#if WIN32 - sprintf_s(executableFileName, ARRAY_SIZE(executableFileName),"%s","executable.exe"); -#else - sprintf_s(executableFileName, ARRAY_SIZE(executableFileName),"%s","executable"); -#endif - - //conver string to a unicode one - wpFileName = convert(executableFileName); - - - //create a file and return the file handle - FileHandle = CreateFile(wpFileName, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - NULL); - - //free this memory - free(wpFileName); - - if(INVALID_HANDLE_VALUE == FileHandle) - { - Fail("Failed to call CreateFile to create a file\n"); - } - - //create a unnamed file-mapping object with file handle FileHandle - //and with PAGE_READONLY protection - FileMappingHandle = CreateFileMapping( - FileHandle, //File Handle - NULL, //not inherited - PAGE_READONLY|SEC_IMAGE, //access protection and section attribute - 0, //high-order of object size - 0, //low-orger of object size - NULL); //unnamed object - - - if(NULL == FileMappingHandle) - { - Trace("\nFailed to call CreateFileMapping to create a mapping object!\n"); - err = CloseHandle(FileHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API\n"); - } - Fail(""); - } - if(GetLastError() == ERROR_ALREADY_EXISTS) - { - Trace("\nFile mapping object already exists!\n"); - err = CloseHandle(FileHandle); - if(0 == err) - { - Trace("\nFailed to call CloseHandle API to close a file handle\n"); - err = CloseHandle(FileMappingHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API to close a mapping object handle\n"); - } - Fail(""); - } - err = CloseHandle(FileMappingHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API to close a mapping object handle\n"); - } - Fail(""); - } - err = CloseHandle(FileMappingHandle); - if(0 == err) - { - Trace("\nFailed to call CloseHandle API to close a mapping object handle\n"); - err = CloseHandle(FileHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API to close a file handle\n"); - } - Fail(""); - } - err = CloseHandle(FileHandle); - if(0 == err) - { - Fail("\nFailed to call CloseHandle API to close a file handle\n"); - } - - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test3/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test3/CreateFileMappingW.cpp deleted file mode 100644 index 409e829718e9df..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test3/CreateFileMappingW.cpp +++ /dev/null @@ -1,155 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 3) -** -** Purpose: Positive test the CreateFileMappingW API. -** Call CreateFileMapping with access PAGE_READWRITE. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test3_paltest_createfilemappingw_test3, "filemapping_memmgt/CreateFileMappingW/test3/paltest_createfilemappingw_test3") -{ - - HANDLE hFile; - char buf[] = "this is a test string"; - char ch[2048]; - WCHAR lpFileName[] = {'t','e','s','t','.','t','m','p','\0'}; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - int RetVal = PASS; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Initialize the buffers. - */ - memset(ch, 0, MAPPINGSIZE); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and wite*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_ALL_ACCESS, /* access code */ - 0, /*high order offset*/ - 0, /*low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* Write to the Map view. - */ - memcpy(lpMapViewAddress, buf, strlen(buf)); - - /* Read from the Map view. - */ - memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE); - - /* Copy the MapViewOfFile to buffer, so we can - * compare with value read from file directly. - */ - if (memcmp(ch, buf, strlen(buf))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - ch, buf); - RetVal = FAIL; - goto CleanUpThree; - } - -CleanUpThree: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewAddress) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewAddress); - RetVal = FAIL; - } - -CleanUpTwo: - - /* Close Handle to opend file mapping. - */ - if ( CloseHandle(hFileMapping) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapping); - RetVal = FAIL; - } - -CleanUpOne: - - /* Close Handle to create file mapping. - */ - if ( CloseHandle(hFile) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFile); - RetVal = FAIL; - } - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test4/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test4/CreateFileMappingW.cpp deleted file mode 100644 index 1ac6815542a36e..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test4/CreateFileMappingW.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 4) -** -** Purpose: Positive test the CreateFileMappingW API. -** Call CreateFileMappingW with access PAGE_WRITECOPY. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test4_paltest_createfilemappingw_test4, "filemapping_memmgt/CreateFileMappingW/test4/paltest_createfilemappingw_test4") -{ - - HANDLE hFile; - char buf[] = "this is a test string"; - char ch[2048]; - WCHAR lpFileName[] = {'t','e','s','t','.','t','m','p','\0'}; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - int RetVal = PASS; - int err; - DWORD dwBytesWritten; - - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Write to the File handle. - */ - err = WriteFile(hFile, - buf, - strlen(buf), - &dwBytesWritten, - NULL); - - if (err == FALSE) - { - Trace("ERROR: %u :unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - RetVal = FAIL; - goto CleanUpOne; - } - - /* Flush to the hard-drive. - */ - FlushFileBuffers(hFile); - - /* Initialize the buffers. - */ - memset(ch, 0, MAPPINGSIZE); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_WRITECOPY protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_WRITECOPY, /*write copy*/ - 0, /*high-order size*/ - 0, /*low-order size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_COPY, /* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - 0); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* Write to the Map view.3 - */ - memcpy(lpMapViewAddress, buf, strlen(buf)); - - /* Read from the Map view. - */ - memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE); - - /* Copy the MapViewOfFile to buffer, so we can - * compare with value read from file directly. - */ - if (memcmp(ch, buf, strlen(buf))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - ch, buf); - RetVal = FAIL; - goto CleanUpThree; - } - -CleanUpThree: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewAddress) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewAddress); - RetVal = FAIL; - } - -CleanUpTwo: - - /* Close Handle to opend file mapping. - */ - if ( CloseHandle(hFileMapping) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapping); - RetVal = FAIL; - } - -CleanUpOne: - - /* Close Handle to create file mapping. - */ - if ( CloseHandle(hFile) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFile); - RetVal = FAIL; - } - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test5/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test5/CreateFileMappingW.cpp deleted file mode 100644 index 098f7a09a0a71d..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test5/CreateFileMappingW.cpp +++ /dev/null @@ -1,193 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 5) -** -** Purpose: Positive test the CreateFileMappingW API. -** Test CreateFileMappingW to a "swap" handle with -** access PAGE_READONLY. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test5_paltest_createfilemappingw_test5, "filemapping_memmgt/CreateFileMappingW/test5/paltest_createfilemappingw_test5") -{ - HANDLE SWAP_HANDLE = ((VOID *)(-1)); - char testString[] = "this is a test string"; - WCHAR lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'}; - int RetVal = FAIL; - char results[2048]; - - HANDLE hFileMapRO; - HANDLE hFileMapRW; - LPVOID lpMapViewRO; - LPVOID lpMapViewRW; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Initialize the buffers. - */ - memset(results, 0, MAPPINGSIZE); - - /* Create a named file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapRW = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read only*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - lpObjectName); /*named object*/ - - if(NULL == hFileMapRW) - { - Fail("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewRW = MapViewOfFile( - hFileMapRW, - FILE_MAP_ALL_ACCESS, /* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRW) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - - hFileMapRO = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_READONLY, /*read and write*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - lpObjectName); /*named object*/ - - if(NULL == hFileMapRO) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewRO = MapViewOfFile( - hFileMapRO, - FILE_MAP_READ, /* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRO) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpThree; - } - - /* Write the test string to the Map view. - */ - memcpy(lpMapViewRW, testString, strlen(testString)); - - /* Read from the second Map view. - */ - memcpy(results, (LPCSTR)lpMapViewRO, MAPPINGSIZE); - - /* Verify the contents of the file mapping, - * by comparing what was written to what was read. - */ - if (memcmp(results, testString, strlen(testString))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - results, - testString); - RetVal = FAIL; - goto CleanUpFour; - } - - /* Test was successful. - */ - RetVal = PASS; - -CleanUpFour: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRO) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRO); - RetVal = FAIL; - } - -CleanUpThree: - - /* Close Handle to opend file mapping. - */ - if ( CloseHandle(hFileMapRO) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapRO); - RetVal = FAIL; - } - - -CleanUpTwo: - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRW) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRW); - RetVal = FAIL; - } - - -CleanUpOne: - - /* Close Handle to opend file mapping. - */ - if ( CloseHandle(hFileMapRW) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapRW); - RetVal = FAIL; - } - - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test6/CreateFileMappingW.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test6/CreateFileMappingW.cpp deleted file mode 100644 index 615d261214966e..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test6/CreateFileMappingW.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 6) -** -** Purpose: Positive test the CreateFileMappingW API. -** Test CreateFileMappingW to a "swap" handle with -** access PAGE_READWRITE. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test6_paltest_createfilemappingw_test6, "filemapping_memmgt/CreateFileMappingW/test6/paltest_createfilemappingw_test6") -{ - HANDLE SWAP_HANDLE = ((VOID *)(-1)); - char testString[] = "this is a test string"; - WCHAR lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'}; - char results[2048]; - int RetVal = PASS; - - HANDLE hFileMapRW; - LPVOID lpMapViewRW; - LPVOID lpMapViewRW2; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Initialize the buffers. - */ - memset(results, 0, MAPPINGSIZE); - - /* Create a named file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapRW = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read write*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - lpObjectName); /*named object*/ - - if(NULL == hFileMapRW) - { - Fail("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - } - - /* Create a map view of the READWRITE file mapping. - */ - lpMapViewRW = MapViewOfFile( - hFileMapRW, - FILE_MAP_ALL_ACCESS,/* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRW) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewRW2 = MapViewOfFile( - hFileMapRW, - FILE_MAP_ALL_ACCESS, /* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRW2) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* Write the test string to the Map view. - */ - memcpy(lpMapViewRW, testString, strlen(testString)); - - /* Read from the second Map view. - */ - memcpy(results, (LPCSTR)lpMapViewRW2, MAPPINGSIZE); - - /* Verify the contents of the file mapping, - * by comparing what was written to what was read. - */ - if (memcmp(results, testString, strlen(testString))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - results, - testString); - RetVal = FAIL; - goto CleanUpThree; - } - - /* Test successful. - */ - RetVal = PASS; - -CleanUpThree: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRW2) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRW2); - RetVal = FAIL; - } - -CleanUpTwo: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRW) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRW); - RetVal = FAIL; - } - - -CleanUpOne: - - /* Close Handle to create file mapping. - */ - if ( CloseHandle(hFileMapRW) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapRW); - RetVal = FAIL; - } - - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test7/createfilemapping.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test7/createfilemapping.cpp deleted file mode 100644 index 48c2361faddb38..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test7/createfilemapping.cpp +++ /dev/null @@ -1,164 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 7) -** -** Purpose: Positive test the CreateFileMappingW API. -** Test CreateFileMappingW to a "swap" handle with -** access PAGE_READWRITE. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test7_paltest_createfilemappingw_test7, "filemapping_memmgt/CreateFileMappingW/test7/paltest_createfilemappingw_test7") -{ - HANDLE SWAP_HANDLE = ((VOID *)(-1)); - char testString[] = "this is a test string"; - WCHAR lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'}; - char results[2048]; - int RetVal = PASS; - - HANDLE hFileMapRW; - LPVOID lpMapViewRW; - LPVOID lpMapViewRO; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Initialize the buffers. - */ - memset(results, 0, MAPPINGSIZE); - - /* Create a named file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapRW = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read write*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - lpObjectName); /*unnamed object*/ - - if(NULL == hFileMapRW) - { - Fail("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - } - - /* Create a map view to the READWRITE file mapping. - */ - lpMapViewRW = MapViewOfFile( - hFileMapRW, - FILE_MAP_ALL_ACCESS,/* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRW) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpOne; - } - - - /* Create a map view to the READWRITE file mapping. - */ - lpMapViewRO = MapViewOfFile( - hFileMapRW, - FILE_MAP_READ, /* access code */ - 0, /* high order offset*/ - 0, /* low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewRO) - { - Trace("ERROR:%u: Failed to call MapViewOfFile " - "API to map a view of file!\n", - GetLastError()); - RetVal = FAIL; - goto CleanUpTwo; - } - - /* Write the test string to the Map view. - */ - memcpy(lpMapViewRW, testString, strlen(testString)); - - /* Read from the second Map view. - */ - memcpy(results, (LPCSTR)lpMapViewRO, MAPPINGSIZE); - - /* Verify the contents of the file mapping, - * by comparing what was written to what was read. - */ - if (memcmp(results, testString, strlen(testString))!= 0) - { - Trace("ERROR: MapViewOfFile not equal to file contents " - "retrieved \"%s\", expected \"%s\".\n", - results, - testString); - RetVal = FAIL; - goto CleanUpThree; - } - - /* Test successful. - */ - RetVal = PASS; - -CleanUpThree: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRO) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRO); - RetVal = FAIL; - } - -CleanUpTwo: - - /* Unmap the view of file. - */ - if ( UnmapViewOfFile(lpMapViewRW) == FALSE ) - { - Trace("ERROR:%u: Failed to UnmapViewOfFile of \"%0x%lx\".\n", - GetLastError(), - lpMapViewRW); - RetVal = FAIL; - } - - -CleanUpOne: - - /* Close Handle to create file mapping. - */ - if ( CloseHandle(hFileMapRW) == FALSE ) - { - Trace("ERROR:%u: Failed to CloseHandle \"0x%lx\".\n", - GetLastError(), - hFileMapRW); - RetVal = FAIL; - } - - - /* Terminate the PAL. - */ - PAL_TerminateEx(RetVal); - return RetVal; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test8/createfilemapping.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test8/createfilemapping.cpp deleted file mode 100644 index 8a264ea83e1735..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test8/createfilemapping.cpp +++ /dev/null @@ -1,81 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemappingw.c (test 8) -** -** Purpose: Positive test the CreateFileMappingW API. -** Test the un-verifiable parameter combinations. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test8_paltest_createfilemappingw_test8, "filemapping_memmgt/CreateFileMappingW/test8/paltest_createfilemappingw_test8") -{ - HANDLE SWAP_HANDLE = ((VOID *)(-1)); - WCHAR lpObjectName[] = {'m','y','O','b','j','e','c','t','\0'}; - - HANDLE hFileMap; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a READONLY, "swap", un-named file mapping. - * This test is unverifiable since there is no hook back to the file map - * because it is un-named. As well, since it resides in "swap", and is - * initialized to zero, there is nothing to read. - */ - hFileMap = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_READONLY, /*read only*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - NULL); /*un-named object*/ - - if(NULL == hFileMap) - { - Fail("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - } - - - /* Create a COPYWRITE, "swap", un-named file mapping. - * This test is unverifiable, here is a quote from MSDN: - * - * Copy on write access. If you create the map with PAGE_WRITECOPY and - * the view with FILE_MAP_COPY, you will receive a view to file. If you - * write to it, the pages are automatically swappable and the modifications - * you make will not go to the original data file. - * - */ - hFileMap = CreateFileMapping( - SWAP_HANDLE, - NULL, /*not inherited*/ - PAGE_WRITECOPY, /*write copy*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMap) - { - Fail("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - } - - - /* Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test9/createfilemapping.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test9/createfilemapping.cpp deleted file mode 100644 index fe34754bf7319c..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/CreateFileMappingW/test9/createfilemapping.cpp +++ /dev/null @@ -1,150 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: createfilemapping.c (test 9) -** -** Purpose: Negative test the CreateFileMappingW API. -** -** -**============================================================*/ -#define UNICODE -#include - -const int MAPPINGSIZE = 2048; - -PALTEST(filemapping_memmgt_CreateFileMappingW_test9_paltest_createfilemappingw_test9, "filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9") -{ - - HANDLE hFile; - WCHAR lpFileName[] = {'t','e','s','t','.','t','m','p','\0'}; - - HANDLE hFileMapping; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile, as READONLY - */ - hFile = CreateFile( lpFileName, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Attempt to create a unnamed file-mapping object to a READONLY file - * as READWRITE access. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and write*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - NULL); /*unnamed object*/ - - if(NULL != hFileMapping) - { - Trace("ERROR: Able to create READWRITE mapping to a " - "READONLY file.\n" ); - if( 0 == CloseHandle(hFile) ) - { - Trace("Unexpected Error: Unable to close file handle\n"); - } - Fail(""); - } - - /* Attempt to create a unnamed file-mapping object to a zero length - * file. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and write*/ - 0, /*high-order size*/ - 0, /*low-order size*/ - NULL); /*unnamed object*/ - - if( NULL != hFileMapping ) - { - Trace("ERROR: Able to create READWRITE mapping to a " - "READONLY file.\n" ); - if( 0 == CloseHandle(hFile) ) - { - Trace("Unexpected Error: Unable to close file handle\n"); - } - Fail(""); - } - if(GetLastError() != ERROR_ACCESS_DENIED) - { - Trace("ERROR: Expected GetLastError() to return " - "ERROR_FILE_INVALID (%d), it returned %u.\n", - ERROR_FILE_INVALID, - GetLastError()); - if( 0 == CloseHandle(hFile) ) - { - Trace("Unexpected Error: Unable to close file handle\n"); - } - Fail(""); - } - - /* Attempt to create a file mapping that is larger than - * the file. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READONLY, /*read only*/ - 0, /*high-order size*/ - MAPPINGSIZE, /*low-order size*/ - NULL); /*unnamed object*/ - if(NULL != hFileMapping) - { - Trace("ERROR: Able to create file mapping of size %d to " - "file of size 0.\n", - MAPPINGSIZE); - if( 0 == CloseHandle(hFile) ) - { - Trace("Unexpected Error: Unable to close file handle\n"); - } - Fail(""); - } - - if(GetLastError() != ERROR_NOT_ENOUGH_MEMORY ) - { - Trace("ERROR: Expected GetLastError() to return " - "ERROR_NOT_ENOUGH_MEMORY (%d), it returned %u.\n", - ERROR_NOT_ENOUGH_MEMORY, - GetLastError()); - if( 0 == CloseHandle(hFile) ) - { - Trace("Unexpected Error: Unable to close file handle\n"); - } - Fail(""); - } - - if( 0 == CloseHandle(hFile) ) - { - Fail("Unexpected Error: Unable to close file handle\n"); - } - - /* Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp deleted file mode 100644 index 8de37a15619f69..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test2/MapViewOfFile.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: MapViewOfFile.c -** -** Purpose: Positive test the MapViewOfFile API. -** Call MapViewOfFile with access FILE_MAP_WRITE. -** -** Depends: CreateFile, -** GetFileSize, -** memset, -** CreateFileMapping, -** CloseHandle, -** memcpy, -** ReadFile, -** memcmp, -** UnMapViewOfFile. -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_MapViewOfFile_test2_paltest_mapviewoffile_test2, "filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2") -{ - - HANDLE hFile; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - char buf[] = "this is a test string"; - const int MAPPINGSIZE = 2048; - char ch[2048]; - char readString[2048]; - char lpFileName[] = "test.tmp"; - DWORD dwBytesRead; - DWORD dwInitialSize = 0; - DWORD dwFinalSize = 0; - BOOL bRetVal; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Get the initial size of file, for latter tests. - */ - dwInitialSize = GetFileSize (hFile, NULL); - if ( dwInitialSize == INVALID_FILE_SIZE ) - { - Fail("ERROR:%u: The created file \"%s\" has an invalid " - "file size.\n", - GetLastError(), - lpFileName); - } - - /* Initialize the buffers. - */ - memset(ch, 0, MAPPINGSIZE); - memset(readString, 0, MAPPINGSIZE); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and wite*/ - 0, /*high-order of object size*/ - MAPPINGSIZE, /*low-orger of object size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - CloseHandle(hFile); - Fail(""); - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_WRITE, /* access code */ - 0, /*high order offset*/ - 0, /*low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile API to map a view" - " of file!\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Verify that the size of the file has increased to - * accomidate the MapView. - */ - dwFinalSize = GetFileSize (hFile, NULL); - if ( (dwFinalSize <= dwInitialSize) && (dwFinalSize != MAPPINGSIZE)) - { - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail("ERROR: Size of the file was expected to " - "increase from \"%d\", to \"%d\".\n ", - dwInitialSize, - MAPPINGSIZE); - } - - /* Write to the MapView and copy the MapViewOfFile - * to buffer, so we can compare with value read from - * file directly. - */ - memcpy(lpMapViewAddress, buf, strlen(buf)); - - /* Read from the File handle. - */ - bRetVal = ReadFile(hFile, - readString, - strlen(buf), - &dwBytesRead, - NULL); - - if (bRetVal == FALSE) - { - Trace("ERROR: %u :unable to read from file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - if (memcmp(buf, readString, strlen(readString)) != 0) - { - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail("ERROR: Read string from file \"%s\", is " - "not equal to string written through MapView " - "\"%s\".\n", - readString, - ch); - } - - /* Unmap the view of file. - */ - if(UnmapViewOfFile(lpMapViewAddress) == FALSE) - { - Trace("ERROR: Failed to call UnmapViewOfFile API to" - " unmap the view of a file, error code=%u\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Close handle to create file. - */ - if(CloseHandle(hFile) == FALSE) - { - Trace("ERROR:%u:Failed to call CloseHandle API " - "to close a file handle.", - GetLastError()); - CloseHandle(hFileMapping); - Fail(""); - } - - if(CloseHandle(hFileMapping) == FALSE) - { - Fail("ERROR:%u:Failed to call CloseHandle API " - "to close a file mapping handle.", - GetLastError()); - } - - PAL_Terminate(); - return PASS; -} - - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test3/MapViewOfFile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test3/MapViewOfFile.cpp deleted file mode 100644 index b5d4ef346232d2..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test3/MapViewOfFile.cpp +++ /dev/null @@ -1,208 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: MapViewOfFile.c -** -** Purpose: Positive test the MapViewOfFile API. -** Call MapViewOfFile with access FILE_MAP_ALL_ACCESS. -** -** Depends: CreateFile, -** GetFileSize, -** memset, -** memcpy, -** memcmp, -** ReadFile, -** UnMapViewOfFile, -** CreateFileMapping, -** CloseHandle. -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_MapViewOfFile_test3_paltest_mapviewoffile_test3, "filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3") -{ - - HANDLE hFile; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - char buf[] = "this is a test string"; - const int MAPPINGSIZE = 2048; - char ch[2048]; - char readString[2048]; - char lpFileName[] = "test.tmp"; - DWORD dwBytesRead; - DWORD dwInitialSize = 0; - DWORD dwFinalSize = 0; - BOOL bRetVal; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Get the initial size of file, for latter tests. - */ - dwInitialSize = GetFileSize (hFile, NULL); - if ( dwInitialSize == INVALID_FILE_SIZE ) - { - Trace("ERROR:%u: The created file \"%s\" has an invalid " - "file size.\n", - GetLastError(), - lpFileName); - CloseHandle(hFile); - Fail(""); - } - - /* Initialize the buffers. - */ - memset(ch, 0, MAPPINGSIZE); - memset(readString, 0, MAPPINGSIZE); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and wite*/ - 0, /*high-order of object size*/ - MAPPINGSIZE, /*low-orger of object size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - CloseHandle(hFile); - Fail(""); - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_ALL_ACCESS, /*access code*/ - 0, /*high order offset*/ - 0, /*low order offset*/ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile API to map a view" - " of file!\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Verify that the size of the file has increased to - * accomidate the MapView. - */ - dwFinalSize = GetFileSize (hFile, NULL); - if ( (dwFinalSize <= dwInitialSize) && (dwFinalSize != MAPPINGSIZE)) - { - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail("ERROR: Size of the file was expected to " - "increase from \"%d\", to \"%d\".\n ", - dwInitialSize, - MAPPINGSIZE); - } - - /* Write to the MapView and copy the MapViewOfFile - * to buffer, so we can compare with value read from - * file directly. - */ - - memcpy(lpMapViewAddress, buf, strlen(buf)); - memcpy(ch, (LPCSTR)lpMapViewAddress, MAPPINGSIZE); - - /* Read from the File handle. - */ - bRetVal = ReadFile(hFile, - readString, - strlen(buf), - &dwBytesRead, - NULL); - - if (bRetVal == FALSE) - { - Trace("ERROR: %u :unable to read from file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - if (memcmp(ch, readString, strlen(readString)) != 0) - { - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail("ERROR: Read string from file \"%s\", is " - "not equal to string written through MapView " - "\"%s\".\n", - readString, - ch); - } - - /* Unmap the view of file. - */ - if(UnmapViewOfFile(lpMapViewAddress) == FALSE) - { - Trace("ERROR: Failed to call UnmapViewOfFile API to" - " unmap the view of a file, error code=%u\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Close handle to create file. - */ - if(CloseHandle(hFile) == FALSE) - { - Trace("ERROR:%u:Failed to call CloseHandle API " - "to close a file handle.", - GetLastError()); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Close handle to file mapping. - */ - if(CloseHandle(hFileMapping) == FALSE) - { - Fail("ERROR:%u:Failed to call CloseHandle API " - "to close a file handle.", - GetLastError()); - } - - PAL_Terminate(); - return PASS; -} - - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test4/mapviewoffile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test4/mapviewoffile.cpp deleted file mode 100644 index 00139eda9da6d6..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test4/mapviewoffile.cpp +++ /dev/null @@ -1,165 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: MapViewOfFile.c -** -** Purpose: Negative test the MapViewOfFile API. -** Call MapViewOfFile with all access modes, except -** read-only, on a read only map. -** -** Depends: CreateFile, -** CreateFileMapping, -** CloseHandle, -** UnMapViewOfFile. -** - -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_MapViewOfFile_test4_paltest_mapviewoffile_test4, "filemapping_memmgt/MapViewOfFile/test4/paltest_mapviewoffile_test4") -{ - - HANDLE hFile; - BOOL err; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - DWORD dwBytesWritten; - const int MAPPINGSIZE = 2048; - char buf[] = "this is a test string"; - char lpFileName[] = "test.tmp"; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Write to the File handle. - */ - err = WriteFile(hFile, - buf, - strlen(buf), - &dwBytesWritten, - NULL); - - if ( !FlushFileBuffers( hFile ) ) - { - CloseHandle(hFile); - Fail("ERROR: Unable to flush the buffers\n"); - } - - if (err == FALSE) - { - Trace("ERROR: %u :unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - Fail(""); - } - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READONLY, /*read and wite*/ - 0, /*high-order of object size*/ - 0, /*low-orger of object size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - CloseHandle(hFile); - Fail(""); - } - - /* map a writeable view of a file to a read-only file map. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_WRITE, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL != lpMapViewAddress) - { - Trace("ERROR:%u: Able to create a writeable MapViewOfFile" - " to a read-only file.\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - UnmapViewOfFile(lpMapViewAddress); - Fail(""); - } - - /* map an all access view of a file to a read-only file map. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_ALL_ACCESS, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL != lpMapViewAddress) - { - Trace("ERROR:%u: Able to create an all access MapViewOfFile" - " to a read-only file.\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - UnmapViewOfFile(lpMapViewAddress); - Fail(""); - } - - /* map an copy view of a file to a read-only file map. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_COPY, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL != lpMapViewAddress) - { - Trace("ERROR:%u: Able to create a copy access MapViewOfFile " - "to a read-only file.\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Clean-up and Teminate. */ - CloseHandle(hFile); - CloseHandle(hFileMapping); - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test5/mapviewoffile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test5/mapviewoffile.cpp deleted file mode 100644 index 0f42512a66f02f..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test5/mapviewoffile.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: MapViewOfFile.c -** -** Purpose: Negative test the MapViewOfFile API. -** Passing invalid values for the hFileMappingObject. -** -** Depends: CreatePipe, -** CreateFile, -** CreateFileMapping, -** CloseHandle. -** - -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_MapViewOfFile_test5_paltest_mapviewoffile_test5, "filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5") -{ - - const int MAPPINGSIZE = 2048; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - HANDLE hReadPipe = NULL; - HANDLE hWritePipe = NULL; - BOOL bRetVal; - - SECURITY_ATTRIBUTES lpPipeAttributes; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - - /* Attempt to create a MapViewOfFile with a NULL handle. - */ - hFileMapping = NULL; - - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_WRITE, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if((NULL != lpMapViewAddress) && - (GetLastError() != ERROR_INVALID_HANDLE)) - { - Trace("ERROR:%u: Able to create a MapViewOfFile with " - "hFileMapping=0x%lx.\n", - GetLastError()); - UnmapViewOfFile(lpMapViewAddress); - Fail(""); - } - - /* Attempt to create a MapViewOfFile with an invalid handle. - */ - hFileMapping = INVALID_HANDLE_VALUE; - - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_WRITE, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if((NULL != lpMapViewAddress) && - (GetLastError() != ERROR_INVALID_HANDLE)) - { - Trace("ERROR:%u: Able to create a MapViewOfFile with " - "hFileMapping=0x%lx.\n", - GetLastError()); - UnmapViewOfFile(lpMapViewAddress); - Fail(""); - } - - /* Clean-up and Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} - - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test6/mapviewoffile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test6/mapviewoffile.cpp deleted file mode 100644 index c118fa1f6692df..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/MapViewOfFile/test6/mapviewoffile.cpp +++ /dev/null @@ -1,84 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: MapViewOfFile.c -** -** Purpose: Positivve test the MapViewOfFile API. -** Mapping a pagefile allocation into memory -** -** Depends: CreateFileMappingW, -** UnmapViewOfFile -** CloseHandle. -** - -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_MapViewOfFile_test6_paltest_mapviewoffile_test6, "filemapping_memmgt/MapViewOfFile/test6/paltest_mapviewoffile_test6") -{ - - const int MAPPINGSIZE = 2048; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - char *p; - int i; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - hFileMapping = CreateFileMappingW(INVALID_HANDLE_VALUE, - NULL, - PAGE_READWRITE, - 0, - MAPPINGSIZE, - NULL); - - if (hFileMapping == NULL) { - Trace("ERROR:%u: CreateFileMappingW() failed\n", GetLastError()); - Fail(""); - } - - - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_WRITE, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MAPPINGSIZE); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: MapViewOfFile() failed.\n", - GetLastError()); - CloseHandle(hFileMapping); - Fail(""); - } - - p = (char *)lpMapViewAddress; - for (i=0; i - -PALTEST(filemapping_memmgt_UnmapViewOfFile_test1_paltest_unmapviewoffile_test1, "filemapping_memmgt/UnmapViewOfFile/test1/paltest_unmapviewoffile_test1") -{ - const int MappingSize = 2048; - HANDLE hFile; - HANDLE hFileMapping; - LPVOID lpMapViewAddress; - char buf[] = "this is a test string"; - char ch[2048]; - char readString[2048]; - char lpFileName[] = "test.tmp"; - DWORD dwBytesRead; - BOOL bRetVal; - - /* Initialize the PAL environment. - */ - if(0 != PAL_Initialize(argc, argv)) - { - return FAIL; - } - - /* Create a file handle with CreateFile. - */ - hFile = CreateFile( lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_READ|FILE_SHARE_WRITE, - NULL, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /* Initialize the buffers. - */ - memset(ch, 0, MappingSize); - memset(readString, 0, MappingSize); - - /* Create a unnamed file-mapping object with file handle FileHandle - * and with PAGE_READWRITE protection. - */ - hFileMapping = CreateFileMapping( - hFile, - NULL, /*not inherited*/ - PAGE_READWRITE, /*read and wite*/ - 0, /*high-order of object size*/ - MappingSize, /*low-orger of object size*/ - NULL); /*unnamed object*/ - - if(NULL == hFileMapping) - { - Trace("ERROR:%u: Failed to create File Mapping.\n", - GetLastError()); - CloseHandle(hFile); - Fail(""); - } - - /* maps a view of a file into the address space of the calling process. - */ - lpMapViewAddress = MapViewOfFile( - hFileMapping, - FILE_MAP_ALL_ACCESS, /* access code */ - 0, /* high order offset */ - 0, /* low order offset */ - MappingSize); /* number of bytes for map */ - - if(NULL == lpMapViewAddress) - { - Trace("ERROR:%u: Failed to call MapViewOfFile API to map a view" - " of file!\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Write to the MapView and copy the MapViewOfFile - * to buffer, so we can compare with value read from - * file directly. - */ - - memcpy(lpMapViewAddress, buf, strlen(buf)); - memcpy(ch, (LPCSTR)lpMapViewAddress, MappingSize); - - /* Read from the File handle. - */ - bRetVal = ReadFile(hFile, - readString, - strlen(buf), - &dwBytesRead, - NULL); - - if (bRetVal == FALSE) - { - Trace("ERROR: %u :unable to read from file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - if (memcmp(ch, readString, strlen(readString)) != 0) - { - Trace("ERROR: Read string from file \"%s\", is " - "not equal to string written through MapView " - "\"%s\".\n", - readString, - ch); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Unmap the view of file. - */ - if(UnmapViewOfFile(lpMapViewAddress) == FALSE) - { - Trace("ERROR: Failed to call UnmapViewOfFile API to" - " unmap the view of a file, error code=%u\n", - GetLastError()); - CloseHandle(hFile); - CloseHandle(hFileMapping); - Fail(""); - } - - /* Re-initialize the buffer. - */ - memset(ch, 0, MappingSize); - - /* Close handle to created file mapping. - */ - if(CloseHandle(hFileMapping) == FALSE) - { - Trace("ERROR:%u:Failed to call CloseHandle API " - "to close a file mapping handle.", - GetLastError()); - CloseHandle(hFile); - Fail(""); - } - - /* Close handle to create file. - */ - if(CloseHandle(hFile) == FALSE) - { - Fail("ERROR:%u:Failed to call CloseHandle API " - "to close a file handle.", - GetLastError()); - } - - PAL_Terminate(); - return PASS; -} - - diff --git a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/UnmapViewOfFile/test2/unmapviewoffile.cpp b/src/coreclr/pal/tests/palsuite/filemapping_memmgt/UnmapViewOfFile/test2/unmapviewoffile.cpp deleted file mode 100644 index b887891c46c9df..00000000000000 --- a/src/coreclr/pal/tests/palsuite/filemapping_memmgt/UnmapViewOfFile/test2/unmapviewoffile.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================= -** -** Source: UnmapViewOfFile.c (test 2) -** -** Purpose: Negative test the UnmapViewOfFile API. -** Call UnmapViewOfFile to unmap a view of -** NULL. -** -** -**============================================================*/ -#include - -PALTEST(filemapping_memmgt_UnmapViewOfFile_test2_paltest_unmapviewoffile_test2, "filemapping_memmgt/UnmapViewOfFile/test2/paltest_unmapviewoffile_test2") -{ - int err; - - /*Initialize the PAL environment*/ - err = PAL_Initialize(argc, argv); - if(0 != err) - { - return FAIL; - } - - /* Negative test the UnmapViewOfFile by passing a NULL*/ - /* mapping address handle*/ - err = UnmapViewOfFile(NULL); - if(0 != err) - { - Fail("ERROR: Able to call UnmapViewOfFile API " - "by passing a NULL mapping address.\n" ); - - } - - /* Terminate the PAL. - */ - PAL_Terminate(); - return PASS; -} diff --git a/src/coreclr/pal/tests/palsuite/miscellaneous/CloseHandle/test1/test.cpp b/src/coreclr/pal/tests/palsuite/miscellaneous/CloseHandle/test1/test.cpp deleted file mode 100644 index 304ec987184889..00000000000000 --- a/src/coreclr/pal/tests/palsuite/miscellaneous/CloseHandle/test1/test.cpp +++ /dev/null @@ -1,47 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*============================================================ -** -** Source: test.c -** -** Purpose: Test for CloseHandle function -** -** -**=========================================================*/ - -/* Depends on: CreateFile */ - -#include - -PALTEST(miscellaneous_CloseHandle_test1_paltest_closehandle_test1, "miscellaneous/CloseHandle/test1/paltest_closehandle_test1") -{ - - HANDLE FileHandle = NULL; - - /* - * Initialize the PAL and return FAILURE if this fails - */ - - if(0 != (PAL_Initialize(argc, argv))) - { - return FAIL; - } - - /* Create a file, since this returns to us a HANDLE we can use */ - FileHandle = CreateFile("testfile", - GENERIC_READ | GENERIC_WRITE,0,NULL,CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - - /* Should be able to close this handle */ - if(CloseHandle(FileHandle) == 0) - { - Fail("ERROR: (Test 1) Attempted to close a HANDLE on a file, but the " - "return value was <=0, indicating failure.\n"); - } - - PAL_Terminate(); - return PASS; -} - diff --git a/src/coreclr/pal/tests/palsuite/paltestlist.txt b/src/coreclr/pal/tests/palsuite/paltestlist.txt index fabaebdf172687..afd899d6d46468 100644 --- a/src/coreclr/pal/tests/palsuite/paltestlist.txt +++ b/src/coreclr/pal/tests/palsuite/paltestlist.txt @@ -91,50 +91,11 @@ exception_handling/RaiseException/test1/paltest_raiseexception_test1 exception_handling/RaiseException/test2/paltest_raiseexception_test2 exception_handling/RaiseException/test3/paltest_raiseexception_test3 exception_handling/pal_sxs/test1/paltest_pal_sxs_test1 -filemapping_memmgt/CreateFileMappingW/test1/paltest_createfilemappingw_test1 -filemapping_memmgt/CreateFileMappingW/test3/paltest_createfilemappingw_test3 -filemapping_memmgt/CreateFileMappingW/test4/paltest_createfilemappingw_test4 -filemapping_memmgt/CreateFileMappingW/test8/paltest_createfilemappingw_test8 -filemapping_memmgt/CreateFileMappingW/test9/paltest_createfilemappingw_test9 filemapping_memmgt/FreeLibrary/test2/paltest_freelibrary_test2 filemapping_memmgt/GetModuleFileNameA/test2/paltest_getmodulefilenamea_test2 filemapping_memmgt/GetModuleFileNameW/test2/paltest_getmodulefilenamew_test2 -filemapping_memmgt/MapViewOfFile/test2/paltest_mapviewoffile_test2 -filemapping_memmgt/MapViewOfFile/test3/paltest_mapviewoffile_test3 -filemapping_memmgt/MapViewOfFile/test4/paltest_mapviewoffile_test4 -filemapping_memmgt/MapViewOfFile/test5/paltest_mapviewoffile_test5 -filemapping_memmgt/MapViewOfFile/test6/paltest_mapviewoffile_test6 filemapping_memmgt/ProbeMemory/test1/paltest_probememory_test1 filemapping_memmgt/ProbeMemory/ProbeMemory_neg1/paltest_probememory_probememory_neg1 -filemapping_memmgt/UnmapViewOfFile/test1/paltest_unmapviewoffile_test1 -filemapping_memmgt/UnmapViewOfFile/test2/paltest_unmapviewoffile_test2 -file_io/FILECanonicalizePath/paltest_filecanonicalizepath_test1 -file_io/FlushFileBuffers/test1/paltest_flushfilebuffers_test1 -file_io/GetFileSize/test1/paltest_getfilesize_test1 -file_io/GetFileSizeEx/test1/paltest_getfilesizeex_test1 -file_io/GetFullPathNameA/test1/paltest_getfullpathnamea_test1 -file_io/GetFullPathNameA/test3/paltest_getfullpathnamea_test3 -file_io/GetFullPathNameA/test4/paltest_getfullpathnamea_test4 -file_io/GetFullPathNameW/test1/paltest_getfullpathnamew_test1 -file_io/GetFullPathNameW/test3/paltest_getfullpathnamew_test3 -file_io/GetFullPathNameW/test4/paltest_getfullpathnamew_test4 -file_io/GetStdHandle/test2/paltest_getstdhandle_test2 -file_io/gettemppatha/test1/paltest_gettemppatha_test1 -file_io/ReadFile/test2/paltest_readfile_test2 -file_io/ReadFile/test3/paltest_readfile_test3 -file_io/ReadFile/test4/paltest_readfile_test4 -file_io/SearchPathW/test1/paltest_searchpathw_test1 -file_io/SetFilePointer/test1/paltest_setfilepointer_test1 -file_io/SetFilePointer/test2/paltest_setfilepointer_test2 -file_io/SetFilePointer/test3/paltest_setfilepointer_test3 -file_io/SetFilePointer/test4/paltest_setfilepointer_test4 -file_io/SetFilePointer/test5/paltest_setfilepointer_test5 -file_io/SetFilePointer/test6/paltest_setfilepointer_test6 -file_io/SetFilePointer/test7/paltest_setfilepointer_test7 -file_io/WriteFile/test1/paltest_writefile_test1 -file_io/WriteFile/test3/paltest_writefile_test3 -file_io/WriteFile/test4/paltest_writefile_test4 -file_io/WriteFile/test5/paltest_writefile_test5 loader/LoadLibraryA/test2/paltest_loadlibrarya_test2 loader/LoadLibraryA/test3/paltest_loadlibrarya_test3 loader/LoadLibraryA/test5/paltest_loadlibrarya_test5 @@ -149,7 +110,6 @@ locale_info/WideCharToMultiByte/test1/paltest_widechartomultibyte_test1 locale_info/WideCharToMultiByte/test2/paltest_widechartomultibyte_test2 locale_info/WideCharToMultiByte/test3/paltest_widechartomultibyte_test3 locale_info/WideCharToMultiByte/test5/paltest_widechartomultibyte_test5 -miscellaneous/CloseHandle/test1/paltest_closehandle_test1 miscellaneous/CloseHandle/test2/paltest_closehandle_test2 miscellaneous/FlushInstructionCache/test1/paltest_flushinstructioncache_test1 miscellaneous/FormatMessageW/test1/paltest_formatmessagew_test1 diff --git a/src/coreclr/pal/tests/palsuite/paltestlist_to_be_reviewed.txt b/src/coreclr/pal/tests/palsuite/paltestlist_to_be_reviewed.txt index 2ef293d3841a24..aa4324c318988f 100644 --- a/src/coreclr/pal/tests/palsuite/paltestlist_to_be_reviewed.txt +++ b/src/coreclr/pal/tests/palsuite/paltestlist_to_be_reviewed.txt @@ -24,25 +24,11 @@ exception_handling/PAL_TRY_EXCEPT_EX/test1/paltest_pal_try_except_ex_test1 exception_handling/PAL_TRY_EXCEPT_EX/test2/paltest_pal_try_except_ex_test2 exception_handling/PAL_TRY_EXCEPT_EX/test3/paltest_pal_try_except_ex_test3 exception_handling/PAL_TRY_LEAVE_FINALLY/test1/paltest_pal_try_leave_finally_test1 -filemapping_memmgt/CreateFileMappingW/CreateFileMapping_neg1/paltest_createfilemappingw_createfilemapping_neg1 -filemapping_memmgt/CreateFileMappingW/test2/paltest_createfilemappingw_test2 -filemapping_memmgt/CreateFileMappingW/test5/paltest_createfilemappingw_test5 -filemapping_memmgt/CreateFileMappingW/test6/paltest_createfilemappingw_test6 -filemapping_memmgt/CreateFileMappingW/test7/paltest_createfilemappingw_test7 filemapping_memmgt/FreeLibrary/test1/paltest_freelibrary_test1 filemapping_memmgt/GetModuleFileNameA/test1/paltest_getmodulefilenamea_test1 filemapping_memmgt/GetModuleFileNameW/test1/paltest_getmodulefilenamew_test1 filemapping_memmgt/GetProcAddress/test1/paltest_getprocaddress_test1 filemapping_memmgt/GetProcAddress/test2/paltest_getprocaddress_test2 -file_io/CreateFileA/test1/paltest_createfilea_test1 -file_io/CreateFileW/test1/paltest_createfilew_test1 -file_io/errorpathnotfound/test1/paltest_errorpathnotfound_test1 -file_io/GetFullPathNameA/test2/paltest_getfullpathnamea_test2 -file_io/GetFullPathNameW/test2/paltest_getfullpathnamew_test2 -file_io/GetStdHandle/test1/paltest_getstdhandle_test1 -file_io/gettemppatha/test1/paltest_gettemppatha_test1 -file_io/ReadFile/test1/paltest_readfile_test1 -file_io/WriteFile/test2/paltest_writefile_test2 loader/LoadLibraryA/test1/paltest_loadlibrarya_test1 loader/LoadLibraryA/test6/paltest_loadlibrarya_test6 loader/LoadLibraryA/test7/paltest_loadlibrarya_test7 @@ -66,8 +52,6 @@ pal_specific/PAL_get_stdout/test1/paltest_pal_get_stdout_test1 pal_specific/PAL_RegisterLibraryW_UnregisterLibraryW/test1/paltest_pal_registerlibraryw_unregisterlibraryw_test1 samples/test2/paltest_samples_test2 threading/CreateThread/test2/paltest_createthread_test2 -threading/DuplicateHandle/test1/paltest_duplicatehandle_test1 -threading/DuplicateHandle/test12/paltest_duplicatehandle_test12 threading/DuplicateHandle/test9/paltest_duplicatehandle_test9 threading/ExitThread/test2/paltest_exitthread_test2 threading/GetCurrentProcess/test1/paltest_getcurrentprocess_test1 diff --git a/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test1/test1.cpp b/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test1/test1.cpp deleted file mode 100644 index 654b257bdbe625..00000000000000 --- a/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test1/test1.cpp +++ /dev/null @@ -1,151 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test1.c (DuplicateHandle) -** -** Purpose: Tests the PAL implementation of the DuplicateHandle function. -** This test will create two handles to file, one to write and -** one to read what was written. Test on a closed handle and a -** NULL handle, both should fail. -** -** -**===================================================================*/ -#include - -PALTEST(threading_DuplicateHandle_test1_paltest_duplicatehandle_test1, "threading/DuplicateHandle/test1/paltest_duplicatehandle_test1") -{ - HANDLE hFile; - HANDLE hDupFile; - char buf[256]; - char teststr[] = "A uNiQuE tEsT sTrInG"; - char lpFileName[] = "testfile.txt"; - DWORD dwBytesWritten; - DWORD dwBytesRead; - BOOL bRetVal; - - /*Initialize the PAL*/ - if ((PAL_Initialize(argc,argv)) != 0) - { - return (FAIL); - } - - /*Create a file handle with CreateFile*/ - hFile = CreateFile(lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_WRITE|FILE_SHARE_READ, - NULL, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /*Write test string to the file.*/ - bRetVal = WriteFile(hFile, // handle to file - teststr, // data buffer - strlen(teststr), // number of bytes to write - &dwBytesWritten, // number of bytes written - NULL); // overlapped buffer - - if (bRetVal == FALSE) - { - Trace("ERROR: %u : unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - Fail(""); - } - - /*Create a duplicate handle with DuplicateHandle.*/ - if (!(DuplicateHandle( - GetCurrentProcess(), - hFile, - GetCurrentProcess(), - &hDupFile, - GENERIC_READ|GENERIC_WRITE, - FALSE, - DUPLICATE_SAME_ACCESS))) - { - Trace("ERROR: %u : Fail to create the duplicate handle" - " to hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - Fail(""); - } - - memset(buf, 0, 256); - - /*Read from the Duplicated handle.*/ - bRetVal = ReadFile(hDupFile, - buf, - 256, - &dwBytesRead, - NULL); - if (bRetVal == FALSE) - { - Trace("ERROR: %u :unable to read from file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - CloseHandle(hDupFile); - Fail(""); - } - - /*Compare what was written to what was read.*/ - if (memcmp(teststr, buf, dwBytesRead) != 0) - { - Trace("ERROR: expected %s, got %s\n", teststr, buf); - CloseHandle(hFile); - CloseHandle(hDupFile); - Fail(""); - } - - /*Close the handles*/ - CloseHandle(hFile); - CloseHandle(hDupFile); - - /*Failure test: Create DuplicateHandle to a closed handle*/ - if ((DuplicateHandle( - GetCurrentProcess(), - hFile, - GetCurrentProcess(), - &hDupFile, - GENERIC_READ|GENERIC_WRITE, - FALSE, - DUPLICATE_SAME_ACCESS))) - { - Fail("ERROR: %u :Created a duplicate handle to" - " a closed handle hFile=0x%lx\n", - GetLastError(), - hFile); - } - - /*Failure test: Create DuplicateHandle to a NULL handle*/ - hFile = NULL; - if ((DuplicateHandle( - GetCurrentProcess(), - hFile, - GetCurrentProcess(), - &hDupFile, - GENERIC_READ|GENERIC_WRITE, - FALSE, - DUPLICATE_SAME_ACCESS))) - { - Fail("ERROR: %u :Created a duplicate handle to " - " a NULL handle hFile=0x%lx\n", - GetLastError(), - hFile); - } - - PAL_Terminate(); - return (PASS); -} diff --git a/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test12/test12.cpp b/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test12/test12.cpp deleted file mode 100644 index 5a476b2d9edf75..00000000000000 --- a/src/coreclr/pal/tests/palsuite/threading/DuplicateHandle/test12/test12.cpp +++ /dev/null @@ -1,128 +0,0 @@ -// Licensed to the .NET Foundation under one or more agreements. -// The .NET Foundation licenses this file to you under the MIT license. - -/*===================================================================== -** -** Source: test12.c (DuplicateHandle) -** -** Purpose: Tests the PAL implementation of the DuplicateHandle function. -** This test will create handle to file (to write) and close it, -** then call duplicate handle to read what was written. -** -** -**===================================================================*/ -#include - -PALTEST(threading_DuplicateHandle_test12_paltest_duplicatehandle_test12, "threading/DuplicateHandle/test12/paltest_duplicatehandle_test12") -{ - HANDLE hFile; - HANDLE hDupFile; - char buf[256]; - char teststr[] = "A uNiQuE tEsT sTrInG"; - char lpFileName[] = "testfile.txt"; - DWORD dwBytesWritten; - DWORD dwBytesRead; - BOOL bRetVal; - - /*Initialize the PAL*/ - if ((PAL_Initialize(argc,argv)) != 0) - { - return (FAIL); - } - - /*Create a file handle with CreateFile*/ - hFile = CreateFile(lpFileName, - GENERIC_WRITE|GENERIC_READ, - FILE_SHARE_WRITE|FILE_SHARE_READ, - NULL, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - Fail("ERROR: %u :unable to create file \"%s\".\n", - GetLastError(), - lpFileName); - } - - /*Write test string to the file.*/ - bRetVal = WriteFile(hFile, // handle to file - teststr, // data buffer - strlen(teststr), // number of bytes to write - &dwBytesWritten, // number of bytes written - NULL); // overlapped buffer - - if (bRetVal == FALSE) - { - Trace("ERROR: %u : unable to write to file handle " - "hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - Fail(""); - } - - /*Create a duplicate handle with DuplicateHandle.*/ - if (!(DuplicateHandle( - GetCurrentProcess(), - hFile, - GetCurrentProcess(), - &hDupFile, - GENERIC_READ|GENERIC_WRITE, - FALSE, - DUPLICATE_SAME_ACCESS))) - { - Trace("ERROR: %u : Fail to create the duplicate handle" - " to hFile=0x%lx\n", - GetLastError(), - hFile); - CloseHandle(hFile); - Fail(""); - } - - if( !CloseHandle(hFile) ) - { - Fail("Duplicate Handle:Unable to close original file: Error[%u]\n", GetLastError()); - } - - memset(buf, 0, 256); - - /*Read from the Duplicated handle.*/ - bRetVal = ReadFile(hDupFile, - buf, - 256, - &dwBytesRead, - NULL); - if (bRetVal == FALSE) - { - Trace("ERROR: %u :unable to read from file handle " - "hFile=0x%lx\n", - GetLastError(), - hDupFile); - CloseHandle(hDupFile); - Fail(""); - } - - /*Compare what was written to what was read.*/ - if (memcmp(teststr, buf, dwBytesRead) != 0) - { - Trace("ERROR: expected %s, got %s\n", teststr, buf); - CloseHandle(hDupFile); - Fail(""); - } - - /*Close the handles*/ - CloseHandle(hDupFile); - - bRetVal = DeleteFileA(lpFileName); - if (bRetVal != TRUE) - { - Trace("Error:%u: DuplicateHandle, DeleteFileA: Couldn't delete DeleteFileA's" - " %s\n", GetLastError(), lpFileName); - Fail(""); - } - - - PAL_Terminate(); - return (PASS); -} diff --git a/src/coreclr/pal/tests/palsuite/wasm/index.html b/src/coreclr/pal/tests/palsuite/wasm/index.html index 38fd0a6b39b1e1..c9883adeb6730a 100644 --- a/src/coreclr/pal/tests/palsuite/wasm/index.html +++ b/src/coreclr/pal/tests/palsuite/wasm/index.html @@ -11,8 +11,6 @@

PAL Tests WASM