1 //===- bolt/RuntimeLibs/RuntimeLibrary.cpp - Runtime Library --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the RuntimeLibrary class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "bolt/RuntimeLibs/RuntimeLibrary.h" 14 #include "bolt/RuntimeLibs/RuntimeLibraryVariables.inc" 15 #include "bolt/Utils/Utils.h" 16 #include "llvm/BinaryFormat/Magic.h" 17 #include "llvm/ExecutionEngine/RuntimeDyld.h" 18 #include "llvm/Object/Archive.h" 19 #include "llvm/Support/Path.h" 20 21 #define DEBUG_TYPE "bolt-rtlib" 22 23 using namespace llvm; 24 using namespace bolt; 25 26 void RuntimeLibrary::anchor() {} 27 28 std::string RuntimeLibrary::getLibPath(StringRef ToolPath, 29 StringRef LibFileName) { 30 StringRef Dir = llvm::sys::path::parent_path(ToolPath); 31 SmallString<128> LibPath = llvm::sys::path::parent_path(Dir); 32 llvm::sys::path::append(LibPath, "lib" LLVM_LIBDIR_SUFFIX); 33 if (!llvm::sys::fs::exists(LibPath)) { 34 // In some cases we install bolt binary into one level deeper in bin/, 35 // we need to go back one more level to find lib directory. 36 LibPath = llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir)); 37 llvm::sys::path::append(LibPath, "lib" LLVM_LIBDIR_SUFFIX); 38 } 39 llvm::sys::path::append(LibPath, LibFileName); 40 if (!llvm::sys::fs::exists(LibPath)) { 41 errs() << "BOLT-ERROR: library not found: " << LibPath << "\n"; 42 exit(1); 43 } 44 return std::string(LibPath.str()); 45 } 46 47 void RuntimeLibrary::loadLibrary(StringRef LibPath, RuntimeDyld &RTDyld) { 48 ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = 49 MemoryBuffer::getFile(LibPath, false, false); 50 check_error(MaybeBuf.getError(), LibPath); 51 std::unique_ptr<MemoryBuffer> B = std::move(MaybeBuf.get()); 52 file_magic Magic = identify_magic(B->getBuffer()); 53 54 if (Magic == file_magic::archive) { 55 Error Err = Error::success(); 56 object::Archive Archive(B.get()->getMemBufferRef(), Err); 57 for (const object::Archive::Child &C : Archive.children(Err)) { 58 std::unique_ptr<object::Binary> Bin = cantFail(C.getAsBinary()); 59 if (object::ObjectFile *Obj = dyn_cast<object::ObjectFile>(&*Bin)) 60 RTDyld.loadObject(*Obj); 61 } 62 check_error(std::move(Err), B->getBufferIdentifier()); 63 } else if (Magic == file_magic::elf_relocatable || 64 Magic == file_magic::elf_shared_object) { 65 std::unique_ptr<object::ObjectFile> Obj = cantFail( 66 object::ObjectFile::createObjectFile(B.get()->getMemBufferRef()), 67 "error creating in-memory object"); 68 RTDyld.loadObject(*Obj); 69 } else { 70 errs() << "BOLT-ERROR: unrecognized library format: " << LibPath << "\n"; 71 exit(1); 72 } 73 } 74