diff --git a/src/coreclr/ilasm/asmparse.h b/src/coreclr/ilasm/asmparse.h index a20157e83132d8..aa576898fd8c14 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), /* executable */ false); + 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..ab0e4ed2d13725 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), /* executable */ false); + 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/minipal/Unix/dn-stdio.cpp b/src/coreclr/minipal/Unix/dn-stdio.cpp index c60c72e476eae6..0190e03b87d615 100644 --- a/src/coreclr/minipal/Unix/dn-stdio.cpp +++ b/src/coreclr/minipal/Unix/dn-stdio.cpp @@ -48,20 +48,20 @@ int64_t fgetsize(FILE* stream) { fpos_t current; fgetpos(stream, ¤t); - fseek(stream, 0, SEEK_END); - int64_t length = ftell(stream); + fseeko(stream, 0, SEEK_END); + int64_t length = ftello(stream); fsetpos(stream, ¤t); return length; } int64_t ftell_64(FILE* stream) { - return ftell(stream); + return ftello(stream); } int fsetpos_64(FILE* stream, int64_t pos) { - return fseek(stream, pos, SEEK_SET); + return fseeko(stream, (off_t)pos, SEEK_SET); } #define FACILITY_WIN32 7 diff --git a/src/coreclr/minipal/Unix/memory.cpp b/src/coreclr/minipal/Unix/memory.cpp index 6919d7d1f4751f..58fa02100cdbcc 100644 --- a/src/coreclr/minipal/Unix/memory.cpp +++ b/src/coreclr/minipal/Unix/memory.cpp @@ -23,7 +23,7 @@ int32_t VMToOSInterface::GetLastMemoryMappingError() return HRESULTFromErr(errno); } -VMToOSInterface::MemoryMapHandle VMToOSInterface::OpenFile(const char16_t* path) +VMToOSInterface::MemoryMapHandle VMToOSInterface::OpenFile(const char16_t* path, bool /* executable */) { FILE* stream; int error = u16_fopen_s(&stream, path, u"rb"); diff --git a/src/coreclr/minipal/Windows/memory.cpp b/src/coreclr/minipal/Windows/memory.cpp index 6250ded16f4b48..89810080552954 100644 --- a/src/coreclr/minipal/Windows/memory.cpp +++ b/src/coreclr/minipal/Windows/memory.cpp @@ -8,10 +8,10 @@ #include #include "minipal.h" -VMToOSInterface::MemoryMapHandle VMToOSInterface::OpenFile(const char16_t* path) +VMToOSInterface::MemoryMapHandle VMToOSInterface::OpenFile(const char16_t* path, bool executable) { return CreateFileW(reinterpret_cast(path), - GENERIC_READ | GENERIC_EXECUTE, + executable ? (GENERIC_READ | GENERIC_EXECUTE) : GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, diff --git a/src/coreclr/minipal/minipal.h b/src/coreclr/minipal/minipal.h index 62ae16580eac66..45d47439ab171c 100644 --- a/src/coreclr/minipal/minipal.h +++ b/src/coreclr/minipal/minipal.h @@ -37,7 +37,7 @@ class VMToOSInterface ExecuteReadWrite }; - static MemoryMapHandle OpenFile(const char16_t* path); + static MemoryMapHandle OpenFile(const char16_t* path, bool executable = true); static bool CloseFile(MemoryMapHandle fileHandle); static bool GetFileSize(MemoryMapHandle fileHandle, uint64_t* size); static int32_t GetLastMemoryMappingError(); diff --git a/src/coreclr/tools/metainfo/mdobj.cpp b/src/coreclr/tools/metainfo/mdobj.cpp index 8d9d604280213b..6fdc11a30ce89b 100644 --- a/src/coreclr/tools/metainfo/mdobj.cpp +++ b/src/coreclr/tools/metainfo/mdobj.cpp @@ -5,6 +5,7 @@ #include #include #include "mdinfo.h" +#include "minipal.h" #ifndef STRING_BUFFER_LEN #define STRING_BUFFER_LEN 4096 @@ -59,38 +60,33 @@ static HRESULT FindObjMetaData(PVOID pImage, PVOID *ppMetaData, long *pcbMetaDat // This function returns the address to the MapView of file and file size. void GetMapViewOfFile(_In_ WCHAR *szFile, PBYTE *ppbMap, DWORD *pdwFileSize) { - HANDLE hMapFile; - DWORD dwHighSize; - - HANDLE hFile = WszCreateFile(szFile, - GENERIC_READ, - FILE_SHARE_READ, - NULL, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, - NULL); - if (hFile == INVALID_HANDLE_VALUE) - MDInfo::Error("CreateFileA failed!"); - - *pdwFileSize = GetFileSize(hFile, &dwHighSize); - - if ((*pdwFileSize == 0xFFFFFFFF) && (GetLastError() != NO_ERROR)) + VMToOSInterface::MemoryMapHandle hFile = VMToOSInterface::OpenFile(reinterpret_cast(szFile), /* executable */ false); + if (hFile == VMToOSInterface::InvalidFileHandle) + MDInfo::Error("OpenFile failed!"); + + uint64_t fileSize; + if (!VMToOSInterface::GetFileSize(hFile, &fileSize) || fileSize > UINT32_MAX) { - CloseHandle(hFile); + VMToOSInterface::CloseFile(hFile); MDInfo::Error("GetFileSize failed!"); } - _ASSERTE(dwHighSize == 0); + *pdwFileSize = (DWORD)fileSize; - hMapFile = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 0, NULL); - CloseHandle(hFile); - if (!hMapFile) - MDInfo::Error("CreateFileMappingW failed!"); + VMToOSInterface::MemoryMapHandle hMapFile = + VMToOSInterface::CreateMemoryMapping(hFile, 0, VMToOSInterface::MemoryProtection::ReadOnly); + if (hMapFile == VMToOSInterface::InvalidMemoryMapHandle) + { + VMToOSInterface::CloseFile(hFile); + MDInfo::Error("CreateMemoryMapping failed!"); + } - *ppbMap = (PBYTE) MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0); - CloseHandle(hMapFile); + *ppbMap = (PBYTE) VMToOSInterface::MapMemory(hMapFile, 0, nullptr, *pdwFileSize, + VMToOSInterface::MemoryProtection::ReadOnly, true); + VMToOSInterface::CloseMemoryMapping(hMapFile); + VMToOSInterface::CloseFile(hFile); if (!*ppbMap) - MDInfo::Error("MapViewOfFile failed!"); + MDInfo::Error("MapMemory failed!"); } // void GetMapViewOfFile() // This function skips a member given the pointer to the member header @@ -241,7 +237,7 @@ void DisplayArchive(_In_z_ WCHAR* szFile, ULONG DumpFilter, _In_opt_z_ WCHAR* sz pbMapAddress = SkipMember(pbMapAddress); } - UnmapViewOfFile(pbStartAddress); + VMToOSInterface::UnmapMemory(pbStartAddress, dwFileSize); } // void DisplayArchive() // DisplayFile() function diff --git a/src/coreclr/tools/superpmi/mcs/removedup.cpp b/src/coreclr/tools/superpmi/mcs/removedup.cpp index b2ba784e633f15..6507aeb7705b3a 100644 --- a/src/coreclr/tools/superpmi/mcs/removedup.cpp +++ b/src/coreclr/tools/superpmi/mcs/removedup.cpp @@ -118,7 +118,7 @@ bool RemoveDup::uniqueLegacy(MethodContext* mc) return true; } -bool RemoveDup::CopyAndRemoveDups(const char* nameOfInput, HANDLE hFileOut) +bool RemoveDup::CopyAndRemoveDups(const char* nameOfInput, FILE* hFileOut) { MethodContextIterator mci(/* progressReport */ true); if (!mci.Initialize(nameOfInput)) diff --git a/src/coreclr/tools/superpmi/mcs/removedup.h b/src/coreclr/tools/superpmi/mcs/removedup.h index ee14e636ef7fff..7d035e5e21e3e8 100644 --- a/src/coreclr/tools/superpmi/mcs/removedup.h +++ b/src/coreclr/tools/superpmi/mcs/removedup.h @@ -35,7 +35,7 @@ class RemoveDup ~RemoveDup(); - bool CopyAndRemoveDups(const char* nameOfInput, HANDLE hFileOut); + bool CopyAndRemoveDups(const char* nameOfInput, FILE* hFileOut); private: diff --git a/src/coreclr/tools/superpmi/mcs/verbasmdump.cpp b/src/coreclr/tools/superpmi/mcs/verbasmdump.cpp index 6d70077b8c7a4e..145fe1d414b939 100644 --- a/src/coreclr/tools/superpmi/mcs/verbasmdump.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbasmdump.cpp @@ -28,31 +28,29 @@ int verbASMDump::DoWork(const char* nameOfInput, const char* nameOfOutput, int i char buff[500]; sprintf_s(buff, 500, "%s-%d.asm", nameOfOutput, mci.MethodContextNumber()); - HANDLE hFileOut = CreateFileA(buff, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(buff, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open output '%s'. GetLastError()=%u", buff, GetLastError()); + LogError("Failed to open output '%s'. errno=%d", buff, errno); return -1; } if (mc->cr->IsEmpty()) { const size_t bufflen = 4096; - DWORD bytesWritten; char buff[bufflen]; ZeroMemory(buff, bufflen * sizeof(char)); int buff_offset = sprintf_s(buff, bufflen, ";;Method context has no compile result"); - WriteFile(hFileOut, buff, buff_offset * sizeof(char), &bytesWritten, nullptr); + fwrite(buff, 1, buff_offset * sizeof(char), hFileOut); } else { ASMDumper::DumpToFile(hFileOut, mc, mc->cr); } - if (!CloseHandle(hFileOut)) + if (fclose(hFileOut) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); return -1; } savedCount++; diff --git a/src/coreclr/tools/superpmi/mcs/verbconcat.cpp b/src/coreclr/tools/superpmi/mcs/verbconcat.cpp index 9d6f7b39c0e291..3c71e4ca35f5d4 100644 --- a/src/coreclr/tools/superpmi/mcs/verbconcat.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbconcat.cpp @@ -14,67 +14,42 @@ int verbConcat::DoWork(const char* nameOfFile1, const char* nameOfFile2) LogVerbose("Concatenating '%s'+'%s' into %s", nameOfFile1, nameOfFile2, nameOfFile1); - LARGE_INTEGER DataTemp1; - LARGE_INTEGER DataTemp2; - - HANDLE hFileIn1 = CreateFileA(nameOfFile1, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileIn1 == INVALID_HANDLE_VALUE) - { - LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfFile1, GetLastError()); - return -1; - } - if (GetFileSizeEx(hFileIn1, &DataTemp1) == 0) - { - LogError("GetFileSizeEx failed. GetLastError()=%u", GetLastError()); - return -1; - } - - LONG highDWORD = 0; - DWORD dwPtr = SetFilePointer(hFileIn1, 0, &highDWORD, FILE_END); - if (dwPtr == INVALID_SET_FILE_POINTER) + FILE* hFileIn1 = fopen(nameOfFile1, "ab"); + if (hFileIn1 == nullptr) { - LogError("Failed to SetFilePointer on input 1 '%s'. GetLastError()=%u", nameOfFile1, GetLastError()); + LogError("Failed to open input 1 '%s'. errno=%d", nameOfFile1, errno); return -1; } - HANDLE hFileIn2 = CreateFileA(nameOfFile2, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileIn2 == INVALID_HANDLE_VALUE) + FILE* hFileIn2 = fopen(nameOfFile2, "rb"); + if (hFileIn2 == nullptr) { - LogError("Failed to open input 2 '%s'. GetLastError()=%u", nameOfFile2, GetLastError()); + LogError("Failed to open input 2 '%s'. errno=%d", nameOfFile2, errno); return -1; } - if (GetFileSizeEx(hFileIn2, &DataTemp2) == 0) + int64_t fileSize2 = fgetsize(hFileIn2); + if (fileSize2 < 0) { - LogError("2nd GetFileSizeEx failed. GetLastError()=%u", GetLastError()); + LogError("fgetsize failed. errno=%d", errno); return -1; } unsigned char* buffer = new unsigned char[BUFFER_SIZE]; st1.Start(); - for (LONGLONG offset = 0; offset < DataTemp2.QuadPart; offset += BUFFER_SIZE) + for (LONGLONG offset = 0; offset < fileSize2; offset += BUFFER_SIZE) { - DWORD bytesRead = -1; - BOOL res = ReadFile(hFileIn2, buffer, BUFFER_SIZE, &bytesRead, nullptr); - if (res == 0) - { - LogError("Failed to read '%s' from offset %lld. GetLastError()=%u", nameOfFile2, offset, GetLastError()); - delete[] buffer; - return -1; - } - DWORD bytesWritten = -1; - BOOL res2 = WriteFile(hFileIn1, buffer, bytesRead, &bytesWritten, nullptr); - if (res2 == 0) + size_t bytesRead = fread(buffer, 1, BUFFER_SIZE, hFileIn2); + if (ferror(hFileIn2)) { - LogError("Failed to write '%s' at offset %lld. GetLastError()=%u", nameOfFile1, offset, GetLastError()); + LogError("Failed to read '%s' from offset %lld. errno=%d", nameOfFile2, offset, errno); delete[] buffer; return -1; } + size_t bytesWritten = fwrite(buffer, 1, bytesRead, hFileIn1); if (bytesRead != bytesWritten) { - LogError("Failed to read/write matching bytes %u!=%u", bytesRead, bytesWritten); + LogError("Failed to write '%s' at offset %lld. errno=%d", nameOfFile1, offset, errno); delete[] buffer; return -1; } @@ -83,19 +58,19 @@ int verbConcat::DoWork(const char* nameOfFile1, const char* nameOfFile2) delete[] buffer; - if (CloseHandle(hFileIn1) == 0) + if (fclose(hFileIn1) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); return -1; } - if (CloseHandle(hFileIn2) == 0) + if (fclose(hFileIn2) != 0) { - LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("2nd fclose failed. errno=%d", errno); return -1; } - LogInfo("Read/Wrote %lld MB @ %4.2f MB/s.\n", DataTemp2.QuadPart / (1000 * 1000), - (((double)DataTemp2.QuadPart) / (1000 * 1000)) / + LogInfo("Read/Wrote %lld MB @ %4.2f MB/s.\n", fileSize2 / (1000 * 1000), + (((double)fileSize2) / (1000 * 1000)) / st1.GetSeconds()); // yes yes.. http://en.wikipedia.org/wiki/Megabyte_per_second#Megabyte_per_second return 0; diff --git a/src/coreclr/tools/superpmi/mcs/verbfracture.cpp b/src/coreclr/tools/superpmi/mcs/verbfracture.cpp index 549e4ed9322149..af3862e7efb4b0 100644 --- a/src/coreclr/tools/superpmi/mcs/verbfracture.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbfracture.cpp @@ -24,28 +24,27 @@ int verbFracture::DoWork( int fileCount = 0; char fileName[512]; - HANDLE hFileOut = INVALID_HANDLE_VALUE; + FILE* hFileOut = nullptr; while (mci.MoveNext()) { MethodContext* mc = mci.Current(); - if ((hFileOut == INVALID_HANDLE_VALUE) || (((mci.MethodContextNumber() - 1) % rangeSize) == 0)) + if ((hFileOut == nullptr) || (((mci.MethodContextNumber() - 1) % rangeSize) == 0)) { - if (hFileOut != INVALID_HANDLE_VALUE) + if (hFileOut != nullptr) { - if (!CloseHandle(hFileOut)) + if (fclose(hFileOut) != 0) { - LogError("1st CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("1st fclose failed. errno=%d", errno); return -1; } - hFileOut = INVALID_HANDLE_VALUE; + hFileOut = nullptr; } sprintf_s(fileName, 512, "%s-%0*d.mch", nameOfOutput, 5, fileCount++); - hFileOut = CreateFileA(fileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + hFileOut = fopen(fileName, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open output file '%s'. GetLastError()=%u", fileName, GetLastError()); + LogError("Failed to open output file '%s'. errno=%d", fileName, errno); return -1; } } @@ -57,11 +56,11 @@ int verbFracture::DoWork( mc->saveToFile(hFileOut); } - if (hFileOut != INVALID_HANDLE_VALUE) + if (hFileOut != nullptr) { - if (!CloseHandle(hFileOut)) + if (fclose(hFileOut) != 0) { - LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("2nd fclose failed. errno=%d", errno); return -1; } } diff --git a/src/coreclr/tools/superpmi/mcs/verbmerge.cpp b/src/coreclr/tools/superpmi/mcs/verbmerge.cpp index 35b7263d4a68b7..66c2f46a7ef768 100644 --- a/src/coreclr/tools/superpmi/mcs/verbmerge.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbmerge.cpp @@ -69,52 +69,41 @@ WCHAR* verbMerge::ConvertMultiByteToWideChar(LPCSTR str) // 'buffer' is memory that can be used to do reading/buffering. // // static -int verbMerge::AppendFileRaw(HANDLE hFileOut, LPCWSTR fileFullPath, unsigned char* buffer, size_t bufferSize) +int verbMerge::AppendFileRaw(FILE* hFileOut, LPCWSTR fileFullPath, unsigned char* buffer, size_t bufferSize) { int result = 0; // default to zero == success char* fileNameAsChar = ConvertWideCharToMultiByte(fileFullPath); LogInfo("Appending file '%s'", fileNameAsChar); - HANDLE hFileIn = CreateFileW(fileFullPath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileIn == INVALID_HANDLE_VALUE) + FILE* hFileIn; + if (u16_fopen_s(&hFileIn, fileFullPath, W("rb")) != 0) { - // If you use a relative path, you can get GetLastError()==3, if the absolute path is longer - // than MAX_PATH. - LogError("Failed to open input file '%s'. GetLastError()=%u", fileNameAsChar, GetLastError()); + LogError("Failed to open input file '%s'. errno=%d", fileNameAsChar, errno); return -1; } - LARGE_INTEGER fileSize; - if (GetFileSizeEx(hFileIn, &fileSize) == 0) + int64_t fileSize = fgetsize(hFileIn); + if (fileSize < 0) { - LogError("GetFileSizeEx on '%s' failed. GetLastError()=%u", fileNameAsChar, GetLastError()); + LogError("fgetsize on '%s' failed. errno=%d", fileNameAsChar, errno); result = -1; goto CLEAN_UP; } - for (LONGLONG offset = 0; offset < fileSize.QuadPart; offset += bufferSize) + for (LONGLONG offset = 0; offset < fileSize; offset += bufferSize) { - DWORD bytesRead = -1; - BOOL res = ReadFile(hFileIn, buffer, (DWORD)bufferSize, &bytesRead, nullptr); - if (!res) + size_t bytesRead = fread(buffer, 1, bufferSize, hFileIn); + if (ferror(hFileIn)) { - LogError("Failed to read '%s' from offset %lld. GetLastError()=%u", fileNameAsChar, offset, GetLastError()); - result = -1; - goto CLEAN_UP; - } - DWORD bytesWritten = -1; - BOOL res2 = WriteFile(hFileOut, buffer, bytesRead, &bytesWritten, nullptr); - if (!res2) - { - LogError("Failed to write output file at offset %lld. GetLastError()=%u", offset, GetLastError()); + LogError("Failed to read '%s' from offset %lld. errno=%d", fileNameAsChar, offset, errno); result = -1; goto CLEAN_UP; } + size_t bytesWritten = fwrite(buffer, 1, bytesRead, hFileOut); if (bytesRead != bytesWritten) { - LogError("Failed to read/write matching bytes %u!=%u", bytesRead, bytesWritten); + LogError("Failed to write output file at offset %lld. errno=%d", offset, errno); result = -1; goto CLEAN_UP; } @@ -124,9 +113,9 @@ int verbMerge::AppendFileRaw(HANDLE hFileOut, LPCWSTR fileFullPath, unsigned cha delete[] fileNameAsChar; - if (CloseHandle(hFileIn) == 0) + if (fclose(hFileIn) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); result = -1; } @@ -139,7 +128,7 @@ int verbMerge::AppendFileRaw(HANDLE hFileOut, LPCWSTR fileFullPath, unsigned cha // 'buffer' is memory that can be used to do reading/buffering. // // static -int verbMerge::AppendFile(HANDLE hFileOut, LPCWSTR fileFullPath, bool dedup, unsigned char* buffer, size_t bufferSize) +int verbMerge::AppendFile(FILE* hFileOut, LPCWSTR fileFullPath, bool dedup, unsigned char* buffer, size_t bufferSize) { int result = 0; // default to zero == success @@ -454,7 +443,7 @@ int verbMerge::FilterDirectory(LPCWSTR dir, // Append all files in the given directory matching the file pattern. // // static -int verbMerge::AppendAllInDir(HANDLE hFileOut, +int verbMerge::AppendAllInDir(FILE* hFileOut, LPCWSTR dir, LPCWSTR file, unsigned char* buffer, @@ -631,11 +620,10 @@ int verbMerge::DoWork(const char* nameOfOutputFile, const char* pattern, bool re LPWSTR patternAsWchar = new WCHAR[patternLength]; MultiByteToWideChar(CP_ACP, 0, pattern, -1, patternAsWchar, patternLength); - HANDLE hFileOut = CreateFileW(nameOfOutputFileAsWchar, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutputFile, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open output file '%s'. GetLastError()=%u", nameOfOutputFile, GetLastError()); + LogError("Failed to open output file '%s'. errno=%d", nameOfOutputFile, errno); return -1; } @@ -708,9 +696,9 @@ int verbMerge::DoWork(const char* nameOfOutputFile, const char* pattern, bool re delete[] patternAsWchar; delete[] buffer; - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); result = -1; } @@ -720,7 +708,7 @@ int verbMerge::DoWork(const char* nameOfOutputFile, const char* pattern, bool re int st = remove(nameOfOutputFile); if (st != 0) { - LogError("Failed to delete file after MCS /merge failed. GetLastError()=%u", GetLastError()); + LogError("Failed to delete file after MCS /merge failed. errno=%d", errno); } } else diff --git a/src/coreclr/tools/superpmi/mcs/verbmerge.h b/src/coreclr/tools/superpmi/mcs/verbmerge.h index ce1eee96b7c522..e03ad869600ca1 100644 --- a/src/coreclr/tools/superpmi/mcs/verbmerge.h +++ b/src/coreclr/tools/superpmi/mcs/verbmerge.h @@ -83,9 +83,9 @@ class verbMerge static char* ConvertWideCharToMultiByte(LPCWSTR wstr); static WCHAR* ConvertMultiByteToWideChar(LPCSTR str); - static int AppendFileRaw(HANDLE hFileOut, LPCWSTR fileFullPath, unsigned char* buffer, size_t bufferSize); - static int AppendFile(HANDLE hFileOut, LPCWSTR fileFullPath, bool dedup, unsigned char* buffer, size_t bufferSize); - static int AppendAllInDir(HANDLE hFileOut, + static int AppendFileRaw(FILE* hFileOut, LPCWSTR fileFullPath, unsigned char* buffer, size_t bufferSize); + static int AppendFile(FILE* hFileOut, LPCWSTR fileFullPath, bool dedup, unsigned char* buffer, size_t bufferSize); + static int AppendAllInDir(FILE* hFileOut, LPCWSTR dir, LPCWSTR file, unsigned char* buffer, diff --git a/src/coreclr/tools/superpmi/mcs/verbremovedup.cpp b/src/coreclr/tools/superpmi/mcs/verbremovedup.cpp index a67f7f8debc400..9a4e145d082af4 100644 --- a/src/coreclr/tools/superpmi/mcs/verbremovedup.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbremovedup.cpp @@ -9,11 +9,10 @@ int verbRemoveDup::DoWork(const char* nameOfInput, const char* nameOfOutput, boo { LogVerbose("Removing duplicates from '%s', writing to '%s'", nameOfInput, nameOfOutput); - HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutput, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open output '%s'. GetLastError()=%u", nameOfOutput, GetLastError()); + LogError("Failed to open output '%s'. errno=%d", nameOfOutput, errno); return -1; } @@ -25,9 +24,9 @@ int verbRemoveDup::DoWork(const char* nameOfInput, const char* nameOfOutput, boo return -1; } - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); return -1; } diff --git a/src/coreclr/tools/superpmi/mcs/verbstat.cpp b/src/coreclr/tools/superpmi/mcs/verbstat.cpp index e3cc44de1a0317..354e14cffe8153 100644 --- a/src/coreclr/tools/superpmi/mcs/verbstat.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbstat.cpp @@ -18,16 +18,14 @@ int verbStat::DoWork(const char* nameOfInput, const char* nameOfOutput, int inde int savedCount = 0; - HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutput, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError()); + LogError("Failed to open input 1 '%s'. errno=%d", nameOfOutput, errno); return -1; } #define bufflen 50000 - DWORD bytesWritten; char buff[bufflen]; int offset = 0; ZeroMemory(&buff[0], bufflen); @@ -35,7 +33,7 @@ int verbStat::DoWork(const char* nameOfInput, const char* nameOfOutput, int inde offset += MethodContext::dumpStatTitleToBuffer(&buff[offset], bufflen - offset); buff[offset++] = 0x0d; buff[offset++] = 0x0a; - WriteFile(hFileOut, &buff[0], offset, &bytesWritten, nullptr); + fwrite(&buff[0], 1, offset, hFileOut); while (mci.MoveNext()) { @@ -54,13 +52,13 @@ int verbStat::DoWork(const char* nameOfInput, const char* nameOfOutput, int inde offset += mc->dumpStatToBuffer(&buff[offset], bufflen - offset); buff[offset++] = 0x0d; buff[offset++] = 0x0a; - WriteFile(hFileOut, &buff[0], offset, &bytesWritten, nullptr); + fwrite(&buff[0], 1, offset, hFileOut); savedCount++; } - if (!CloseHandle(hFileOut)) + if (fclose(hFileOut) != 0) { - LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("2nd fclose failed. errno=%d", errno); return -1; } diff --git a/src/coreclr/tools/superpmi/mcs/verbstrip.cpp b/src/coreclr/tools/superpmi/mcs/verbstrip.cpp index 5f76e1021ffdc9..0e06149ba5dfe9 100644 --- a/src/coreclr/tools/superpmi/mcs/verbstrip.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbstrip.cpp @@ -33,11 +33,10 @@ int verbStrip::DoWork( return -1; } - HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutput, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError()); + LogError("Failed to open input 1 '%s'. errno=%d", nameOfOutput, errno); return -1; } @@ -71,9 +70,9 @@ int verbStrip::DoWork( savedCount++; delete mc; } - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("2nd fclose failed. errno=%d", errno); return -1; } LogInfo("Loaded %d, Saved %d", loadedCount, savedCount); @@ -95,11 +94,10 @@ int verbStrip::DoWorkTheOldWay( bool write; int index = 0; // Can't use MethodContextIterator indexing, since we want the opposite of that. - HANDLE hFileOut = CreateFileA(nameOfOutput, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutput, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError()); + LogError("Failed to open input 1 '%s'. errno=%d", nameOfOutput, errno); return -1; } @@ -129,9 +127,9 @@ int verbStrip::DoWorkTheOldWay( } } - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("2nd CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("2nd fclose failed. errno=%d", errno); return -1; } diff --git a/src/coreclr/tools/superpmi/mcs/verbtoc.cpp b/src/coreclr/tools/superpmi/mcs/verbtoc.cpp index d2a384388c12fd..13925416eca53e 100644 --- a/src/coreclr/tools/superpmi/mcs/verbtoc.cpp +++ b/src/coreclr/tools/superpmi/mcs/verbtoc.cpp @@ -55,48 +55,44 @@ int verbTOC::DoWork(const char* nameOfInput) char* nameOfOutput = (char*)_alloca(maxLen); strcpy_s(nameOfOutput, maxLen, nameOfInput); strcat_s(nameOfOutput, maxLen, ".mct"); - HANDLE hFileOut = - CreateFileA(nameOfOutput, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(nameOfOutput, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open input 1 '%s'. GetLastError()=%u", nameOfOutput, GetLastError()); + LogError("Failed to open input 1 '%s'. errno=%d", nameOfOutput, errno); return -1; } - DWORD written; // Write out the signature "INDX" and then the element count LARGE_INTEGER token; token.u.LowPart = *(const int*)"INDX"; // cuz Type Safety is for languages that have good IO facilities token.u.HighPart = savedCount; - if (!WriteFile(hFileOut, &token, sizeof(token), &written, nullptr) || written != sizeof(token)) + if (fwrite(&token, 1, sizeof(token), hFileOut) != sizeof(token)) { - LogError("Failed to write index header. GetLastError()=%u", GetLastError()); + LogError("Failed to write index header. errno=%d", errno); } // Now just dump sizeof(TOCElement) byte chunks into the file. // I could probably do this more efficiently, but I don't think it matters - DWORD chunkSize = sizeof(TOCElement); + size_t chunkSize = sizeof(TOCElement); for (curElem = head; curElem != nullptr; curElem = curElem->Next) { - if (!WriteFile(hFileOut, &curElem->tocElement, chunkSize, &written, nullptr) || written != chunkSize) + if (fwrite(&curElem->tocElement, 1, chunkSize, hFileOut) != chunkSize) { - LogError("Failed to write index element '%d'. GetLastError()=%u", curElem->tocElement.Number, - GetLastError()); + LogError("Failed to write index element '%d'. errno=%d", curElem->tocElement.Number, errno); return -1; } } // Now write out a final "INDX" to flag the end of the file... - if (!WriteFile(hFileOut, &token.u.LowPart, sizeof(token.u.LowPart), &written, nullptr) || - (written != sizeof(token.u.LowPart))) + if (fwrite(&token.u.LowPart, 1, sizeof(token.u.LowPart), hFileOut) != sizeof(token.u.LowPart)) { - LogError("Failed to write index terminal. GetLastError()=%u", GetLastError()); + LogError("Failed to write index terminal. errno=%d", errno); } LogInfo("Loaded %d, added %d to Table of Contents", mci.MethodContextNumber(), savedCount); - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); return -1; } diff --git a/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp index 471033ad2d3906..b88dd04a3e4ec6 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.cpp @@ -4,7 +4,7 @@ #include "standardpch.h" #include "asmdumper.h" -void ASMDumper::DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr) +void ASMDumper::DumpToFile(FILE* hFile, MethodContext* mc, CompileResult* cr) { CORINFO_METHOD_INFO info; unsigned flags = 0; @@ -12,7 +12,6 @@ void ASMDumper::DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr) mc->repCompileMethod(&info, &flags, &os); #define bufflen 4096 - DWORD bytesWritten; char buff[bufflen]; int buff_offset = 0; @@ -22,7 +21,7 @@ void ASMDumper::DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr) buff_offset += sprintf_s(&buff[buff_offset], bufflen - buff_offset, "\r\n Method Name \"%s\"", getMethodName(mc, info.ftn).c_str()); - WriteFile(hFile, buff, buff_offset * sizeof(char), &bytesWritten, nullptr); + fwrite(buff, sizeof(char), buff_offset, hFile); ULONG hotCodeSize; ULONG coldCodeSize; @@ -90,7 +89,7 @@ void ASMDumper::DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr) for (unsigned int i = 0; i < instrSize; i++) buff_offset += sprintf_s(&buff[buff_offset], bufflen - buff_offset, "%02x ", *((BYTE*)(hotCodeBlock + offset + i))); - WriteFile(hFile, buff, buff_offset * sizeof(char), &bytesWritten, nullptr); + fwrite(buff, sizeof(char), buff_offset, hFile); offset += instrSize; } @@ -101,9 +100,9 @@ void ASMDumper::DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr) buff_offset = 0; ZeroMemory(buff, bufflen * sizeof(char)); buff_offset += sprintf_s(&buff[buff_offset], bufflen - buff_offset, ";; No disassembler available"); - WriteFile(hFile, buff, buff_offset * sizeof(char), &bytesWritten, nullptr); + fwrite(buff, sizeof(char), buff_offset, hFile); #endif // !USE_MSVCDIS - FlushFileBuffers(hFile); + fflush(hFile); } diff --git a/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h index 90af3ef16febfc..a6af67115f8815 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/asmdumper.h @@ -11,7 +11,7 @@ class ASMDumper { public: - static void DumpToFile(HANDLE hFile, MethodContext* mc, CompileResult* cr); + static void DumpToFile(FILE* hFile, MethodContext* mc, CompileResult* cr); }; #endif diff --git a/src/coreclr/tools/superpmi/superpmi-shared/logging.cpp b/src/coreclr/tools/superpmi/superpmi-shared/logging.cpp index a0de0cda60d122..873d644f568403 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/logging.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/logging.cpp @@ -18,7 +18,7 @@ bool Logger::s_initialized = false; UINT32 Logger::s_logLevel = LOGMASK_DEFAULT; -HANDLE Logger::s_logFile = INVALID_HANDLE_VALUE; +FILE* Logger::s_logFile = nullptr; char* Logger::s_logFilePath = nullptr; minipal_mutex Logger::s_critSec; @@ -55,12 +55,11 @@ void Logger::Shutdown() /* static */ void Logger::OpenLogFile(const char* logFilePath) { - if (s_logFile == INVALID_HANDLE_VALUE && logFilePath != nullptr) + if (s_logFile == nullptr && logFilePath != nullptr) { - s_logFile = CreateFileA(logFilePath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); + s_logFile = fopen(logFilePath, "wb"); - if (s_logFile != INVALID_HANDLE_VALUE) + if (s_logFile != nullptr) { // We may need the file path later in order to delete the log file s_logFilePath = _strdup(logFilePath); @@ -79,22 +78,18 @@ void Logger::OpenLogFile(const char* logFilePath) /* static */ void Logger::CloseLogFile() { - if (s_logFile != INVALID_HANDLE_VALUE) + if (s_logFile != nullptr) { // Avoid polluting the file system with empty log files - if (GetFileSize(s_logFile, nullptr) == 0 && s_logFilePath != nullptr) - { - // We can call this before closing the handle because remove just marks the file - // for deletion, i.e. it does not actually get deleted until its last handle is closed. - if (remove(s_logFilePath) == -1) - fprintf(stderr, "WARNING: [Logger::CloseLogFile] remove failed. GetLastError()=%u\n", - GetLastError()); - } + bool isEmpty = fgetsize(s_logFile) == 0; - if (!CloseHandle(s_logFile)) - fprintf(stderr, "WARNING: [Logger::CloseLogFile] CloseHandle failed. GetLastError()=%u\n", GetLastError()); + if (fclose(s_logFile) != 0) + fprintf(stderr, "WARNING: [Logger::CloseLogFile] fclose failed. errno=%d\n", errno); - s_logFile = INVALID_HANDLE_VALUE; + s_logFile = nullptr; + + if (isEmpty && s_logFilePath != nullptr && remove(s_logFilePath) == -1) + fprintf(stderr, "WARNING: [Logger::CloseLogFile] remove failed. errno=%d\n", errno); free(s_logFilePath); s_logFilePath = nullptr; @@ -251,7 +246,7 @@ void Logger::LogVprintf( fprintf(dest, "%s\n", fullMsg); - if (s_logFile != INVALID_HANDLE_VALUE) + if (s_logFile != nullptr) { #ifndef TARGET_UNIX // TODO: no localtime_s() or strftime() in PAL tm timeInfo; @@ -284,15 +279,11 @@ void Logger::LogVprintf( sprintf_s(logEntry, logEntryBuffSize, logEntryFmtStr, timeStr, function, file, line, logLevelStr, fullMsg); size_t logEntryLen = strlen(logEntry); - DWORD bytesWritten; - - if (!WriteFile(s_logFile, logEntry, (DWORD)logEntryLen, &bytesWritten, nullptr)) - fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to write to log file. GetLastError()=%u\n", - GetLastError()); + if (fwrite(logEntry, 1, logEntryLen, s_logFile) != logEntryLen) + fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to write to log file. errno=%d\n", errno); - if (!FlushFileBuffers(s_logFile)) - fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to flush log file. GetLastError()=%u\n", - GetLastError()); + if (fflush(s_logFile) != 0) + fprintf(stderr, "WARNING: [Logger::LogVprintf] Failed to flush log file. errno=%d\n", errno); delete[] logEntry; diff --git a/src/coreclr/tools/superpmi/superpmi-shared/logging.h b/src/coreclr/tools/superpmi/superpmi-shared/logging.h index 83559df9befdbf..57685260cee097 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/logging.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/logging.h @@ -65,7 +65,7 @@ class Logger private: static bool s_initialized; static UINT32 s_logLevel; - static HANDLE s_logFile; + static FILE* s_logFile; static char* s_logFilePath; static minipal_mutex s_critSec; diff --git a/src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp b/src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp index 79dca0cdc766ae..04c38d47d7c169 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/mclist.cpp @@ -151,38 +151,36 @@ bool MCList::processArgAsMCL(char* input, int* count, int** list) /* static */ bool MCList::getLineData(const char* nameOfInput, /* OUT */ int* pIndexCount, /* OUT */ int** pIndexes) { - HANDLE hFile = CreateFileA(nameOfInput, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFile == INVALID_HANDLE_VALUE) + FILE* hFile = fopen(nameOfInput, "rb"); + if (hFile == nullptr) { - LogError("Unable to open '%s'. GetLastError()=%u", nameOfInput, GetLastError()); + LogError("Unable to open '%s'. errno=%d", nameOfInput, errno); return false; } - LARGE_INTEGER DataTemp; - if (!GetFileSizeEx(hFile, &DataTemp)) + int64_t fileSize = fgetsize(hFile); + if (fileSize < 0) { - LogError("GetFileSizeEx failed. GetLastError()=%u", GetLastError()); + LogError("fgetsize failed. errno=%d", errno); return false; } - if (DataTemp.QuadPart > MAXMCLFILESIZE) + if (fileSize > MAXMCLFILESIZE) { - LogError("Size %d exceeds max size of %d", DataTemp.QuadPart, MAXMCLFILESIZE); + LogError("Size %lld exceeds max size of %d", (long long)fileSize, MAXMCLFILESIZE); return false; } - int sz = DataTemp.u.LowPart; + int sz = (int)fileSize; char* buff = new char[sz]; - DWORD bytesRead; - if (ReadFile(hFile, buff, sz, &bytesRead, nullptr) == 0) + if (fread(buff, 1, sz, hFile) != (size_t)sz) { - LogError("ReadFile failed. GetLastError()=%u", GetLastError()); + LogError("fread failed. errno=%d", errno); delete[] buff; return false; } - if (!CloseHandle(hFile)) + if (fclose(hFile) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); delete[] buff; return false; } @@ -221,37 +219,37 @@ bool MCList::getLineData(const char* nameOfInput, /* OUT */ int* pIndexCount, /* void MCList::InitializeMCL(char* filename) { - hMCLFile = CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hMCLFile == INVALID_HANDLE_VALUE) + hMCLFile = fopen(filename, "wb"); + if (hMCLFile == nullptr) { - LogError("Failed to open output file '%s'. GetLastError()=%u", filename, GetLastError()); + LogError("Failed to open output file '%s'. errno=%d", filename, errno); } } void MCList::AddMethodToMCL(int methodIndex) { - if (hMCLFile != INVALID_HANDLE_VALUE) + if (hMCLFile != nullptr) { char strMethodIndex[12]; DWORD charCount = 0; - DWORD bytesWritten = 0; charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", methodIndex); - if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || bytesWritten != charCount) + if (fwrite(strMethodIndex, 1, charCount, hMCLFile) != charCount) { - LogError("Failed to write method index '%d'. GetLastError()=%u", strMethodIndex, GetLastError()); + LogError("Failed to write method index '%d'. errno=%d", methodIndex, errno); } } } void MCList::CloseMCL() { - if (hMCLFile != INVALID_HANDLE_VALUE) + if (hMCLFile != nullptr) { - if (CloseHandle(hMCLFile) == 0) + if (fclose(hMCLFile) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); } + hMCLFile = nullptr; } } diff --git a/src/coreclr/tools/superpmi/superpmi-shared/mclist.h b/src/coreclr/tools/superpmi/superpmi-shared/mclist.h index 44291f0600a0e0..5c4ec5baea311f 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/mclist.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/mclist.h @@ -16,7 +16,7 @@ class MCList MCList() { // Initialize the static file handle - hMCLFile = INVALID_HANDLE_VALUE; + hMCLFile = nullptr; } // Methods to create an MCL file @@ -28,6 +28,6 @@ class MCList static bool getLineData(const char* nameOfInput, /* OUT */ int* pIndexCount, /* OUT */ int** pIndexes); // File handle for MCL file - HANDLE hMCLFile; + FILE* hMCLFile; }; #endif diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp index f8b57daaf65764..4d8e7f5661ef56 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.cpp @@ -144,13 +144,13 @@ unsigned int MethodContext::calculateRawFileSize() 2 /* end canary '4', '2' */; } -unsigned int MethodContext::saveToFile(HANDLE hFile) +unsigned int MethodContext::saveToFile(FILE* hFile) { unsigned int totalLen = calculateFileSize(); unsigned int totalFileSize = 2 /* leading magic cookie 'm', 'c' */ + 4 /* 4-byte data length */ + totalLen + 2 /* end canary '4', '2' */; - DWORD bytesWritten = 0; + unsigned int bytesWritten = 0; unsigned int buffIndex = 0; unsigned char* buff2 = new unsigned char[totalFileSize]; buff2[buffIndex++] = 'm'; @@ -171,7 +171,7 @@ unsigned int MethodContext::saveToFile(HANDLE hFile) Assert(buffIndex == totalFileSize); - WriteFile(hFile, buff2, totalFileSize, &bytesWritten, NULL); + bytesWritten = (unsigned int)fwrite(buff2, 1, totalFileSize, hFile); delete[] buff2; return bytesWritten; } @@ -189,7 +189,7 @@ bool MethodContext::Initialize(int mcIndex, unsigned char* buff, DWORD size, boo } // static -bool MethodContext::Initialize(int mcIndex, HANDLE hFile, bool readCompileResults, /* OUT */ MethodContext** ppmc) +bool MethodContext::Initialize(int mcIndex, FILE* hFile, bool readCompileResults, /* OUT */ MethodContext** ppmc) { MethodContext* mc = new MethodContext(); mc->index = mcIndex; @@ -226,13 +226,13 @@ bool MethodContext::Initialize(int mcIndex, unsigned char* buff, DWORD size, boo return result; } -bool MethodContext::Initialize(int mcIndex, HANDLE hFile, bool readCompileResults) +bool MethodContext::Initialize(int mcIndex, FILE* hFile, bool readCompileResults) { bool result = true; struct Param { - HANDLE hFile; + FILE* hFile; MethodContext* pThis; bool readCompileResults; } param; @@ -254,18 +254,17 @@ bool MethodContext::Initialize(int mcIndex, HANDLE hFile, bool readCompileResult return result; } -void MethodContext::MethodInitHelperFile(HANDLE hFile, bool readCompileResults) +void MethodContext::MethodInitHelperFile(FILE* hFile, bool readCompileResults) { - DWORD bytesRead; char buff[512]; unsigned int totalLen = 0; - AssertCode(ReadFile(hFile, buff, 2 + sizeof(unsigned int), &bytesRead, NULL) == TRUE, + AssertCode(fread(buff, 1, 2 + sizeof(unsigned int), hFile) == 2 + sizeof(unsigned int), EXCEPTIONCODE_MC); // Read Magic number and totalLen AssertCodeMsg((buff[0] == 'm') && (buff[1] == 'c'), EXCEPTIONCODE_MC, "Didn't find magic number"); memcpy(&totalLen, &buff[2], sizeof(unsigned int)); unsigned char* buff2 = new unsigned char[totalLen + 2]; // total + End Canary - AssertCode(ReadFile(hFile, buff2, totalLen + 2, &bytesRead, NULL) == TRUE, EXCEPTIONCODE_MC); + AssertCode(fread(buff2, 1, totalLen + 2, hFile) == totalLen + 2, EXCEPTIONCODE_MC); AssertCodeMsg((buff2[totalLen] == '4') && (buff2[totalLen + 1] == '2'), EXCEPTIONCODE_MC, "Didn't find end canary"); MethodInitHelper(buff2, totalLen, readCompileResults); } diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h index 08c742551f0b27..df418037bc92d4 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontext.h @@ -68,16 +68,16 @@ class MethodContext private: void MethodInitHelper(unsigned char* buff, unsigned int totalLen, bool readCompileResults); - void MethodInitHelperFile(HANDLE hFile, bool readCompileResults); + void MethodInitHelperFile(FILE* hFile, bool readCompileResults); bool Initialize(int mcIndex, unsigned char* buff, DWORD size, bool readCompileResults); - bool Initialize(int mcIndex, HANDLE hFile, bool readCompileResults); + bool Initialize(int mcIndex, FILE* hFile, bool readCompileResults); int dumpHashToBuffer(BYTE* pBuffer, int bufLen, char* buff, int len); public: static bool Initialize(int mcIndex, unsigned char* buff, DWORD size, bool readCompileResults, /* OUT */ MethodContext** ppmc); - static bool Initialize(int mcIndex, HANDLE hFile, bool readCompileResults, /* OUT */ MethodContext** ppmc); + static bool Initialize(int mcIndex, FILE* hFile, bool readCompileResults, /* OUT */ MethodContext** ppmc); ~MethodContext(); void Destroy(); @@ -87,7 +87,7 @@ class MethodContext } bool Equal(MethodContext* other); - unsigned int saveToFile(HANDLE hFile); + unsigned int saveToFile(FILE* hFile); unsigned int calculateFileSize(); unsigned int calculateRawFileSize(); diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp index 3cd0ecbc53b2b7..c3daa0bc997f78 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.cpp @@ -7,25 +7,22 @@ bool MethodContextIterator::Initialize(const char* fileName) { - m_hFile = CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (m_hFile == INVALID_HANDLE_VALUE) + m_hFile = fopen(fileName, "rb"); + if (m_hFile == nullptr) { - LogError("Failed to open file '%s'. GetLastError()=%u", fileName, GetLastError()); + LogError("Failed to open file '%s'. errno=%d", fileName, errno); return false; } - LARGE_INTEGER DataTemp; - if (GetFileSizeEx(m_hFile, &DataTemp) == 0) + m_fileSize = fgetsize(m_hFile); + if (m_fileSize < 0) { - LogError("GetFileSizeEx failed. GetLastError()=%u", GetLastError()); - CloseHandle(m_hFile); - m_hFile = INVALID_HANDLE_VALUE; + LogError("fgetsize failed. errno=%d", errno); + fclose(m_hFile); + m_hFile = nullptr; return false; } - m_fileSize = DataTemp.QuadPart; - if (m_progressReport) { m_timer->Start(); @@ -37,14 +34,14 @@ bool MethodContextIterator::Initialize(const char* fileName) bool MethodContextIterator::Destroy() { bool ret = true; // assume success - if (m_hFile != INVALID_HANDLE_VALUE) + if (m_hFile != nullptr) { - if (!CloseHandle(m_hFile)) + if (fclose(m_hFile) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); ret = false; } - m_hFile = INVALID_HANDLE_VALUE; + m_hFile = nullptr; } delete m_mc; m_mc = nullptr; @@ -72,15 +69,14 @@ bool MethodContextIterator::MoveNext() while (true) { // Figure out where the pointer is currently. - LARGE_INTEGER pos; - pos.QuadPart = 0; - if (SetFilePointerEx(m_hFile, pos, &m_pos, FILE_CURRENT) == 0) + m_pos = ftell_64(m_hFile); + if (m_pos < 0) { - LogError("SetFilePointerEx failed. GetLastError()=%u", GetLastError()); + LogError("ftell_64 failed. errno=%d", errno); return false; // any failure causes us to bail out. } - if (m_pos.QuadPart >= m_fileSize) + if (m_pos >= m_fileSize) { return false; } diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h index f45e85ea6e3954..34ecf523fc25f5 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextiterator.h @@ -9,7 +9,7 @@ class MethodContextIterator { public: MethodContextIterator(bool progressReport = false) - : m_hFile(INVALID_HANDLE_VALUE) + : m_hFile(nullptr) , m_fileSize(0) , m_methodContextNumber(0) , m_mc(nullptr) @@ -27,7 +27,7 @@ class MethodContextIterator } MethodContextIterator(const int indexCount, const int* indexes, bool progressReport = false) - : m_hFile(INVALID_HANDLE_VALUE) + : m_hFile(nullptr) , m_fileSize(0) , m_methodContextNumber(0) , m_mc(nullptr) @@ -73,7 +73,7 @@ class MethodContextIterator // Return the file position offset of the current method context. int64_t CurrentPos() { - return m_pos.QuadPart; + return m_pos; } int MethodContextNumber() @@ -82,11 +82,11 @@ class MethodContextIterator } private: - HANDLE m_hFile; + FILE* m_hFile; int64_t m_fileSize; int m_methodContextNumber; MethodContext* m_mc; - LARGE_INTEGER m_pos; + int64_t m_pos; // If m_indexCount==-1, use all method contexts. Otherwise, m_indexCount is the number of elements in the // m_indexes array, which contains a sorted set of method context indexes to return. In this case, m_index diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp index 73206fa3bedfae..0d2ee4d83bad81 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.cpp @@ -18,13 +18,12 @@ #endif // TARGET_UNIX // Just a helper... -HANDLE MethodContextReader::OpenFile(const char* inputFile, DWORD flags) +FILE* MethodContextReader::OpenFile(const char* inputFile) { - HANDLE fileHandle = - CreateFileA(inputFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | flags, NULL); - if (fileHandle == INVALID_HANDLE_VALUE) + FILE* fileHandle = fopen(inputFile, "rb"); + if (fileHandle == nullptr) { - LogError("Failed to open file '%s'. GetLastError()=%u", inputFile, GetLastError()); + LogError("Failed to open file '%s'. errno=%d", inputFile, errno); } return fileHandle; } @@ -83,7 +82,7 @@ std::string MethodContextReader::CheckForPairedFile(const std::string& fileName, MethodContextReader::MethodContextReader( const char* inputFileName, const int* indexes, int indexCount, char* hash, int offset, int increment) - : fileHandle(INVALID_HANDLE_VALUE) + : fileHandle(nullptr) , fileSize(0) , curMCIndex(0) , Indexes(indexes) @@ -123,11 +122,16 @@ MethodContextReader::MethodContextReader( this->tocFile.LoadToc(tocFileName.c_str()); // we'll get here even if we don't have a valid index file - this->fileHandle = OpenFile(mchFileName.c_str(), (this->hasTOC() && this->hasIndex()) ? FILE_ATTRIBUTE_NORMAL - : FILE_FLAG_SEQUENTIAL_SCAN); - if (this->fileHandle != INVALID_HANDLE_VALUE) + this->fileHandle = OpenFile(mchFileName.c_str()); + if (this->fileHandle != nullptr) { - GetFileSizeEx(this->fileHandle, (PLARGE_INTEGER) & this->fileSize); + this->fileSize = fgetsize(this->fileHandle); + if (this->fileSize < 0) + { + LogError("Failed to get the size of '%s'. errno=%d", mchFileName.c_str(), errno); + fclose(this->fileHandle); + this->fileHandle = nullptr; + } } ReadExcludedMethods(mchFileName); @@ -135,9 +139,9 @@ MethodContextReader::MethodContextReader( MethodContextReader::~MethodContextReader() { - if (fileHandle != INVALID_HANDLE_VALUE) + if (fileHandle != nullptr) { - CloseHandle(this->fileHandle); + fclose(this->fileHandle); } minipal_mutex_destroy(&this->mutex); @@ -157,30 +161,26 @@ void MethodContextReader::ReleaseLock() bool MethodContextReader::atEof() { - int64_t pos = 0; - SetFilePointerEx(this->fileHandle, *(PLARGE_INTEGER)&pos, (PLARGE_INTEGER)&pos, - FILE_CURRENT); // LARGE_INTEGER is a crime against humanity - return pos == this->fileSize; + return ftell_64(this->fileHandle) == this->fileSize; } MethodContextBuffer MethodContextReader::ReadMethodContextNoLock(bool justSkip) { - DWORD bytesRead; char buff[512]; unsigned int totalLen = 0; if (atEof()) { return MethodContextBuffer(); } - Assert(ReadFile(this->fileHandle, buff, 2 + sizeof(unsigned int), &bytesRead, NULL) == TRUE); + Assert(fread(buff, 1, 2 + sizeof(unsigned int), this->fileHandle) == 2 + sizeof(unsigned int)); AssertMsg((buff[0] == 'm') && (buff[1] == 'c'), "Didn't find magic number"); memcpy(&totalLen, &buff[2], sizeof(unsigned int)); if (justSkip) { int64_t pos = totalLen + 2; // Just move the file pointer ahead the correct number of bytes - AssertMsg(SetFilePointerEx(this->fileHandle, *(PLARGE_INTEGER)&pos, (PLARGE_INTEGER)&pos, FILE_CURRENT) == TRUE, - "SetFilePointerEx failed (Error %X)", GetLastError()); + AssertMsg(fsetpos_64(this->fileHandle, ftell_64(this->fileHandle) + pos) == 0, + "fsetpos_64 failed (errno %d)", errno); // Increment curMCIndex as we advanced the file pointer by another MC ++curMCIndex; @@ -190,7 +190,7 @@ MethodContextBuffer MethodContextReader::ReadMethodContextNoLock(bool justSkip) else { unsigned char* buff2 = new unsigned char[totalLen + 2]; // total + End Canary - Assert(ReadFile(this->fileHandle, buff2, totalLen + 2, &bytesRead, NULL) == TRUE); + Assert(fread(buff2, 1, totalLen + 2, this->fileHandle) == totalLen + 2); // Increment curMCIndex as we read another MC ++curMCIndex; @@ -417,7 +417,7 @@ bool MethodContextReader::hasTOC() bool MethodContextReader::isValid() { - return this->fileHandle != INVALID_HANDLE_VALUE; + return this->fileHandle != nullptr; } // Return a measure of "progress" through the method contexts, as follows: @@ -438,8 +438,7 @@ double MethodContextReader::Progress() else { this->AcquireLock(); - int64_t pos = 0; - SetFilePointerEx(this->fileHandle, *(PLARGE_INTEGER)&pos, (PLARGE_INTEGER)&pos, FILE_CURRENT); + int64_t pos = ftell_64(this->fileHandle); this->ReleaseLock(); return (double)pos; } @@ -512,7 +511,7 @@ MethodContextBuffer MethodContextReader::GetSpecificMethodContext(unsigned int m { return MethodContextBuffer(-2); } - if (SetFilePointerEx(this->fileHandle, *(PLARGE_INTEGER)&pos, (PLARGE_INTEGER)&pos, FILE_BEGIN)) + if (fsetpos_64(this->fileHandle, pos) == 0) { // ReadMethodContext will release the lock, but we already acquired it MethodContextBuffer mcb = this->ReadMethodContext(false); @@ -549,17 +548,16 @@ void MethodContextReader::ReadExcludedMethods(std::string mchFileName) { return; } - HANDLE excludeFileHandle = OpenFile(excludeFileName.c_str()); - if (excludeFileHandle != INVALID_HANDLE_VALUE) + FILE* excludeFileHandle = OpenFile(excludeFileName.c_str()); + if (excludeFileHandle != nullptr) { - int64_t excludeFileSizeLong; - GetFileSizeEx(excludeFileHandle, (PLARGE_INTEGER)&excludeFileSizeLong); + int64_t excludeFileSizeLong = fgetsize(excludeFileHandle); unsigned excludeFileSize = (unsigned)excludeFileSizeLong; char* buffer = new char[excludeFileSize + 1]; - DWORD bytesRead; - bool success = (ReadFile(excludeFileHandle, buffer, excludeFileSize, &bytesRead, NULL) == TRUE); - CloseHandle(excludeFileHandle); + size_t bytesRead = fread(buffer, 1, excludeFileSize, excludeFileHandle); + bool success = !ferror(excludeFileHandle); + fclose(excludeFileHandle); if (!success || excludeFileSize != bytesRead) { @@ -636,9 +634,8 @@ bool MethodContextReader::IsMethodExcluded(MethodContext* mc) void MethodContextReader::Reset(const int* newIndexes, int newIndexCount) { - int64_t pos = 0; - BOOL result = SetFilePointerEx(fileHandle, *(PLARGE_INTEGER)&pos, NULL, FILE_BEGIN); - assert(result); + int result = fsetpos_64(fileHandle, 0); + assert(result == 0); Indexes = newIndexes; IndexCount = newIndexCount; diff --git a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h index f5ef48009b8370..4c8cc3febc6406 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/methodcontextreader.h @@ -48,7 +48,7 @@ class MethodContextReader { private: // The MC/MCH file - HANDLE fileHandle; + FILE* fileHandle; // The size of the MC/MCH file int64_t fileSize; @@ -94,7 +94,7 @@ class MethodContextReader int64_t GetOffset(unsigned int methodNumber); // Just a helper... - static HANDLE OpenFile(const char* inputFile, DWORD flags = FILE_ATTRIBUTE_NORMAL); + static FILE* OpenFile(const char* inputFile); MethodContextBuffer ReadMethodContextNoLock(bool justSkip = false); MethodContextBuffer ReadMethodContext(bool acquireLock, bool justSkip = false); diff --git a/src/coreclr/tools/superpmi/superpmi-shared/standardpch.h b/src/coreclr/tools/superpmi/superpmi-shared/standardpch.h index affc2f6ef9688b..4db0ed707797d2 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/standardpch.h +++ b/src/coreclr/tools/superpmi/superpmi-shared/standardpch.h @@ -64,6 +64,8 @@ #include #include #include +#include +#include #include #include diff --git a/src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp b/src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp index 4898c6d8b9a161..0ce36b8816ed3f 100644 --- a/src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shared/tocfile.cpp @@ -12,20 +12,18 @@ // Tries to load a Table of Contents void TOCFile::LoadToc(const char* inputFileName, bool validate) { - HANDLE hIndex = CreateFileA(inputFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hIndex == INVALID_HANDLE_VALUE) + FILE* hIndex = fopen(inputFileName, "rb"); + if (hIndex == nullptr) { - LogError("Failed to open file '%s'. GetLastError()=%u", inputFileName, GetLastError()); + LogError("Failed to open file '%s'. errno=%d", inputFileName, errno); return; } // Now read the index file LARGE_INTEGER val; // I'm abusing LARGE_INTEGER here... - DWORD read; - if (!ReadFile(hIndex, &val, sizeof(val), &read, nullptr) || (val.u.LowPart != *(DWORD*)("INDX"))) + if ((fread(&val, 1, sizeof(val), hIndex) != sizeof(val)) || (val.u.LowPart != *(DWORD*)("INDX"))) { - CloseHandle(hIndex); + fclose(hIndex); LogWarning("The index file %s is invalid: it seems to be missing the starting sentinel/length", inputFileName); return; } @@ -34,26 +32,26 @@ void TOCFile::LoadToc(const char* inputFileName, bool validate) this->m_tocArray = new TOCElement[this->m_tocCount]; // Read the whole array - if (!ReadFile(hIndex, &this->m_tocArray[0], (DWORD)(this->m_tocCount * sizeof(TOCElement)), &read, nullptr) || - (read != (DWORD)(this->m_tocCount * sizeof(TOCElement)))) + if (fread(&this->m_tocArray[0], 1, this->m_tocCount * sizeof(TOCElement), hIndex) != + this->m_tocCount * sizeof(TOCElement)) { - CloseHandle(hIndex); + fclose(hIndex); this->Clear(); LogWarning("The index file %s is invalid: it appears to be truncated.", inputFileName); return; } // Get the last 4 byte token (more abuse of LARGE_INTEGER) - if (!ReadFile(hIndex, &val.u.HighPart, sizeof(DWORD), &read, nullptr) || (read != sizeof(DWORD)) || + if ((fread(&val.u.HighPart, 1, sizeof(DWORD), hIndex) != sizeof(DWORD)) || (val.u.LowPart != (DWORD)val.u.HighPart)) { - CloseHandle(hIndex); + fclose(hIndex); this->Clear(); LogWarning("The index file %s is invalid: it appears to be missing the ending sentinel.", inputFileName); return; } - CloseHandle(hIndex); + fclose(hIndex); if (validate) { diff --git a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp index d7f15ea6cd1fc3..0ad7f741ac1e41 100644 --- a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.cpp @@ -26,7 +26,9 @@ void interceptor_ICJC::finalizeAndCommitCollection(MethodContext* mc, CorJitResu mc->cr->recAllocGCInfoCapture(); } - mc->saveToFile(hFile); + // The collection file failed to open at startup; that was already reported. + if (hFile != nullptr) + mc->saveToFile(hFile); } template diff --git a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h index 56e82ca744237c..6b18a4108cd7fb 100644 --- a/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h +++ b/src/coreclr/tools/superpmi/superpmi-shim-collector/icorjitcompiler.h @@ -16,7 +16,7 @@ class interceptor_ICJC : public ICorJitCompiler public: // Added to help us track the original icjc and be able to easily indirect to it. ICorJitCompiler* original_ICorJitCompiler; - HANDLE hFile; + FILE* hFile; CORINFO_OS currentOs; void finalizeAndCommitCollection(MethodContext* mc, CorJitResult result, uint8_t* nativeEntry, uint32_t nativeSizeOfCode); diff --git a/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp b/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp index f3ff4af0e6f9db..8870b5ee9bd14d 100644 --- a/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp +++ b/src/coreclr/tools/superpmi/superpmi-shim-collector/superpmi-shim-collector.cpp @@ -215,11 +215,15 @@ extern "C" DLLEXPORT ICorJitCompiler* getJit() #endif // create our datafile - pJitInstance->hFile = CreateFileA(g_dataFileName.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (pJitInstance->hFile == INVALID_HANDLE_VALUE) + pJitInstance->hFile = fopen(g_dataFileName.c_str(), "w+b"); + if (pJitInstance->hFile == nullptr) { - LogError("Couldn't open file '%s': error %d", g_dataFileName.c_str(), GetLastError()); + LogError("Couldn't open file '%s': errno %d", g_dataFileName.c_str(), errno); + } + else + { + // The file is never closed; write each method context straight through to it. + setvbuf(pJitInstance->hFile, nullptr, _IONBF, 0); } return pJitInstance; diff --git a/src/coreclr/tools/superpmi/superpmi/fileio.cpp b/src/coreclr/tools/superpmi/superpmi/fileio.cpp index eaa53fb0c9189e..6751e3865697d3 100644 --- a/src/coreclr/tools/superpmi/superpmi/fileio.cpp +++ b/src/coreclr/tools/superpmi/superpmi/fileio.cpp @@ -46,11 +46,7 @@ bool FileWriter::Print(const char* value, size_t numChars) if (numChars > m_buffer.size()) { - DWORD numWritten; - bool result = - WriteFile(m_file.Get(), value, static_cast(numChars), &numWritten, nullptr) && - (numWritten == static_cast(numChars)); - return result; + return fwrite(value, 1, numChars, m_file.Get()) == numChars; } } @@ -124,17 +120,14 @@ bool FileWriter::Flush() if (m_bufferIndex <= 0) return true; - DWORD numWritten; - bool result = - WriteFile(m_file.Get(), m_buffer.data(), static_cast(m_bufferIndex), &numWritten, nullptr) && - (numWritten == static_cast(m_bufferIndex)); + bool result = fwrite(m_buffer.data(), 1, m_bufferIndex, m_file.Get()) == m_bufferIndex; m_bufferIndex = 0; return result; } bool FileWriter::CreateNew(const char* path, FileWriter* fw) { - FileHandle handle(CreateFile(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr)); + FileHandle handle(fopen(path, "wb")); if (!handle.IsValid()) { return false; @@ -146,36 +139,25 @@ bool FileWriter::CreateNew(const char* path, FileWriter* fw) bool FileLineReader::Open(const char* path, FileLineReader* fr) { - FileHandle file(CreateFile(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); + FileHandle file(fopen(path, "rb")); if (!file.IsValid()) { return false; } - LARGE_INTEGER size; - if (!GetFileSizeEx(file.Get(), &size)) - { - return false; - } - - if (static_cast(size.QuadPart) > SIZE_MAX) - { - return false; - } - - FileMappingHandle mapping(CreateFileMapping(file.Get(), nullptr, PAGE_READONLY, size.u.HighPart, size.u.LowPart, nullptr)); - if (!mapping.IsValid()) + int64_t size = fgetsize(file.Get()); + if (size < 0 || static_cast(size) > SIZE_MAX) { return false; } - FileViewHandle view(MapViewOfFile(mapping.Get(), FILE_MAP_READ, 0, 0, 0)); - if (!view.IsValid()) + std::vector data(static_cast(size)); + if (fread(data.data(), 1, data.size(), file.Get()) != data.size()) { return false; } - *fr = FileLineReader(std::move(file), std::move(mapping), std::move(view), static_cast(size.QuadPart)); + *fr = FileLineReader(std::move(data)); return true; } diff --git a/src/coreclr/tools/superpmi/superpmi/fileio.h b/src/coreclr/tools/superpmi/superpmi/fileio.h index 8c721c2545008e..b968065a7c7284 100644 --- a/src/coreclr/tools/superpmi/superpmi/fileio.h +++ b/src/coreclr/tools/superpmi/superpmi/fileio.h @@ -56,28 +56,12 @@ struct HandleWrapper struct FileHandleSpec { - using Type = HANDLE; - static HANDLE Invalid() { return INVALID_HANDLE_VALUE; } - static void Close(HANDLE h) { CloseHandle(h); } -}; - -struct FileMappingHandleSpec -{ - using Type = HANDLE; - static HANDLE Invalid() { return nullptr; } - static void Close(HANDLE h) { CloseHandle(h); } -}; - -struct FileViewHandleSpec -{ - using Type = LPVOID; - static LPVOID Invalid() { return nullptr; } - static void Close(LPVOID p) { UnmapViewOfFile(p); } + using Type = FILE*; + static FILE* Invalid() { return nullptr; } + static void Close(FILE* f) { fclose(f); } }; typedef HandleWrapper FileHandle; -typedef HandleWrapper FileMappingHandle; -typedef HandleWrapper FileViewHandle; class FileWriter { @@ -132,20 +116,16 @@ class FileWriter class FileLineReader { - FileHandle m_file; - FileMappingHandle m_fileMapping; - FileViewHandle m_view; + std::vector m_data; char* m_cur; char* m_end; std::vector m_currentLine; - FileLineReader(FileHandle file, FileMappingHandle fileMapping, FileViewHandle view, size_t size) - : m_file(std::move(file)) - , m_fileMapping(std::move(fileMapping)) - , m_view(std::move(view)) - , m_cur(static_cast(m_view.Get())) - , m_end(static_cast(m_view.Get()) + size) + explicit FileLineReader(std::vector data) + : m_data(std::move(data)) + , m_cur(m_data.data()) + , m_end(m_data.data() + m_data.size()) { } diff --git a/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp b/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp index 753452a80a4b2d..fa24e9ca646d48 100644 --- a/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp +++ b/src/coreclr/tools/superpmi/superpmi/jitinstance.cpp @@ -78,21 +78,28 @@ JitInstance* JitInstance::InitJit(char* nameOfJit, HRESULT JitInstance::StartUp(char* PathToJit, bool breakOnDebugBreakorAV, MethodContext* firstContext) { // startup jit - DWORD dwRetVal = 0; UINT uRetVal = 0; BOOL bRetVal = FALSE; SetBreakOnDebugBreakOrAV(breakOnDebugBreakorAV); - char pFullPathName[MAX_PATH]; - // find the full jit path - dwRetVal = ::GetFullPathNameA(PathToJit, MAX_PATH, pFullPathName, nullptr); +#ifdef TARGET_UNIX + char pFullPathName[PATH_MAX]; + if (realpath(PathToJit, pFullPathName) == nullptr) + { + LogError("realpath failed (errno=%d)", errno); + return E_FAIL; + } +#else + char pFullPathName[MAX_PATH]; + DWORD dwRetVal = ::GetFullPathNameA(PathToJit, MAX_PATH, pFullPathName, nullptr); if (dwRetVal == 0) { LogError("GetFullPathName failed (0x%08x)", ::GetLastError()); return E_FAIL; } +#endif #ifndef TARGET_UNIX // No file version APIs in the PAL // Do a quick version check diff --git a/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp index 36cee7c6ccdb2d..cf0c256c8c161d 100644 --- a/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp +++ b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.cpp @@ -14,34 +14,31 @@ MethodStatsEmitter::MethodStatsEmitter(char* nameOfInput) char filename[MAX_PATH + 1]; sprintf_s(filename, MAX_PATH + 1, "%s.stats", nameOfInput); - hStatsFile = - CreateFileA(filename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - if (hStatsFile == INVALID_HANDLE_VALUE) + hStatsFile = fopen(filename, "wb"); + if (hStatsFile == nullptr) { - LogError("Failed to open output file '%s'. GetLastError()=%u", filename, GetLastError()); + LogError("Failed to open output file '%s'. errno=%d", filename, errno); } } MethodStatsEmitter::~MethodStatsEmitter() { - if (hStatsFile != INVALID_HANDLE_VALUE) + if (hStatsFile != nullptr) { - if (CloseHandle(hStatsFile) == 0) + if (fclose(hStatsFile) != 0) { - LogError("CloseHandle failed. GetLastError()=%u", GetLastError()); + LogError("fclose failed. errno=%d", errno); } } } void MethodStatsEmitter::Emit(int methodNumber, MethodContext* mc, ULONGLONG firstTime, ULONGLONG secondTime) { - if (hStatsFile != INVALID_HANDLE_VALUE) + if (hStatsFile != nullptr) { // Print the CSV header row char rowData[2048]; DWORD charCount = 0; - DWORD bytesWritten = 0; - if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'h') != NULL || strchr(statsTypes, 'H') != NULL) { // Obtain the method Hash @@ -87,9 +84,9 @@ void MethodStatsEmitter::Emit(int methodNumber, MethodContext* mc, ULONGLONG fir // get rid of the final ',' and replace it with a '\n' rowData[charCount - 1] = '\n'; - if (!WriteFile(hStatsFile, rowData, charCount, &bytesWritten, nullptr) || bytesWritten != charCount) + if (fwrite(rowData, 1, charCount, hStatsFile) != charCount) { - LogError("Failed to write row header '%s'. GetLastError()=%u", rowData, GetLastError()); + LogError("Failed to write row header '%s'. errno=%d", rowData, errno); } } } @@ -98,13 +95,11 @@ void MethodStatsEmitter::SetStatsTypes(char* types) { statsTypes = types; - if (hStatsFile != INVALID_HANDLE_VALUE) + if (hStatsFile != nullptr) { // Print the CSV header row char rowHeader[1024]; DWORD charCount = 0; - DWORD bytesWritten = 0; - if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'h') != NULL || strchr(statsTypes, 'H') != NULL) charCount += sprintf_s(rowHeader + charCount, ARRAY_SIZE(rowHeader) - charCount, "HASH,"); if (strchr(statsTypes, '*') != NULL || strchr(statsTypes, 'n') != NULL || strchr(statsTypes, 'N') != NULL) @@ -119,9 +114,9 @@ void MethodStatsEmitter::SetStatsTypes(char* types) // get rid of the final ',' and replace it with a '\n' rowHeader[charCount - 1] = '\n'; - if (!WriteFile(hStatsFile, rowHeader, charCount, &bytesWritten, nullptr) || bytesWritten != charCount) + if (fwrite(rowHeader, 1, charCount, hStatsFile) != charCount) { - LogError("Failed to write row header '%s'. GetLastError()=%u", rowHeader, GetLastError()); + LogError("Failed to write row header '%s'. errno=%d", rowHeader, errno); } } } diff --git a/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h index 40d38698b3d446..ba3e30e5fcdbbc 100644 --- a/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h +++ b/src/coreclr/tools/superpmi/superpmi/methodstatsemitter.h @@ -15,7 +15,7 @@ class MethodStatsEmitter private: char* statsTypes; - HANDLE hStatsFile; + FILE* hStatsFile; public: MethodStatsEmitter(char* nameOfInput); diff --git a/src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp b/src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp index 26362868f660f8..c9fb24c24df47d 100644 --- a/src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp +++ b/src/coreclr/tools/superpmi/superpmi/parallelsuperpmi.cpp @@ -249,36 +249,35 @@ void ReadMCLToArray(char* mclFilename, int** arr, int* count) *arr = nullptr; char* buff = nullptr; - HANDLE hFile = CreateFileA(mclFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); + FILE* hFile = fopen(mclFilename, "rb"); - if (hFile == INVALID_HANDLE_VALUE) + if (hFile == nullptr) { - LogError("Unable to open '%s'. GetLastError()=%u", mclFilename, GetLastError()); + LogError("Unable to open '%s'. errno=%d", mclFilename, errno); goto Cleanup; } - LARGE_INTEGER DataTemp; - if (GetFileSizeEx(hFile, &DataTemp) == 0) + int64_t fileSize; + fileSize = fgetsize(hFile); + if (fileSize < 0) { - LogError("GetFileSizeEx failed. GetLastError()=%u", GetLastError()); + LogError("fgetsize failed. errno=%d", errno); goto Cleanup; } - if (DataTemp.QuadPart > MAXMCLFILESIZE) + if (fileSize > MAXMCLFILESIZE) { - LogError("Size %d exceeds max size of %d", DataTemp.QuadPart, MAXMCLFILESIZE); + LogError("Size %lld exceeds max size of %d", (long long)fileSize, MAXMCLFILESIZE); goto Cleanup; } int sz; - sz = (int)(DataTemp.QuadPart); + sz = (int)fileSize; buff = new char[sz]; - DWORD bytesRead; - if (ReadFile(hFile, buff, sz, &bytesRead, nullptr) == 0) + if (fread(buff, 1, sz, hFile) != (size_t)sz) { - LogError("ReadFile failed. GetLastError()=%u", GetLastError()); + LogError("fread failed. errno=%d", errno); goto Cleanup; } @@ -309,19 +308,18 @@ void ReadMCLToArray(char* mclFilename, int** arr, int* count) if (buff != nullptr) delete[] buff; - if (hFile != INVALID_HANDLE_VALUE) - CloseHandle(hFile); + if (hFile != nullptr) + fclose(hFile); } bool WriteArrayToMCL(char* mclFilename, int* arr, int count) { - HANDLE hMCLFile = - CreateFileA(mclFilename, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + FILE* hMCLFile = fopen(mclFilename, "wb"); bool result = true; - if (hMCLFile == INVALID_HANDLE_VALUE) + if (hMCLFile == nullptr) { - LogError("Failed to open output file '%s'. GetLastError()=%u", mclFilename, GetLastError()); + LogError("Failed to open output file '%s'. errno=%d", mclFilename, errno); result = false; goto Cleanup; } @@ -330,21 +328,23 @@ bool WriteArrayToMCL(char* mclFilename, int* arr, int count) { char strMethodIndex[12]; DWORD charCount = 0; - DWORD bytesWritten = 0; charCount = sprintf_s(strMethodIndex, sizeof(strMethodIndex), "%d\r\n", arr[i]); - if (!WriteFile(hMCLFile, strMethodIndex, charCount, &bytesWritten, nullptr) || (bytesWritten != charCount)) + if (fwrite(strMethodIndex, 1, charCount, hMCLFile) != charCount) { - LogError("Failed to write method index '%d'. GetLastError()=%u", strMethodIndex, GetLastError()); + LogError("Failed to write method index '%d'. errno=%d", arr[i], errno); result = false; goto Cleanup; } } Cleanup: - if (hMCLFile != INVALID_HANDLE_VALUE) - CloseHandle(hMCLFile); + if (hMCLFile != nullptr && fclose(hMCLFile) != 0) + { + LogError("Failed to close output file '%s'. errno=%d", mclFilename, errno); + result = false; + } return result; } diff --git a/src/coreclr/tools/superpmi/superpmi/superpmi.cpp b/src/coreclr/tools/superpmi/superpmi/superpmi.cpp index b906f243703612..7eecc7d2ec4e16 100644 --- a/src/coreclr/tools/superpmi/superpmi/superpmi.cpp +++ b/src/coreclr/tools/superpmi/superpmi/superpmi.cpp @@ -511,17 +511,16 @@ int __cdecl main(int argc, char* argv[]) { char buff[500]; sprintf_s(buff, 500, "%s-%d.mc", o.reproName, reader->GetMethodContextIndex()); - HANDLE hFileOut = CreateFileA(buff, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, - FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFileOut == INVALID_HANDLE_VALUE) + FILE* hFileOut = fopen(buff, "wb"); + if (hFileOut == nullptr) { - LogError("Failed to open output '%s'. GetLastError()=%u", buff, GetLastError()); + LogError("Failed to open output '%s'. errno=%d", buff, errno); return (int)SpmiResult::GeneralFailure; } mc->saveToFile(hFileOut); - if (CloseHandle(hFileOut) == 0) + if (fclose(hFileOut) != 0) { - LogError("CloseHandle for output file failed. GetLastError()=%u", GetLastError()); + LogError("fclose for output file failed. errno=%d", errno); return (int)SpmiResult::GeneralFailure; } LogInfo("Wrote out repro to '%s'", buff);