From e9bd67739cfe3070919545fb2d28a36723af62ff Mon Sep 17 00:00:00 2001 From: Jonas Hahnfeld Date: Fri, 12 Aug 2022 14:14:18 +0200 Subject: [PATCH] [cling] Try to avoid crashes in llvm::identify_magic The overload taking a path opens the file and then mmap its contents. This can cause bus errors when another process truncates the file while we are trying to read it. Instead just read the first 1024 bytes, which should be enough for identify_magic to do its work. (cherry picked from commit 588e13c4da4a63427ef156f2624f5a5a15bfd298) --- .../lib/Interpreter/DynamicLibraryManager.cpp | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp index d0e8aff5ae594..f95f816909577 100644 --- a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp +++ b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp @@ -18,6 +18,7 @@ #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/Path.h" +#include #include #include @@ -458,12 +459,26 @@ namespace cling { return false; } - file_magic Magic; - const std::error_code Error = identify_magic(libFullPath, Magic); - if (exists) - *exists = !Error; + // Do not use the identify_magic overload taking a path: It will open the + // file and then mmap its contents, possibly causing bus errors when another + // process truncates the file while we are trying to read it. Instead just + // read the first 1024 bytes, which should be enough for identify_magic to + // do its work. + // TODO: Fix the code upstream and consider going back to calling the + // convenience function after a future LLVM upgrade. + std::ifstream in(libFullPath.str(), std::ios::binary); + char header[1024] = {0}; + in.read(header, sizeof(header)); + if (in.fail()) { + if (exists) + *exists = false; + return false; + } + + StringRef headerStr(header, in.gcount()); + file_magic Magic = identify_magic(headerStr); - bool result = !Error && + bool result = #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib