From 3a39b075732a6e01da5806a1de583b7dbf3957da Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Mon, 24 Jun 2019 23:47:07 +0300 Subject: [PATCH 01/17] [cxxmodules] Do not generate a rootmap if a module exists. --- cmake/modules/RootMacros.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/modules/RootMacros.cmake b/cmake/modules/RootMacros.cmake index 0e781d0e5d1e1..5ee380bf32047 100644 --- a/cmake/modules/RootMacros.cmake +++ b/cmake/modules/RootMacros.cmake @@ -426,7 +426,7 @@ function(ROOT_GENERATE_DICTIONARY dictionary) set(rootmap_name ${library_output_dir}/${libprefix}${deduced_arg_module}.rootmap) endif() - if(CMAKE_ROOTTEST_NOROOTMAP) + if(CMAKE_ROOTTEST_NOROOTMAP OR cpp_module_file) set(rootmap_name ) set(rootmapargs ) else() From aa4a162b6589ac997cafd6893170748eaa87e232 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 29 Jun 2019 13:47:56 +0300 Subject: [PATCH 02/17] [rootcling] Simplify code. NFC --- core/dictgen/src/rootcling_impl.cxx | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/core/dictgen/src/rootcling_impl.cxx b/core/dictgen/src/rootcling_impl.cxx index b76d26050eb11..5490acc02efc5 100644 --- a/core/dictgen/src/rootcling_impl.cxx +++ b/core/dictgen/src/rootcling_impl.cxx @@ -3370,8 +3370,8 @@ void ExtractHeadersForDecls(const RScanner::ClassColl_t &annotatedRcds, //////////////////////////////////////////////////////////////////////////////// /// Generate the fwd declarations of the selected entities -std::string GenerateFwdDeclString(const RScanner &scan, - const cling::Interpreter &interp) +static std::string GenerateFwdDeclString(const RScanner &scan, + const cling::Interpreter &interp) { std::string newFwdDeclString; @@ -4842,13 +4842,10 @@ int RootClingMain(int argc, const std::string headersClassesMapString = GenerateStringFromHeadersForClasses(headersDeclsMap, detectedUmbrella, true); - std::string fwdDeclsString = "\"\""; + std::string fwdDeclsString = "nullptr"; if (!gDriverConfig->fBuildingROOTStage1) { - if (writeEmptyRootPCM) { - fwdDeclsString = "nullptr"; - } else { + if (!writeEmptyRootPCM) fwdDeclsString = GenerateFwdDeclString(scan, interp); - } } modGen.WriteRegistrationSource(dictStream, fwdDeclnArgsToKeepString, headersClassesMapString, fwdDeclsString, From edab0991a7848d8d7e67e5b078dd58caa5959217 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Fri, 5 Jul 2019 11:38:36 +0300 Subject: [PATCH 03/17] [cxxmodules] Generate library registration code only when needed. --- core/dictgen/src/TModuleGenerator.cxx | 5 +++-- core/dictgen/src/rootcling_impl.cxx | 18 ++++++++++-------- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/core/dictgen/src/TModuleGenerator.cxx b/core/dictgen/src/TModuleGenerator.cxx index e684e1a620182..329dd83f302da 100644 --- a/core/dictgen/src/TModuleGenerator.cxx +++ b/core/dictgen/src/TModuleGenerator.cxx @@ -395,8 +395,9 @@ void TModuleGenerator::WriteRegistrationSource(std::ostream &out, const std::str { if (hasCxxModule) { std::string emptyStr = "\"\""; - WriteRegistrationSourceImpl(out, GetDictionaryName(), GetDemangledDictionaryName(), {}, {}, emptyStr, "{}", - emptyStr, "0", "0", + WriteRegistrationSourceImpl(out, GetDictionaryName(), GetDemangledDictionaryName(), {}, {}, + fwdDeclString, "{}", + emptyStr, headersClassesMapString, "0", /*HasCxxModule*/ true); return; } diff --git a/core/dictgen/src/rootcling_impl.cxx b/core/dictgen/src/rootcling_impl.cxx index 5490acc02efc5..8a2c53212054b 100644 --- a/core/dictgen/src/rootcling_impl.cxx +++ b/core/dictgen/src/rootcling_impl.cxx @@ -4839,15 +4839,17 @@ int RootClingMain(int argc, } - const std::string headersClassesMapString = GenerateStringFromHeadersForClasses(headersDeclsMap, - detectedUmbrella, - true); - std::string fwdDeclsString = "nullptr"; - if (!gDriverConfig->fBuildingROOTStage1) { - if (!writeEmptyRootPCM) - fwdDeclsString = GenerateFwdDeclString(scan, interp); + std::string headersClassesMapString = "\"\""; + std::string fwdDeclsString = "\"\""; + if (!cxxmodule) { + headersClassesMapString = GenerateStringFromHeadersForClasses(headersDeclsMap, + detectedUmbrella, + true); + if (!gDriverConfig->fBuildingROOTStage1) { + if (!writeEmptyRootPCM) + fwdDeclsString = GenerateFwdDeclString(scan, interp); + } } - modGen.WriteRegistrationSource(dictStream, fwdDeclnArgsToKeepString, headersClassesMapString, fwdDeclsString, extraIncludes, cxxmodule); // If we just want to inline the input header, we don't need From 8201f8b5b059c4b4578719a50be1362284e3e2b4 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 6 Jul 2019 23:42:17 +0300 Subject: [PATCH 04/17] [cxxmodules] Move the addition of extra underscore closer to its use. --- core/metacling/src/TCling.cxx | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 99d7817b0ffa1..a690d3b6d8140 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6113,8 +6113,16 @@ static bool LookupBloomFilter(llvm::object::ObjectFile *soFile, uint32_t hash) { } // Lookup for normal symbols -static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, const std::string& mangled_name, const std::string& LibName) +static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::string mangled_name, const std::string& LibName) { + // The JIT gives us a mangled name which has only one leading underscore on + // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the + // linker stores this symbol as __ZN8TRandom34RndmEv (adding an extra _). +#ifdef R__MACOSX + assert(llvm::StringRef(mangled_name).startswith("__")); + mangled_name = "_" + mangled_name; +#endif + uint32_t hashedMangle = GNUHash(mangled_name); // Check Bloom filter. If false, it means that this library doesn't contain mangled_name defenition if (!LookupBloomFilter(RealSoFile, hashedMangle)) @@ -6175,16 +6183,6 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam sFirstRun = false; } - // The JIT gives us a mangled name which has only one leading underscore on - // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the - // linker stores this symbol as __ZN8TRandom34RndmEv (adding an extra _). -#ifdef R__MACOSX - std::string name_in_so = "_" + mangled_name; -#else - std::string name_in_so = mangled_name; -#endif - - // Iterate over files under this path. We want to get each ".so" files for (std::pair &P : sLibraries) { llvm::SmallString<400> Vec(sPaths[P.first]); @@ -6195,7 +6193,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam if (!SoFile) continue; - if (LookupNormalSymbols(SoFile.get().getBinary(), name_in_so, LibName)) { + if (LookupNormalSymbols(SoFile.get().getBinary(), mangled_name, LibName)) { if (gSystem->Load(LibName.c_str(), "", false) < 0) Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); @@ -6224,7 +6222,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam auto RealSoFile = SoFile.get().getBinary(); - if (LookupNormalSymbols(RealSoFile, name_in_so, LibName)) { + if (LookupNormalSymbols(RealSoFile, mangled_name, LibName)) { if (gSystem->Load(LibName.c_str(), "", false) < 0) Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); From d140fbdbb2471782b5ff5feead5578cdc04cea55 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 6 Jul 2019 23:44:48 +0300 Subject: [PATCH 05/17] [cxxmodules] Use pow of 2 to pre-allocate the string vector. --- core/metacling/src/TCling.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index a690d3b6d8140..6c7ba2914cc81 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6185,7 +6185,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // Iterate over files under this path. We want to get each ".so" files for (std::pair &P : sLibraries) { - llvm::SmallString<400> Vec(sPaths[P.first]); + llvm::SmallString<512> Vec(sPaths[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); const std::string LibName = Vec.str(); @@ -6212,7 +6212,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } for (std::pair &P : sSysLibraries) { - llvm::SmallString<400> Vec(sSysPaths[P.first]); + llvm::SmallString<512> Vec(sSysPaths[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); const std::string LibName = Vec.str(); From 0db6d50a32398af088703622e52a9ab7ded8785c Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sat, 6 Jul 2019 23:56:52 +0300 Subject: [PATCH 06/17] [cxxmodules] Improve code readability. NFC --- core/metacling/src/TCling.cxx | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 6c7ba2914cc81..19a23e32ca04b 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6167,15 +6167,18 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam static bool sFirstRun = true; static bool sFirstSystemLibrary = true; - // sLibraies contains pair of sPaths[i] (eg. /home/foo/module) and library name (eg. libTMVA.so). The - // reason why we're separating sLibraries and sPaths is that we have a lot of - // dupulication in path, for example we have "/home/foo/module-release/lib/libFoo.so", "/home/../libBar.so", "/home/../lib.." - // and it's waste of memory to store the full path. - static std::vector< std::pair > sLibraries; + // LibraryPath contains a pair offset to the canonical dirname (stored as + // sPaths[i]) and a filename. For example, `/home/foo/root/lib/libTMVA.so`) + // The .first will contain an index in sPaths where `/home/foo/root/lib/` + // will be stored and .second `libTMVA.so`. + // This approach reduces the duplicate paths as at one location there may be + // plenty of libraries. + using LibraryPath = std::pair; + static std::vector sLibraries; static std::vector sPaths; // For system header autoloading - static std::vector< std::pair > sSysLibraries; + static std::vector sSysLibraries; static std::vector sSysPaths; if (sFirstRun) { @@ -6184,7 +6187,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } // Iterate over files under this path. We want to get each ".so" files - for (std::pair &P : sLibraries) { + for (LibraryPath &P : sLibraries) { llvm::SmallString<512> Vec(sPaths[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); const std::string LibName = Vec.str(); @@ -6211,7 +6214,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam sFirstSystemLibrary = false; } - for (std::pair &P : sSysLibraries) { + for (LibraryPath &P : sSysLibraries) { llvm::SmallString<512> Vec(sSysPaths[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); const std::string LibName = Vec.str(); From 2eb8880bd2423df75196c7dcb6b5c65761808ea2 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jul 2019 00:10:54 +0300 Subject: [PATCH 07/17] [cxxmodules] Remove obsolete comment. --- core/metacling/src/TClingCallbacks.cxx | 1 - 1 file changed, 1 deletion(-) diff --git a/core/metacling/src/TClingCallbacks.cxx b/core/metacling/src/TClingCallbacks.cxx index 57c8f3a268506..682f4e9e0693b 100644 --- a/core/metacling/src/TClingCallbacks.cxx +++ b/core/metacling/src/TClingCallbacks.cxx @@ -888,7 +888,6 @@ static void SearchAndAddPath(const std::string& Path, std::string FileName(DirIt->path()); if (!llvm::sys::fs::is_directory(FileName) && llvm::sys::path::extension(FileName) == ".so") { - // TCling::IsLoaded is incredibly slow! // No need to check linked libraries, as this function is only invoked // for symbols that cannot be found (neither by dlsym nor in the JIT). if (dyLibManager->isLibraryLoaded(FileName.c_str())) From 7507accce958a4581b888ee41f018b080aa64fe7 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jul 2019 00:45:10 +0300 Subject: [PATCH 08/17] [cxxmodules] Refactor to improve readability. Move common code into lambda. Extract out the lookup in dynamic sections into a separate routine. --- core/metacling/src/TCling.cxx | 87 ++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 38 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 19a23e32ca04b..7fe7d87c6d0c5 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6113,7 +6113,7 @@ static bool LookupBloomFilter(llvm::object::ObjectFile *soFile, uint32_t hash) { } // Lookup for normal symbols -static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::string mangled_name, const std::string& LibName) +static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::string mangled_name) { // The JIT gives us a mangled name which has only one leading underscore on // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the @@ -6157,6 +6157,24 @@ static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::strin return false; } +///\returns true on success +static bool LookupDynamicSymbols(llvm::object::ObjectFile *ObjFile, + const std::string &mangled_name) { + for (auto section : ObjFile->sections()) { + llvm::StringRef sectionName; + section.getName(sectionName); + + // .dynstr contains string of dynamic symbols + if (sectionName == ".dynstr") { + llvm::StringRef dContents; + section.getContents(dContents); + // If this library contains mangled name + return dContents.contains(mangled_name); + } + } + return false; +} + static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_name, cling::Interpreter *fInterpreter) { using namespace llvm::object; @@ -6174,31 +6192,39 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // This approach reduces the duplicate paths as at one location there may be // plenty of libraries. using LibraryPath = std::pair; + using BasePaths = std::vector; static std::vector sLibraries; - static std::vector sPaths; + static BasePaths sPaths; // For system header autoloading static std::vector sSysLibraries; - static std::vector sSysPaths; + static BasePaths sSysPaths; if (sFirstRun) { TCling__FindLoadedLibraries(sLibraries, sPaths, *fInterpreter, /* searchSystem */ false); sFirstRun = false; } - // Iterate over files under this path. We want to get each ".so" files - for (LibraryPath &P : sLibraries) { - llvm::SmallString<512> Vec(sPaths[P.first]); + auto GetLibObjectFile = [](LibraryPath &P, const BasePaths &BaseP) { + llvm::SmallString<512> Vec(BaseP[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); const std::string LibName = Vec.str(); - auto SoFile = ObjectFile::createObjectFile(LibName); + return ObjectFile::createObjectFile(LibName); + }; + + // Iterate over files under this path. We want to get each ".so" files + for (LibraryPath &P : sLibraries) { + auto SoFile = GetLibObjectFile(P, sPaths); if (!SoFile) continue; - if (LookupNormalSymbols(SoFile.get().getBinary(), mangled_name, LibName)) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); + auto RealSoFile = SoFile.get().getBinary(); + + if (LookupNormalSymbols(RealSoFile, mangled_name)) { + llvm::StringRef LibName = RealSoFile->getFileName(); + if (gSystem->Load(LibName.data(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); // We want to delete a loaded library from sLibraries cache, because sLibraries is // a vector of candidate libraries which might be loaded in the future. @@ -6215,19 +6241,16 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } for (LibraryPath &P : sSysLibraries) { - llvm::SmallString<512> Vec(sSysPaths[P.first]); - llvm::sys::path::append(Vec, StringRef(P.second)); - const std::string LibName = Vec.str(); - - auto SoFile = ObjectFile::createObjectFile(LibName); + auto SoFile = GetLibObjectFile(P, sSysPaths); if (!SoFile) continue; auto RealSoFile = SoFile.get().getBinary(); - if (LookupNormalSymbols(RealSoFile, mangled_name, LibName)) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); + llvm::StringRef LibName = RealSoFile->getFileName(); + if (LookupNormalSymbols(RealSoFile, mangled_name)) { + if (gSystem->Load(LibName.data(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); @@ -6235,26 +6258,14 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } // Lookup for dynamic symbols - auto sections = RealSoFile->sections(); - for (auto section : sections) { - llvm::StringRef sectionName; - section.getName(sectionName); - - // .dynstr contains string of dynamic symbols - if (sectionName == ".dynstr") { - llvm::StringRef dContents; - section.getContents(dContents); - // If this library contains mangled name - if (dContents.contains(mangled_name)) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); - - // Delete a loaded library from sLibraries cache. - sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); - void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); - return addr; - } - } + if (LookupDynamicSymbols(RealSoFile, mangled_name)) { + if (gSystem->Load(LibName.data(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); + + // Delete a loaded library from sLibraries cache. + sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); + void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); + return addr; } } From 9ff1318411521ec08f0d701f4c4b7e183f1bff19 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jul 2019 01:09:59 +0300 Subject: [PATCH 09/17] [cxxmodules] Move the creation of the llvm objectfile in Lookup*Symbols. --- core/metacling/src/TCling.cxx | 63 +++++++++++++++++------------------ 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 7fe7d87c6d0c5..2e5f21e12b716 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6112,9 +6112,16 @@ static bool LookupBloomFilter(llvm::object::ObjectFile *soFile, uint32_t hash) { return (bitmask & word) == bitmask; } -// Lookup for normal symbols -static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::string mangled_name) +/// Looks up symbols from a an object file, representing the library. +///\returns true on success. +static bool LookupNormalSymbols(const std::string &library_filename, std::string mangled_name) { + auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename); + if (!ObjF) + return false; + + llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary(); + // The JIT gives us a mangled name which has only one leading underscore on // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the // linker stores this symbol as __ZN8TRandom34RndmEv (adding an extra _). @@ -6125,11 +6132,10 @@ static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::strin uint32_t hashedMangle = GNUHash(mangled_name); // Check Bloom filter. If false, it means that this library doesn't contain mangled_name defenition - if (!LookupBloomFilter(RealSoFile, hashedMangle)) + if (!LookupBloomFilter(BinObjFile, hashedMangle)) return false; - auto Symbols = RealSoFile->symbols(); - for (auto S : Symbols) { + for (const auto &S : BinObjFile->symbols()) { uint32_t Flags = S.getFlags(); // DO NOT insert to table if symbol was undefined if (Flags & llvm::object::SymbolRef::SF_Undefined) @@ -6158,9 +6164,15 @@ static bool LookupNormalSymbols(llvm::object::ObjectFile *RealSoFile, std::strin } ///\returns true on success -static bool LookupDynamicSymbols(llvm::object::ObjectFile *ObjFile, - const std::string &mangled_name) { - for (auto section : ObjFile->sections()) { +static bool LookupDynamicSymbols(const std::string &library_filename, std::string mangled_name) +{ + llvm::object::ObjectFile *BinObjFile = nullptr; + if (auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename)) + BinObjFile = ObjF.get().getBinary(); + else + return false; + + for (const auto §ion : BinObjFile->sections()) { llvm::StringRef sectionName; section.getName(sectionName); @@ -6177,7 +6189,6 @@ static bool LookupDynamicSymbols(llvm::object::ObjectFile *ObjFile, static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_name, cling::Interpreter *fInterpreter) { - using namespace llvm::object; using namespace llvm::sys::path; using namespace llvm::sys::fs; @@ -6205,26 +6216,19 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam sFirstRun = false; } - auto GetLibObjectFile = [](LibraryPath &P, const BasePaths &BaseP) { + auto GetLibFileName = [](LibraryPath &P, const BasePaths &BaseP) { llvm::SmallString<512> Vec(BaseP[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); - const std::string LibName = Vec.str(); - - return ObjectFile::createObjectFile(LibName); + return Vec.str(); }; // Iterate over files under this path. We want to get each ".so" files for (LibraryPath &P : sLibraries) { - auto SoFile = GetLibObjectFile(P, sPaths); - if (!SoFile) - continue; - - auto RealSoFile = SoFile.get().getBinary(); + const std::string LibName = GetLibFileName(P, sPaths); - if (LookupNormalSymbols(RealSoFile, mangled_name)) { - llvm::StringRef LibName = RealSoFile->getFileName(); - if (gSystem->Load(LibName.data(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); + if (LookupNormalSymbols(LibName, mangled_name)) { + if (gSystem->Load(LibName.c_str(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); // We want to delete a loaded library from sLibraries cache, because sLibraries is // a vector of candidate libraries which might be loaded in the future. @@ -6241,16 +6245,11 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } for (LibraryPath &P : sSysLibraries) { - auto SoFile = GetLibObjectFile(P, sSysPaths); - if (!SoFile) - continue; - - auto RealSoFile = SoFile.get().getBinary(); + const std::string LibName = GetLibFileName(P, sPaths); - llvm::StringRef LibName = RealSoFile->getFileName(); - if (LookupNormalSymbols(RealSoFile, mangled_name)) { - if (gSystem->Load(LibName.data(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); + if (LookupNormalSymbols(LibName, mangled_name)) { + if (gSystem->Load(LibName.c_str(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); @@ -6258,7 +6257,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam } // Lookup for dynamic symbols - if (LookupDynamicSymbols(RealSoFile, mangled_name)) { + if (LookupDynamicSymbols(LibName, mangled_name)) { if (gSystem->Load(LibName.data(), "", false) < 0) Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); From 3261fae622eaabae49324e674b4afe5811c0393b Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jul 2019 01:22:26 +0300 Subject: [PATCH 10/17] [cxxmodules] Simplify code by moving the common pieces in a lambda. NFC --- core/metacling/src/TCling.cxx | 74 ++++++++++++++++------------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 2e5f21e12b716..952b4f266e5d7 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6188,7 +6188,7 @@ static bool LookupDynamicSymbols(const std::string &library_filename, std::strin } static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_name, - cling::Interpreter *fInterpreter) { + cling::Interpreter *interp) { using namespace llvm::sys::path; using namespace llvm::sys::fs; @@ -6203,73 +6203,67 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // This approach reduces the duplicate paths as at one location there may be // plenty of libraries. using LibraryPath = std::pair; + using LibraryPaths = std::vector; using BasePaths = std::vector; - static std::vector sLibraries; + static LibraryPaths sLibraries; static BasePaths sPaths; // For system header autoloading - static std::vector sSysLibraries; + static LibraryPaths sSysLibraries; static BasePaths sSysPaths; if (sFirstRun) { - TCling__FindLoadedLibraries(sLibraries, sPaths, *fInterpreter, /* searchSystem */ false); + TCling__FindLoadedLibraries(sLibraries, sPaths, *interp, /* searchSystem */ false); sFirstRun = false; } - auto GetLibFileName = [](LibraryPath &P, const BasePaths &BaseP) { + auto GetLibFileName = [](const LibraryPath &P, const BasePaths &BaseP) { llvm::SmallString<512> Vec(BaseP[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); return Vec.str(); }; + auto MaterializeSymbol = [&mangled_name](const std::string &LibName, + const LibraryPath &P, + LibraryPaths& LibPaths) { + if (gSystem->Load(LibName.c_str(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); + + // We want to delete a loaded library from sLibraries cache, because sLibraries is + // a vector of candidate libraries which might be loaded in the future. + LibPaths.erase(std::remove(LibPaths.begin(), LibPaths.end(), P), LibPaths.end()); + void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); + return addr; + }; + // Iterate over files under this path. We want to get each ".so" files - for (LibraryPath &P : sLibraries) { + for (const LibraryPath &P : sLibraries) { const std::string LibName = GetLibFileName(P, sPaths); - if (LookupNormalSymbols(LibName, mangled_name)) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); - - // We want to delete a loaded library from sLibraries cache, because sLibraries is - // a vector of candidate libraries which might be loaded in the future. - sLibraries.erase(std::remove(sLibraries.begin(), sLibraries.end(), P), sLibraries.end()); - void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); - return addr; - } + // FIXME: We should also iterate over the dynamic symbols for ROOT + // libraries. However, it seems to be redundant for the moment as we do + // not strictly require symbols from those sections. Enable after checking + // performance! + if (LookupNormalSymbols(LibName, mangled_name)) + if (void * addr = MaterializeSymbol(LibName, P, sLibraries)) + return addr; } - // Normal lookup failed! Fall back to system library + // Lookup in non-system libraries failed. Expand the search to the system. if (sFirstSystemLibrary) { - TCling__FindLoadedLibraries(sSysLibraries, sSysPaths, *fInterpreter, /* searchSystem */ true); + TCling__FindLoadedLibraries(sSysLibraries, sSysPaths, *interp, /* searchSystem */ true); sFirstSystemLibrary = false; } - for (LibraryPath &P : sSysLibraries) { + for (const LibraryPath &P : sSysLibraries) { const std::string LibName = GetLibFileName(P, sPaths); - if (LookupNormalSymbols(LibName, mangled_name)) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); - - sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); - void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); - return addr; - } - - // Lookup for dynamic symbols - if (LookupDynamicSymbols(LibName, mangled_name)) { - if (gSystem->Load(LibName.data(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.data()); - - // Delete a loaded library from sLibraries cache. - sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); - void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); - return addr; - } + if (LookupNormalSymbols(LibName, mangled_name) || LookupDynamicSymbols(LibName, mangled_name)) + if (void * addr = MaterializeSymbol(LibName, P, sSysLibraries)) + return addr; } - // Lookup failed!!!! - return nullptr; + return nullptr; // Lookup failed. } //////////////////////////////////////////////////////////////////////////////// From 6686b1ab9a418b8bc98096f870f5e5a119a36451 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Sun, 7 Jul 2019 23:02:08 +0300 Subject: [PATCH 11/17] [cxxmodules] Merge sSysPaths and sPath. Both data structures are used to store the dirname of the system and non-system library respectively. Their use is to provide a stable offset for the LibraryPath. --- core/metacling/src/TCling.cxx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 952b4f266e5d7..73204793aba9c 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6210,7 +6210,6 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // For system header autoloading static LibraryPaths sSysLibraries; - static BasePaths sSysPaths; if (sFirstRun) { TCling__FindLoadedLibraries(sLibraries, sPaths, *interp, /* searchSystem */ false); @@ -6251,7 +6250,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // Lookup in non-system libraries failed. Expand the search to the system. if (sFirstSystemLibrary) { - TCling__FindLoadedLibraries(sSysLibraries, sSysPaths, *interp, /* searchSystem */ true); + TCling__FindLoadedLibraries(sSysLibraries, sPaths, *interp, /* searchSystem */ true); sFirstSystemLibrary = false; } From 41a2e0fcd35daa9d522730fd9cf3b97a7b1a836d Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Tue, 9 Jul 2019 08:50:31 +0300 Subject: [PATCH 12/17] [cxxmodules] Do not rely on rootmaps to compute library dependencies in ACLiC When ACLiC builds a shared library it does either explicit linking (enumerating all related libraries with -l) or implicit symbol resolution. When ROOT6 appeared we could only rely on rootmaps to compute library dependencies and this hardened the implementation of explicit linking. Explicit linking happens in two ways: 1. We read all rootmap files and store a mapping qualified name -> library. Whenever we read a RecordDecl when generating a dictionary in rootcling we check if the RecordDecl's qualified name exists in the map and store the corresponding library in a special *.out file. 2. In the case of runtime_cxxmodule, if the -cxxmodule flag is passed to rootcling, whenever we deserialize a declaration we fill that information from RecordDecl's owning module. This approach is suboptimal because the deserialized declaration can be a forward declaration or codegen decided not to produce code because the entity was not ord-used. We cannot use explicit linking when ROOT is running in mixed mode, that is it has -Druntime_cxxmodules=On and no -cxxmodule flag in rootcling. The implicit linking means we do not use explicit linking but resolve undefined symbols at library loading time. This is the preferrable way to resolve symbols but it can be tricky and unefficient. It happens in two ways: 1. Upon loading of a shared library we listen to a callback if the library failed to load. The dynamic linker gives an 'undefined symbol' error which we search for in the LD_LIBRARY_PATH. 2. It can happen that the library loads successfully and the symbol lookup fails later. Currently there is no way to subscribe to such an event. This patch enables implicit linking for the 2nd way solving the deficiency of explicit linking when ROOT runs in hybrid mode. In that rare case, we iterate over all undefined symbols in a given library and try to find their definitions in the list of predefined library paths. Currently the behavior is O(n*m) where n is the number of the undefined symbols and m is the number of libraries. We can use a combination of caching and bloom filters to improve the performance but it is not worth it, given the almost corner-case we are in. An easier optimization is to check if the symbol is resolvable via dlsym which means that the library contains an undefined symbol but it was already loaded. This simple optimization brings ~30% improvement. --- core/base/src/TSystem.cxx | 66 +++++++--- core/meta/inc/TInterpreter.h | 2 +- core/metacling/src/TCling.cxx | 184 +++++++++++++++++++++------- core/metacling/src/TCling.h | 2 +- core/metacling/test/TClingTests.cxx | 49 +++++++- 5 files changed, 239 insertions(+), 64 deletions(-) diff --git a/core/base/src/TSystem.cxx b/core/base/src/TSystem.cxx index 2b2e22e7b52c0..f9f25f628f8f4 100644 --- a/core/base/src/TSystem.cxx +++ b/core/base/src/TSystem.cxx @@ -21,14 +21,6 @@ that the method should be overridden in a derived class), which allows a simple partial implementation for new OS'es. */ -#ifdef WIN32 -#include -#endif -#include -#include -#include -#include - #include #include "Riostream.h" #include "TSystem.h" @@ -55,6 +47,14 @@ allows a simple partial implementation for new OS'es. #include "RConfigure.h" #include "THashList.h" +#include +#include +#include + +#ifdef WIN32 +#include +#endif + const char *gRootDir; const char *gProgName; const char *gProgPath; @@ -3353,6 +3353,35 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, linkDepLibraries = linkLibs & 0x1; } + constexpr const bool useCxxModules = +#ifdef R__USE_CXXMODULES + true; +#else + false; +#endif + + auto LoadLibrary = [useCxxModules, produceRootmap](const TString& lib) { + // We have no rootmap files or modules to construct `-l` flags enabling + // explicit linking. We have to resolve the dependencies by ourselves + // taking the job of the dyld. + // FIXME: This is a rare case where we have rootcling running with + // modules disabled. Remove this code once we fully switch to modules, + // or implement a special flag in rootcling which selective enables + // modules for dependent libraries and does not produce a module for + // the ACLiC library. + if (useCxxModules && !produceRootmap) { + using namespace std; + string deps = gInterpreter->GetSharedLibDeps(lib, /*tryDyld*/true); + istringstream iss(deps); + vector libs {istream_iterator{iss}, istream_iterator{}}; + // Skip the first element: it is a relative path to `lib`. + for (auto I = libs.begin() + 1, E = libs.end(); I != E; ++I) + if (gInterpreter->Load(I->c_str(), /*system*/false) < 0) + return false; // failure + } + return !gSystem->Load(lib); + }; + if (!recompile) { // The library already exist, let's just load it. if (loadLib) { @@ -3367,7 +3396,7 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, gInterpreter->LoadLibraryMap(libmapfilename); } - return !gSystem->Load(library); + return LoadLibrary(library); } else return kTRUE; } @@ -3478,9 +3507,11 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, TString mapfileout = mapfile + ".out"; Bool_t needLoadMap = kFALSE; - if (gInterpreter->GetSharedLibDeps(libname) !=0 ) { - gInterpreter->UnloadLibraryMap(libname); - needLoadMap = kTRUE; + if (!useCxxModules) { + if (gInterpreter->GetSharedLibDeps(libname) !=0 ) { + gInterpreter->UnloadLibraryMap(libname); + needLoadMap = kTRUE; + } } std::ofstream mapfileStream( mapfilein, std::ios::out ); @@ -3511,11 +3542,6 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, } mapfileStream.close(); - bool useCxxModules = false; -#ifdef R__USE_CXXMODULES - useCxxModules = true; -#endif - // ======= Generate the rootcling command line TString rcling = "rootcling"; PrependPathName(TROOT::GetBinDir(), rcling); @@ -3770,8 +3796,10 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, gInterpreter->LoadLibraryMap(libmapfilename); } if (verboseLevel>3 && withInfo) ::Info("ACLiC","loading the shared library"); - if (loadLib) result = !gSystem->Load(library); - else result = kTRUE; + if (loadLib) + result = LoadLibrary(library); + else + result = kTRUE; if ( !result ) { if (verboseLevel>3 && withInfo) { diff --git a/core/meta/inc/TInterpreter.h b/core/meta/inc/TInterpreter.h index c5dad5e53b79e..10c29cd583f89 100644 --- a/core/meta/inc/TInterpreter.h +++ b/core/meta/inc/TInterpreter.h @@ -157,7 +157,7 @@ class TInterpreter : public TNamed { virtual char *GetPrompt() = 0; virtual const char *GetSharedLibs() = 0; virtual const char *GetClassSharedLibs(const char *cls) = 0; - virtual const char *GetSharedLibDeps(const char *lib) = 0; + virtual const char *GetSharedLibDeps(const char *lib, bool tryDyld = false) = 0; virtual const char *GetIncludePath() = 0; virtual const char *GetSTLIncludePath() const { return ""; } virtual TObjArray *GetRootMapFiles() const = 0; diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index 73204793aba9c..ffdc310201b8e 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -6114,22 +6114,17 @@ static bool LookupBloomFilter(llvm::object::ObjectFile *soFile, uint32_t hash) { /// Looks up symbols from a an object file, representing the library. ///\returns true on success. -static bool LookupNormalSymbols(const std::string &library_filename, std::string mangled_name) +static bool LookupNormalSymbol(const std::string &library_filename, + const std::string &mangled_name) { auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename); - if (!ObjF) + if (!ObjF) { + Warning("TCling__FindSymbol", "Failed to read object file %s", library_filename.c_str()); return false; + } llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary(); - // The JIT gives us a mangled name which has only one leading underscore on - // all platforms, for instance _ZN8TRandom34RndmEv. However, on OSX the - // linker stores this symbol as __ZN8TRandom34RndmEv (adding an extra _). -#ifdef R__MACOSX - assert(llvm::StringRef(mangled_name).startswith("__")); - mangled_name = "_" + mangled_name; -#endif - uint32_t hashedMangle = GNUHash(mangled_name); // Check Bloom filter. If false, it means that this library doesn't contain mangled_name defenition if (!LookupBloomFilter(BinObjFile, hashedMangle)) @@ -6152,7 +6147,7 @@ static bool LookupNormalSymbols(const std::string &library_filename, std::string llvm::Expected SymNameErr = S.getName(); if (!SymNameErr) { - Warning("LookupNormalSymbols", "Failed to read symbol"); + Warning("LookupNormalSymbol", "Failed to read symbol"); continue; } @@ -6164,14 +6159,15 @@ static bool LookupNormalSymbols(const std::string &library_filename, std::string } ///\returns true on success -static bool LookupDynamicSymbols(const std::string &library_filename, std::string mangled_name) +static bool LookupDynamicSymbol(const std::string &library_filename, + const std::string &mangled_name) { - llvm::object::ObjectFile *BinObjFile = nullptr; - if (auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename)) - BinObjFile = ObjF.get().getBinary(); - else + auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename); + if (!ObjF) return false; + llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary(); + for (const auto §ion : BinObjFile->sections()) { llvm::StringRef sectionName; section.getName(sectionName); @@ -6187,8 +6183,10 @@ static bool LookupDynamicSymbols(const std::string &library_filename, std::strin return false; } -static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_name, - cling::Interpreter *interp) { +static std::string ResolveSymbol(const std::string& mangled_name, + cling::Interpreter *interp, + bool searchSystem = true) { + assert(!mangled_name.empty()); using namespace llvm::sys::path; using namespace llvm::sys::fs; @@ -6197,8 +6195,8 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam static bool sFirstRun = true; static bool sFirstSystemLibrary = true; // LibraryPath contains a pair offset to the canonical dirname (stored as - // sPaths[i]) and a filename. For example, `/home/foo/root/lib/libTMVA.so`) - // The .first will contain an index in sPaths where `/home/foo/root/lib/` + // sPaths[i]) and a filename. For example, `/home/foo/root/lib/libTMVA.so`, + // the .first will contain an index in sPaths where `/home/foo/root/lib/` // will be stored and .second `libTMVA.so`. // This approach reduces the duplicate paths as at one location there may be // plenty of libraries. @@ -6207,6 +6205,7 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam using BasePaths = std::vector; static LibraryPaths sLibraries; static BasePaths sPaths; + static LibraryPaths sQueriedLibraries; // For system header autoloading static LibraryPaths sSysLibraries; @@ -6219,21 +6218,28 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam auto GetLibFileName = [](const LibraryPath &P, const BasePaths &BaseP) { llvm::SmallString<512> Vec(BaseP[P.first]); llvm::sys::path::append(Vec, StringRef(P.second)); - return Vec.str(); + return Vec.str().str(); }; - auto MaterializeSymbol = [&mangled_name](const std::string &LibName, - const LibraryPath &P, - LibraryPaths& LibPaths) { - if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); - - // We want to delete a loaded library from sLibraries cache, because sLibraries is - // a vector of candidate libraries which might be loaded in the future. - LibPaths.erase(std::remove(LibPaths.begin(), LibPaths.end(), P), LibPaths.end()); - void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); - return addr; - }; + if (!sQueriedLibraries.empty()) { + // Last call we were asked if a library contains a symbol. Usually, the + // caller wants to load this library. Check if was loaded and remove it + // from our lists of not-yet-loaded libs. + for (const LibraryPath &P : sQueriedLibraries) { + const std::string LibName = GetLibFileName(P, sPaths); + if (!gCling->IsLibraryLoaded(LibName.c_str())) + continue; + + sLibraries.erase(std::remove(sLibraries.begin(), sLibraries.end(), P), sLibraries.end()); + if (!sSysLibraries.empty()) + sSysLibraries.erase(std::remove(sSysLibraries.begin(), sSysLibraries.end(), P), sSysLibraries.end()); + } + } + + if (sFirstRun) { + TCling__FindLoadedLibraries(sLibraries, sPaths, *interp, /* searchSystem */ false); + sFirstRun = false; + } // Iterate over files under this path. We want to get each ".so" files for (const LibraryPath &P : sLibraries) { @@ -6243,11 +6249,15 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam // libraries. However, it seems to be redundant for the moment as we do // not strictly require symbols from those sections. Enable after checking // performance! - if (LookupNormalSymbols(LibName, mangled_name)) - if (void * addr = MaterializeSymbol(LibName, P, sLibraries)) - return addr; + if (LookupNormalSymbol(LibName, mangled_name)) { + sQueriedLibraries.push_back(P); + return LibName; + } } + if (!searchSystem) + return ""; + // Lookup in non-system libraries failed. Expand the search to the system. if (sFirstSystemLibrary) { TCling__FindLoadedLibraries(sSysLibraries, sPaths, *interp, /* searchSystem */ true); @@ -6257,12 +6267,26 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam for (const LibraryPath &P : sSysLibraries) { const std::string LibName = GetLibFileName(P, sPaths); - if (LookupNormalSymbols(LibName, mangled_name) || LookupDynamicSymbols(LibName, mangled_name)) - if (void * addr = MaterializeSymbol(LibName, P, sSysLibraries)) - return addr; + if (LookupNormalSymbol(LibName, mangled_name) || LookupDynamicSymbol(LibName, mangled_name)) { + sQueriedLibraries.push_back(P); + return LibName; + } } - return nullptr; // Lookup failed. + return ""; // Search found no match. +} + +static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_name, + cling::Interpreter *interp) { + std::string LibName = ResolveSymbol(mangled_name, interp); + if (LibName.empty()) + return nullptr; + + if (gSystem->Load(LibName.c_str(), "", false) < 0) + Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); + + void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); + return addr; } //////////////////////////////////////////////////////////////////////////////// @@ -6923,14 +6947,90 @@ const char* TCling::GetClassSharedLibs(const char* cls) return 0; } +/// This interface returns a list of dependent libraries in the form: +/// lib libA.so libB.so libC.so. The first library is the library we are +/// searching dependencies for. +/// Note: In order to speed up the search, we display the dependencies of the +/// libraries which are not yet loaded. For instance, if libB.so was already +/// loaded the list would contain: lib libA.so libC.so. +static std::string GetSharedLibImmediateDepsSlow(std::string lib, + cling::Interpreter *interp, + bool skipLoadedLibs = true) +{ + TString LibFullPath(lib); + if (!llvm::sys::path::is_absolute(lib)) { + if (!gSystem->FindDynamicLibrary(LibFullPath, /*quiet=*/true)) { + Error("TCling__GetSharedLibImmediateDepsSlow", "Cannot find library '%s'", lib.c_str()); + return ""; + } + } else { + lib = llvm::sys::path::filename(lib); + } + + auto ObjF = llvm::object::ObjectFile::createObjectFile(LibFullPath.Data()); + if (!ObjF) { + Warning("TCling__GetSharedLibImmediateDepsSlow", "Failed to read object file %s", lib.c_str()); + return ""; + } + + llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary(); + + std::set DedupSet; + std::string Result = lib + ' '; + for (const auto &S : BinObjFile->symbols()) { + uint32_t Flags = S.getFlags(); + if (Flags & llvm::object::SymbolRef::SF_Undefined) { + llvm::Expected SymNameErr = S.getName(); + if (!SymNameErr) { + Warning("GetSharedLibDepsForModule", "Failed to read symbol"); + continue; + } + llvm::StringRef SymName = SymNameErr.get(); + if (SymName.empty()) + continue; + + // If we can find the address of the symbol, we have loaded it. Skip. + if (skipLoadedLibs && llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(SymName)) + continue; + + std::string found = ResolveSymbol(SymName, interp, /*searchSystem*/false); + // The expected output is just filename without the full path, which + // is not very accurate, because our Dyld implementation might find + // a match in location a/b/c.so and if we return just c.so ROOT might + // resolve it to y/z/c.so and there we might not be ABI compatible. + // FIXME: Teach the users of GetSharedLibDeps to work with full paths. + if (!found.empty()) { + std::string cand = llvm::sys::path::filename(found).str(); + if (!DedupSet.insert(cand).second) + continue; + + Result += cand + ' '; + } + } + } + + return Result; +} + + //////////////////////////////////////////////////////////////////////////////// /// Get the list a libraries on which the specified lib depends. The /// returned string contains as first element the lib itself. /// Returns 0 in case the lib does not exist or does not have -/// any dependencies. +/// any dependencies. If useDyld is true, we iterate through all available +/// libraries and try to construct the dependency chain by resolving each +/// symbol. -const char* TCling::GetSharedLibDeps(const char* lib) +const char* TCling::GetSharedLibDeps(const char* lib, bool useDyld/* = false*/) { + if (useDyld) { + std::string libs = GetSharedLibImmediateDepsSlow(lib, fInterpreter); + if (!libs.empty()) { + fAutoLoadLibStorage.push_back(libs); + return fAutoLoadLibStorage.back().c_str(); + } + } + if (!fMapfile || !lib || !lib[0]) { return 0; } diff --git a/core/metacling/src/TCling.h b/core/metacling/src/TCling.h index 05b28fdbe4d94..f607ee00d0833 100644 --- a/core/metacling/src/TCling.h +++ b/core/metacling/src/TCling.h @@ -201,7 +201,7 @@ class TCling final : public TInterpreter { char* GetPrompt() { return fPrompt; } const char* GetSharedLibs(); const char* GetClassSharedLibs(const char* cls); - const char* GetSharedLibDeps(const char* lib); + const char* GetSharedLibDeps(const char* lib, bool tryDyld = false); const char* GetIncludePath(); virtual const char* GetSTLIncludePath() const; TObjArray* GetRootMapFiles() const { return fRootmapFiles; } diff --git a/core/metacling/test/TClingTests.cxx b/core/metacling/test/TClingTests.cxx index 7d058be99572c..5679bbdcf1f57 100644 --- a/core/metacling/test/TClingTests.cxx +++ b/core/metacling/test/TClingTests.cxx @@ -133,7 +133,7 @@ static std::string MakeLibNamePlatformIndependent(llvm::StringRef libName) EXPECT_TRUE(llvm::sys::path::has_extension(libName)); libName.consume_front("lib"); // Remove the extension. - return libName.substr(0, libName.find_last_of('.')).str(); + return libName.substr(0, libName.find_first_of('.')).str(); } // Shortens the invocation. @@ -179,3 +179,50 @@ TEST_F(TClingTests, GetClassSharedLibs) // != GetLibs("ROOT::Math::LorentzVector>") // note the missing space. } + +static std::string MakeDepLibsPlatformIndependent(llvm::StringRef libs) { + llvm::SmallVector splitLibs; + libs.trim().split(splitLibs, ' '); + assert(!splitLibs.empty()); + std::string result = MakeLibNamePlatformIndependent(splitLibs[0]) + ' '; + splitLibs.erase(splitLibs.begin()); + + std::sort(splitLibs.begin(), splitLibs.end()); + for (llvm::StringRef lib : splitLibs) + result += MakeLibNamePlatformIndependent(lib.trim()) + ' '; + + return llvm::StringRef(result).rtrim(); +} + +// Check the interface computing the dependencies of a given library. +TEST_F(TClingTests, GetSharedLibDeps) +{ + // Shortens the invocation. + auto GetLibDeps = [](const char *lib) -> const char* { + return gInterpreter->GetSharedLibDeps(lib, /*tryDyld*/true); + }; + + std::string SeenDeps + = MakeDepLibsPlatformIndependent(GetLibDeps("libGenVector.so")); +#ifdef R__MACOSX + ASSERT_TRUE(llvm::StringRef(SeenDeps).startswith("GenVector New")); +#else + // Depends only on libCore.so but libCore.so is loaded and thus missing. + ASSERT_STREQ("GenVector", SeenDeps.c_str()); +#endif + + SeenDeps = MakeDepLibsPlatformIndependent(GetLibDeps("libTreePlayer.so")); + llvm::StringRef SeenDepsRef = SeenDeps; + + // Depending on the configuration we expect: + // TreePlayer Gpad Graf Graf3d Hist [Imt] MathCore MultiProc Net [New] Tree [tbb].. + // FIXME: We should add a generic gtest regex matcher and use a regex here. + ASSERT_TRUE(SeenDepsRef.startswith("TreePlayer Gpad Graf Graf3d Hist")); + ASSERT_TRUE(SeenDepsRef.contains("MathCore MultiProc Net")); + ASSERT_TRUE(SeenDepsRef.contains("Tree")); + + EXPECT_ROOT_ERROR(ASSERT_TRUE(nullptr == GetLibDeps("")), + "Error in : Cannot find library ''\n"); + EXPECT_ROOT_ERROR(ASSERT_TRUE(nullptr == GetLibDeps(" ")), + "Error in : Cannot find library ' '\n"); +} From 58044123639550ede74b92308c08ec1f678b3592 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Wed, 10 Jul 2019 00:10:02 +0300 Subject: [PATCH 13/17] [cling] Mark library search paths system and user accordingly. We have user library search paths which come from LD_LIBRARY_PATH or similar; and system library search paths which are coming from the platform. This patch enables external users performing symbol resolution to filter out system search paths when they know the symbol cannot be there. Now, TClingCallbacks can merge the modules vs non-modules code paths, where the modules prebuilt path is essentially our LD_LIBRARY_PATH. --- core/metacling/src/TClingCallbacks.cxx | 18 ++++---------- .../cling/Interpreter/DynamicLibraryManager.h | 16 ++++++++++--- .../lib/Interpreter/DynamicLibraryManager.cpp | 24 ++++++++++++------- 3 files changed, 33 insertions(+), 25 deletions(-) diff --git a/core/metacling/src/TClingCallbacks.cxx b/core/metacling/src/TClingCallbacks.cxx index 682f4e9e0693b..ef848c73a2312 100644 --- a/core/metacling/src/TClingCallbacks.cxx +++ b/core/metacling/src/TClingCallbacks.cxx @@ -914,20 +914,12 @@ void TCling__FindLoadedLibraries(std::vector> & { // Store the information of path so that we don't have to iterate over the same path again and again. static std::unordered_set alreadyLookedPath; - const clang::Preprocessor &PP = interpreter.getCI()->getPreprocessor(); - const HeaderSearchOptions &HSOpts = PP.getHeaderSearchInfo().getHeaderSearchOpts(); cling::DynamicLibraryManager* dyLibManager = interpreter.getDynamicLibraryManager(); - if (searchSystem) { - llvm::SmallVector systemPath = dyLibManager->getSystemSearchPath(); - for (const std::string& sysPath : systemPath) { - SearchAndAddPath(sysPath, sLibraries, sPaths, alreadyLookedPath, dyLibManager); - } - } else { - const std::vector& MPaths = HSOpts.PrebuiltModulePaths; - // Take path here eg. "/home/foo/module-release/lib/" - for (const std::string& mPath : MPaths) { - SearchAndAddPath(mPath, sLibraries, sPaths, alreadyLookedPath, dyLibManager); - } + const auto &searchPaths = dyLibManager->getSearchPath(); + for (const cling::DynamicLibraryManager::SearchPathInfo &Info : searchPaths) { + if (!Info.IsUser && !searchSystem) + continue; + SearchAndAddPath(Info.Path, sLibraries, sPaths, alreadyLookedPath, dyLibManager); } } diff --git a/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h b/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h index 3dcaa47e3b66e..fc7ae4f318bc4 100644 --- a/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h +++ b/interpreter/cling/include/cling/Interpreter/DynamicLibraryManager.h @@ -34,6 +34,16 @@ namespace cling { kLoadLibNumResults }; + /// Describes the library search paths. + struct SearchPathInfo { + /// The search path. + /// + std::string Path; + + /// True if the Path is on the LD_LIBRARY_PATH. + /// + bool IsUser; + }; private: typedef const void* DyLibHandle; typedef llvm::DenseMap DyLibs; @@ -48,7 +58,7 @@ namespace cling { ///\brief System's include path, get initialized at construction time. /// - llvm::SmallVector m_SystemSearchPaths; + llvm::SmallVector m_SearchPaths; InterpreterCallbacks* m_Callbacks; @@ -81,8 +91,8 @@ namespace cling { /// ///\returns System include paths. /// - llvm::SmallVector getSystemSearchPath() { - return m_SystemSearchPaths; + const llvm::SmallVectorImpl& getSearchPath() { + return m_SearchPaths; } ///\brief Looks up a library taking into account the current include paths diff --git a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp index 27e79d58890e0..c1900f1066819 100644 --- a/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp +++ b/interpreter/cling/lib/Interpreter/DynamicLibraryManager.cpp @@ -50,28 +50,34 @@ namespace cling { SplitPaths(Env, CurPaths, utils::kPruneNonExistant, platform::kEnvDelim, Opts.Verbose()); for (const auto& Path : CurPaths) - m_SystemSearchPaths.push_back(Path.str()); + m_SearchPaths.push_back({Path.str(), /*IsUser*/true}); } } - platform::GetSystemLibraryPaths(m_SystemSearchPaths); + llvm::SmallVector SysPaths; + platform::GetSystemLibraryPaths(SysPaths); + + for (const std::string& P : SysPaths) + m_SearchPaths.push_back({P, /*IsUser*/false}); // This will currently be the last path searched, should it be pushed to // the front of the line, or even to the front of user paths? - m_SystemSearchPaths.push_back("."); + m_SearchPaths.push_back({".", /*IsUser*/true}); } DynamicLibraryManager::~DynamicLibraryManager() {} std::string DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const { - llvm::SmallVector - Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); - Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end()); + llvm::SmallVector Paths; + for (const std::string &P : m_Opts.LibSearchPath) + Paths.push_back({P, /*IsUser*/true}); + + Paths.append(m_SearchPaths.begin(), m_SearchPaths.end()); - for (llvm::SmallVectorImpl::const_iterator - IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) { - llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop + llvm::SmallString<512> ThisPath; + for (const SearchPathInfo& Info : Paths) { + ThisPath = Info.Path; llvm::sys::path::append(ThisPath, libStem); bool exists; if (isSharedLibrary(ThisPath.str(), &exists)) From a9858aae2bb68d7657d9c23f68a69ba560fa36ff Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Fri, 12 Jul 2019 23:33:40 +0300 Subject: [PATCH 14/17] [tcling] Determine if a file is a shared library in a more reliable way. Improve code readability by early continue-s. --- core/metacling/src/TClingCallbacks.cxx | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/core/metacling/src/TClingCallbacks.cxx b/core/metacling/src/TClingCallbacks.cxx index ef848c73a2312..7dcaf7fbd574f 100644 --- a/core/metacling/src/TClingCallbacks.cxx +++ b/core/metacling/src/TClingCallbacks.cxx @@ -887,14 +887,16 @@ static void SearchAndAddPath(const std::string& Path, DirIt != DirEnd && !EC; DirIt.increment(EC)) { std::string FileName(DirIt->path()); - if (!llvm::sys::fs::is_directory(FileName) && llvm::sys::path::extension(FileName) == ".so") { - // No need to check linked libraries, as this function is only invoked - // for symbols that cannot be found (neither by dlsym nor in the JIT). - if (dyLibManager->isLibraryLoaded(FileName.c_str())) - continue; - sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName))); - flag = true; - } + if (llvm::sys::fs::is_directory(FileName)) + continue; + if (!cling::DynamicLibraryManager::isSharedLibrary(FileName)) + continue; + // No need to check linked libraries, as this function is only invoked + // for symbols that cannot be found (neither by dlsym nor in the JIT). + if (dyLibManager->isLibraryLoaded(FileName.c_str())) + continue; + sLibraries.push_back(std::make_pair(sPaths.size(), llvm::sys::path::filename(FileName))); + flag = true; } if (flag) From 2d8067464d05f797932562797974600dc21032f3 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Fri, 12 Jul 2019 23:37:05 +0300 Subject: [PATCH 15/17] Make the static function a local lambda. --- core/metacling/test/TClingTests.cxx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/core/metacling/test/TClingTests.cxx b/core/metacling/test/TClingTests.cxx index 5679bbdcf1f57..3d6462f4f98f9 100644 --- a/core/metacling/test/TClingTests.cxx +++ b/core/metacling/test/TClingTests.cxx @@ -136,16 +136,15 @@ static std::string MakeLibNamePlatformIndependent(llvm::StringRef libName) return libName.substr(0, libName.find_first_of('.')).str(); } -// Shortens the invocation. -static const char *GetLibs(const char *cls) -{ - return gInterpreter->GetClassSharedLibs(cls); -} - // Check if the heavily used interface in TCling::AutoLoad returns consistent // results. TEST_F(TClingTests, GetClassSharedLibs) { + // Shortens the invocation. + auto GetLibs = [](const char *cls) -> const char * { + return gInterpreter->GetClassSharedLibs(cls); + }; + llvm::StringRef lib = GetLibs("TLorentzVector"); ASSERT_STREQ("Physics", MakeLibNamePlatformIndependent(lib).c_str()); From 98e2cc9675894ca898068d579ab84951b38bc2e1 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Tue, 16 Jul 2019 13:14:04 +0300 Subject: [PATCH 16/17] [cxxmodules] Rework finding symbols in the dynamic symbol section of ELF. --- core/metacling/src/TCling.cxx | 60 ++++++++++++++++++++--------------- 1 file changed, 34 insertions(+), 26 deletions(-) diff --git a/core/metacling/src/TCling.cxx b/core/metacling/src/TCling.cxx index ffdc310201b8e..7027a65116b44 100644 --- a/core/metacling/src/TCling.cxx +++ b/core/metacling/src/TCling.cxx @@ -116,9 +116,10 @@ clang/LLVM technology. #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" +#include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ObjectFile.h" -#include "llvm/Support/FileSystem.h" #include "llvm/Object/SymbolicFile.h" +#include "llvm/Support/FileSystem.h" #include #include @@ -6114,8 +6115,8 @@ static bool LookupBloomFilter(llvm::object::ObjectFile *soFile, uint32_t hash) { /// Looks up symbols from a an object file, representing the library. ///\returns true on success. -static bool LookupNormalSymbol(const std::string &library_filename, - const std::string &mangled_name) +static bool FindSymbol(const std::string &library_filename, + const std::string &mangled_name) { auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename); if (!ObjF) { @@ -6147,7 +6148,7 @@ static bool LookupNormalSymbol(const std::string &library_filename, llvm::Expected SymNameErr = S.getName(); if (!SymNameErr) { - Warning("LookupNormalSymbol", "Failed to read symbol"); + Warning("TCling__FindSymbol", "Failed to read symbol %s", mangled_name.c_str()); continue; } @@ -6155,31 +6156,37 @@ static bool LookupNormalSymbol(const std::string &library_filename, return true; } - return false; -} - -///\returns true on success -static bool LookupDynamicSymbol(const std::string &library_filename, - const std::string &mangled_name) -{ - auto ObjF = llvm::object::ObjectFile::createObjectFile(library_filename); - if (!ObjF) + if (!BinObjFile->isELF()) return false; - llvm::object::ObjectFile *BinObjFile = ObjF.get().getBinary(); + // ELF file format has .dynstr section for the dynamic symbol table. + const auto *ElfObj = cast(BinObjFile); - for (const auto §ion : BinObjFile->sections()) { - llvm::StringRef sectionName; - section.getName(sectionName); + for (const auto &S : ElfObj->getDynamicSymbolIterators()) { + uint32_t Flags = S.getFlags(); + // DO NOT insert to table if symbol was undefined + if (Flags & llvm::object::SymbolRef::SF_Undefined) + continue; + + // Note, we are at last resort and loading library based on a weak + // symbol is allowed. Otherwise, the JIT will issue an unresolved + // symbol error. + // + // There are other weak symbol kinds (marked as 'V') to denote + // typeinfo and vtables. It is unclear whether we should load such + // libraries or from which library we should resolve the symbol. + // We seem to not have a way to differentiate it from the symbol API. - // .dynstr contains string of dynamic symbols - if (sectionName == ".dynstr") { - llvm::StringRef dContents; - section.getContents(dContents); - // If this library contains mangled name - return dContents.contains(mangled_name); + llvm::Expected SymNameErr = S.getName(); + if (!SymNameErr) { + Warning("TCling__FindSymbol", "Failed to read symbol %s", mangled_name.c_str()); + continue; } + + if (SymNameErr.get() == mangled_name) + return true; } + return false; } @@ -6249,7 +6256,7 @@ static std::string ResolveSymbol(const std::string& mangled_name, // libraries. However, it seems to be redundant for the moment as we do // not strictly require symbols from those sections. Enable after checking // performance! - if (LookupNormalSymbol(LibName, mangled_name)) { + if (FindSymbol(LibName, mangled_name)) { sQueriedLibraries.push_back(P); return LibName; } @@ -6267,7 +6274,7 @@ static std::string ResolveSymbol(const std::string& mangled_name, for (const LibraryPath &P : sSysLibraries) { const std::string LibName = GetLibFileName(P, sPaths); - if (LookupNormalSymbol(LibName, mangled_name) || LookupDynamicSymbol(LibName, mangled_name)) { + if (FindSymbol(LibName, mangled_name)) { sQueriedLibraries.push_back(P); return LibName; } @@ -6283,7 +6290,8 @@ static void* LazyFunctionCreatorAutoloadForModule(const std::string& mangled_nam return nullptr; if (gSystem->Load(LibName.c_str(), "", false) < 0) - Error("LazyFunctionCreatorAutoloadForModule", "Failed to load library %s", LibName.c_str()); + Error("TCling__LazyFunctionCreatorAutoloadForModule", + "Failed to load library %s", LibName.c_str()); void* addr = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(mangled_name.c_str()); return addr; From ea2ea4216140f75aa079d4730e9954834866b5d4 Mon Sep 17 00:00:00 2001 From: Vassil Vassilev Date: Wed, 17 Jul 2019 09:02:26 +0300 Subject: [PATCH 17/17] Suppress false positive warning. --- core/base/src/TSystem.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/base/src/TSystem.cxx b/core/base/src/TSystem.cxx index f9f25f628f8f4..5df008cdc2c44 100644 --- a/core/base/src/TSystem.cxx +++ b/core/base/src/TSystem.cxx @@ -3353,7 +3353,8 @@ int TSystem::CompileMacro(const char *filename, Option_t *opt, linkDepLibraries = linkLibs & 0x1; } - constexpr const bool useCxxModules = + // FIXME: Triggers clang false positive warning -Wunused-lambda-capture. + /*constexpr const*/ bool useCxxModules = #ifdef R__USE_CXXMODULES true; #else