Skip to content

Commit 588e13c

Browse files
authored
[cling] Try to avoid crashes in llvm::identify_magic (root-project#11174)
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.
1 parent cc28da5 commit 588e13c

File tree

1 file changed

+20
-5
lines changed

1 file changed

+20
-5
lines changed

interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
#include "llvm/Support/DynamicLibrary.h"
1919
#include "llvm/Support/Path.h"
2020

21+
#include <fstream>
2122
#include <system_error>
2223
#include <sys/stat.h>
2324

@@ -459,12 +460,26 @@ namespace cling {
459460
return false;
460461
}
461462

462-
file_magic Magic;
463-
const std::error_code Error = identify_magic(libFullPath, Magic);
464-
if (exists)
465-
*exists = !Error;
463+
// Do not use the identify_magic overload taking a path: It will open the
464+
// file and then mmap its contents, possibly causing bus errors when another
465+
// process truncates the file while we are trying to read it. Instead just
466+
// read the first 1024 bytes, which should be enough for identify_magic to
467+
// do its work.
468+
// TODO: Fix the code upstream and consider going back to calling the
469+
// convenience function after a future LLVM upgrade.
470+
std::ifstream in(libFullPath.str(), std::ios::binary);
471+
char header[1024] = {0};
472+
in.read(header, sizeof(header));
473+
if (in.fail()) {
474+
if (exists)
475+
*exists = false;
476+
return false;
477+
}
478+
479+
StringRef headerStr(header, in.gcount());
480+
file_magic Magic = identify_magic(headerStr);
466481

467-
bool result = !Error &&
482+
bool result =
468483
#ifdef __APPLE__
469484
(Magic == file_magic::macho_fixed_virtual_memory_shared_lib
470485
|| Magic == file_magic::macho_dynamically_linked_shared_lib

0 commit comments

Comments
 (0)