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/Utils/Utils.h" 15 #include "llvm/BinaryFormat/Magic.h" 16 #include "llvm/ExecutionEngine/RuntimeDyld.h" 17 #include "llvm/Object/Archive.h" 18 #include "llvm/Support/Path.h" 19 20 #define DEBUG_TYPE "bolt-rtlib" 21 22 using namespace llvm; 23 using namespace bolt; 24 25 void RuntimeLibrary::anchor() {} 26 27 std::string RuntimeLibrary::getLibPath(StringRef ToolPath, 28 StringRef LibFileName) { 29 StringRef Dir = llvm::sys::path::parent_path(ToolPath); 30 SmallString<128> LibPath = llvm::sys::path::parent_path(Dir); 31 llvm::sys::path::append(LibPath, "lib"); 32 if (!llvm::sys::fs::exists(LibPath)) { 33 // In some cases we install bolt binary into one level deeper in bin/, 34 // we need to go back one more level to find lib directory. 35 LibPath = llvm::sys::path::parent_path(llvm::sys::path::parent_path(Dir)); 36 llvm::sys::path::append(LibPath, "lib"); 37 } 38 llvm::sys::path::append(LibPath, LibFileName); 39 if (!llvm::sys::fs::exists(LibPath)) { 40 errs() << "BOLT-ERROR: library not found: " << LibPath << "\n"; 41 exit(1); 42 } 43 return std::string(LibPath.str()); 44 } 45 46 void RuntimeLibrary::loadLibrary(StringRef LibPath, RuntimeDyld &RTDyld) { 47 ErrorOr<std::unique_ptr<MemoryBuffer>> MaybeBuf = 48 MemoryBuffer::getFile(LibPath, false, false); 49 check_error(MaybeBuf.getError(), LibPath); 50 std::unique_ptr<MemoryBuffer> B = std::move(MaybeBuf.get()); 51 file_magic Magic = identify_magic(B->getBuffer()); 52 53 if (Magic == file_magic::archive) { 54 Error Err = Error::success(); 55 object::Archive Archive(B.get()->getMemBufferRef(), Err); 56 for (const object::Archive::Child &C : Archive.children(Err)) { 57 std::unique_ptr<object::Binary> Bin = cantFail(C.getAsBinary()); 58 if (object::ObjectFile *Obj = dyn_cast<object::ObjectFile>(&*Bin)) 59 RTDyld.loadObject(*Obj); 60 } 61 check_error(std::move(Err), B->getBufferIdentifier()); 62 } else if (Magic == file_magic::elf_relocatable || 63 Magic == file_magic::elf_shared_object) { 64 std::unique_ptr<object::ObjectFile> Obj = cantFail( 65 object::ObjectFile::createObjectFile(B.get()->getMemBufferRef()), 66 "error creating in-memory object"); 67 RTDyld.loadObject(*Obj); 68 } else { 69 errs() << "BOLT-ERROR: unrecognized library format: " << LibPath << "\n"; 70 exit(1); 71 } 72 } 73