1 //===--------- JITLinkGeneric.cpp - Generic JIT linker utilities ----------===// 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 // Generic JITLinker utility class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "JITLinkGeneric.h" 14 15 #include "llvm/Support/BinaryStreamReader.h" 16 #include "llvm/Support/MemoryBuffer.h" 17 18 #define DEBUG_TYPE "jitlink" 19 20 namespace llvm { 21 namespace jitlink { 22 23 JITLinkerBase::~JITLinkerBase() {} 24 25 void JITLinkerBase::linkPhase1(std::unique_ptr<JITLinkerBase> Self) { 26 27 LLVM_DEBUG({ 28 dbgs() << "Building jitlink graph for new input " 29 << Ctx->getObjectBuffer().getBufferIdentifier() << "...\n"; 30 }); 31 32 // Build the link graph. 33 if (auto GraphOrErr = buildGraph(Ctx->getObjectBuffer())) 34 G = std::move(*GraphOrErr); 35 else 36 return Ctx->notifyFailed(GraphOrErr.takeError()); 37 assert(G && "Graph should have been created by buildGraph above"); 38 39 LLVM_DEBUG({ 40 dbgs() << "Starting link phase 1 for graph " << G->getName() << "\n"; 41 }); 42 43 // Prune and optimize the graph. 44 if (auto Err = runPasses(Passes.PrePrunePasses)) 45 return Ctx->notifyFailed(std::move(Err)); 46 47 LLVM_DEBUG({ 48 dbgs() << "Link graph \"" << G->getName() << "\" pre-pruning:\n"; 49 dumpGraph(dbgs()); 50 }); 51 52 prune(*G); 53 54 LLVM_DEBUG({ 55 dbgs() << "Link graph \"" << G->getName() << "\" post-pruning:\n"; 56 dumpGraph(dbgs()); 57 }); 58 59 // Run post-pruning passes. 60 if (auto Err = runPasses(Passes.PostPrunePasses)) 61 return Ctx->notifyFailed(std::move(Err)); 62 63 // Sort blocks into segments. 64 auto Layout = layOutBlocks(); 65 66 // Allocate memory for segments. 67 if (auto Err = allocateSegments(Layout)) 68 return Ctx->notifyFailed(std::move(Err)); 69 70 // Notify client that the defined symbols have been assigned addresses. 71 LLVM_DEBUG( 72 { dbgs() << "Resolving symbols defined in " << G->getName() << "\n"; }); 73 74 if (auto Err = Ctx->notifyResolved(*G)) 75 return Ctx->notifyFailed(std::move(Err)); 76 77 auto ExternalSymbols = getExternalSymbolNames(); 78 79 LLVM_DEBUG({ 80 dbgs() << "Issuing lookup for external symbols for " << G->getName() 81 << " (may trigger materialization/linking of other graphs)...\n"; 82 }); 83 84 // We're about to hand off ownership of ourself to the continuation. Grab a 85 // pointer to the context so that we can call it to initiate the lookup. 86 // 87 // FIXME: Once callee expressions are defined to be sequenced before argument 88 // expressions (c++17) we can simplify all this to: 89 // 90 // Ctx->lookup(std::move(UnresolvedExternals), 91 // [Self=std::move(Self)](Expected<AsyncLookupResult> Result) { 92 // Self->linkPhase2(std::move(Self), std::move(Result)); 93 // }); 94 auto *TmpCtx = Ctx.get(); 95 TmpCtx->lookup(std::move(ExternalSymbols), 96 createLookupContinuation( 97 [S = std::move(Self), L = std::move(Layout)]( 98 Expected<AsyncLookupResult> LookupResult) mutable { 99 auto &TmpSelf = *S; 100 TmpSelf.linkPhase2(std::move(S), std::move(LookupResult), 101 std::move(L)); 102 })); 103 } 104 105 void JITLinkerBase::linkPhase2(std::unique_ptr<JITLinkerBase> Self, 106 Expected<AsyncLookupResult> LR, 107 SegmentLayoutMap Layout) { 108 109 LLVM_DEBUG({ 110 dbgs() << "Starting link phase 2 for graph " << G->getName() << "\n"; 111 }); 112 113 // If the lookup failed, bail out. 114 if (!LR) 115 return deallocateAndBailOut(LR.takeError()); 116 117 // Assign addresses to external addressables. 118 applyLookupResult(*LR); 119 120 // Copy block content to working memory. 121 copyBlockContentToWorkingMemory(Layout, *Alloc); 122 123 LLVM_DEBUG({ 124 dbgs() << "Link graph \"" << G->getName() 125 << "\" before post-allocation passes:\n"; 126 dumpGraph(dbgs()); 127 }); 128 129 if (auto Err = runPasses(Passes.PostAllocationPasses)) 130 return deallocateAndBailOut(std::move(Err)); 131 132 LLVM_DEBUG({ 133 dbgs() << "Link graph \"" << G->getName() << "\" before copy-and-fixup:\n"; 134 dumpGraph(dbgs()); 135 }); 136 137 // Fix up block content. 138 if (auto Err = fixUpBlocks(*G)) 139 return deallocateAndBailOut(std::move(Err)); 140 141 LLVM_DEBUG({ 142 dbgs() << "Link graph \"" << G->getName() << "\" after copy-and-fixup:\n"; 143 dumpGraph(dbgs()); 144 }); 145 146 if (auto Err = runPasses(Passes.PostFixupPasses)) 147 return deallocateAndBailOut(std::move(Err)); 148 149 // FIXME: Use move capture once we have c++14. 150 auto *UnownedSelf = Self.release(); 151 auto Phase3Continuation = [UnownedSelf](Error Err) { 152 std::unique_ptr<JITLinkerBase> Self(UnownedSelf); 153 UnownedSelf->linkPhase3(std::move(Self), std::move(Err)); 154 }; 155 156 Alloc->finalizeAsync(std::move(Phase3Continuation)); 157 } 158 159 void JITLinkerBase::linkPhase3(std::unique_ptr<JITLinkerBase> Self, Error Err) { 160 161 LLVM_DEBUG({ 162 dbgs() << "Starting link phase 3 for graph " << G->getName() << "\n"; 163 }); 164 165 if (Err) 166 return deallocateAndBailOut(std::move(Err)); 167 Ctx->notifyFinalized(std::move(Alloc)); 168 169 LLVM_DEBUG({ dbgs() << "Link of graph " << G->getName() << " complete\n"; }); 170 } 171 172 Error JITLinkerBase::runPasses(LinkGraphPassList &Passes) { 173 for (auto &P : Passes) 174 if (auto Err = P(*G)) 175 return Err; 176 return Error::success(); 177 } 178 179 JITLinkerBase::SegmentLayoutMap JITLinkerBase::layOutBlocks() { 180 181 SegmentLayoutMap Layout; 182 183 /// Partition blocks based on permissions and content vs. zero-fill. 184 for (auto *B : G->blocks()) { 185 auto &SegLists = Layout[B->getSection().getProtectionFlags()]; 186 if (!B->isZeroFill()) 187 SegLists.ContentBlocks.push_back(B); 188 else 189 SegLists.ZeroFillBlocks.push_back(B); 190 } 191 192 /// Sort blocks within each list. 193 for (auto &KV : Layout) { 194 195 auto CompareBlocks = [](const Block *LHS, const Block *RHS) { 196 // Sort by section, address and size 197 if (LHS->getSection().getOrdinal() != RHS->getSection().getOrdinal()) 198 return LHS->getSection().getOrdinal() < RHS->getSection().getOrdinal(); 199 if (LHS->getAddress() != RHS->getAddress()) 200 return LHS->getAddress() < RHS->getAddress(); 201 return LHS->getSize() < RHS->getSize(); 202 }; 203 204 auto &SegLists = KV.second; 205 llvm::sort(SegLists.ContentBlocks, CompareBlocks); 206 llvm::sort(SegLists.ZeroFillBlocks, CompareBlocks); 207 } 208 209 LLVM_DEBUG({ 210 dbgs() << "Computed segment ordering:\n"; 211 for (auto &KV : Layout) { 212 dbgs() << " Segment " 213 << static_cast<sys::Memory::ProtectionFlags>(KV.first) << ":\n"; 214 auto &SL = KV.second; 215 for (auto &SIEntry : 216 {std::make_pair(&SL.ContentBlocks, "content block"), 217 std::make_pair(&SL.ZeroFillBlocks, "zero-fill block")}) { 218 dbgs() << " " << SIEntry.second << ":\n"; 219 for (auto *B : *SIEntry.first) 220 dbgs() << " " << *B << "\n"; 221 } 222 } 223 }); 224 225 return Layout; 226 } 227 228 Error JITLinkerBase::allocateSegments(const SegmentLayoutMap &Layout) { 229 230 // Compute segment sizes and allocate memory. 231 LLVM_DEBUG(dbgs() << "JIT linker requesting: { "); 232 JITLinkMemoryManager::SegmentsRequestMap Segments; 233 for (auto &KV : Layout) { 234 auto &Prot = KV.first; 235 auto &SegLists = KV.second; 236 237 uint64_t SegAlign = 1; 238 239 // Calculate segment content size. 240 size_t SegContentSize = 0; 241 for (auto *B : SegLists.ContentBlocks) { 242 SegAlign = std::max(SegAlign, B->getAlignment()); 243 SegContentSize = alignToBlock(SegContentSize, *B); 244 SegContentSize += B->getSize(); 245 } 246 247 uint64_t SegZeroFillStart = SegContentSize; 248 uint64_t SegZeroFillEnd = SegZeroFillStart; 249 250 for (auto *B : SegLists.ZeroFillBlocks) { 251 SegAlign = std::max(SegAlign, B->getAlignment()); 252 SegZeroFillEnd = alignToBlock(SegZeroFillEnd, *B); 253 SegZeroFillEnd += B->getSize(); 254 } 255 256 Segments[Prot] = {SegAlign, SegContentSize, 257 SegZeroFillEnd - SegZeroFillStart}; 258 259 LLVM_DEBUG({ 260 dbgs() << (&KV == &*Layout.begin() ? "" : "; ") 261 << static_cast<sys::Memory::ProtectionFlags>(Prot) 262 << ": alignment = " << SegAlign 263 << ", content size = " << SegContentSize 264 << ", zero-fill size = " << (SegZeroFillEnd - SegZeroFillStart); 265 }); 266 } 267 LLVM_DEBUG(dbgs() << " }\n"); 268 269 if (auto AllocOrErr = 270 Ctx->getMemoryManager().allocate(Ctx->getJITLinkDylib(), Segments)) 271 Alloc = std::move(*AllocOrErr); 272 else 273 return AllocOrErr.takeError(); 274 275 LLVM_DEBUG({ 276 dbgs() << "JIT linker got memory (working -> target):\n"; 277 for (auto &KV : Layout) { 278 auto Prot = static_cast<sys::Memory::ProtectionFlags>(KV.first); 279 dbgs() << " " << Prot << ": " 280 << (const void *)Alloc->getWorkingMemory(Prot).data() << " -> " 281 << formatv("{0:x16}", Alloc->getTargetMemory(Prot)) << "\n"; 282 } 283 }); 284 285 // Update block target addresses. 286 for (auto &KV : Layout) { 287 auto &Prot = KV.first; 288 auto &SL = KV.second; 289 290 JITTargetAddress NextBlockAddr = 291 Alloc->getTargetMemory(static_cast<sys::Memory::ProtectionFlags>(Prot)); 292 293 for (auto *SIList : {&SL.ContentBlocks, &SL.ZeroFillBlocks}) 294 for (auto *B : *SIList) { 295 NextBlockAddr = alignToBlock(NextBlockAddr, *B); 296 B->setAddress(NextBlockAddr); 297 NextBlockAddr += B->getSize(); 298 } 299 } 300 301 return Error::success(); 302 } 303 304 JITLinkContext::LookupMap JITLinkerBase::getExternalSymbolNames() const { 305 // Identify unresolved external symbols. 306 JITLinkContext::LookupMap UnresolvedExternals; 307 for (auto *Sym : G->external_symbols()) { 308 assert(Sym->getAddress() == 0 && 309 "External has already been assigned an address"); 310 assert(Sym->getName() != StringRef() && Sym->getName() != "" && 311 "Externals must be named"); 312 SymbolLookupFlags LookupFlags = 313 Sym->getLinkage() == Linkage::Weak 314 ? SymbolLookupFlags::WeaklyReferencedSymbol 315 : SymbolLookupFlags::RequiredSymbol; 316 UnresolvedExternals[Sym->getName()] = LookupFlags; 317 } 318 return UnresolvedExternals; 319 } 320 321 void JITLinkerBase::applyLookupResult(AsyncLookupResult Result) { 322 for (auto *Sym : G->external_symbols()) { 323 assert(Sym->getOffset() == 0 && 324 "External symbol is not at the start of its addressable block"); 325 assert(Sym->getAddress() == 0 && "Symbol already resolved"); 326 assert(!Sym->isDefined() && "Symbol being resolved is already defined"); 327 auto ResultI = Result.find(Sym->getName()); 328 if (ResultI != Result.end()) 329 Sym->getAddressable().setAddress(ResultI->second.getAddress()); 330 else 331 assert(Sym->getLinkage() == Linkage::Weak && 332 "Failed to resolve non-weak reference"); 333 } 334 335 LLVM_DEBUG({ 336 dbgs() << "Externals after applying lookup result:\n"; 337 for (auto *Sym : G->external_symbols()) 338 dbgs() << " " << Sym->getName() << ": " 339 << formatv("{0:x16}", Sym->getAddress()) << "\n"; 340 }); 341 } 342 343 void JITLinkerBase::copyBlockContentToWorkingMemory( 344 const SegmentLayoutMap &Layout, JITLinkMemoryManager::Allocation &Alloc) { 345 346 LLVM_DEBUG(dbgs() << "Copying block content:\n"); 347 for (auto &KV : Layout) { 348 auto &Prot = KV.first; 349 auto &SegLayout = KV.second; 350 351 auto SegMem = 352 Alloc.getWorkingMemory(static_cast<sys::Memory::ProtectionFlags>(Prot)); 353 char *LastBlockEnd = SegMem.data(); 354 char *BlockDataPtr = LastBlockEnd; 355 356 LLVM_DEBUG({ 357 dbgs() << " Processing segment " 358 << static_cast<sys::Memory::ProtectionFlags>(Prot) << " [ " 359 << (const void *)SegMem.data() << " .. " 360 << (const void *)((char *)SegMem.data() + SegMem.size()) 361 << " ]\n Processing content sections:\n"; 362 }); 363 364 for (auto *B : SegLayout.ContentBlocks) { 365 LLVM_DEBUG(dbgs() << " " << *B << ":\n"); 366 367 // Pad to alignment/alignment-offset. 368 BlockDataPtr = alignToBlock(BlockDataPtr, *B); 369 370 LLVM_DEBUG({ 371 dbgs() << " Bumped block pointer to " << (const void *)BlockDataPtr 372 << " to meet block alignment " << B->getAlignment() 373 << " and alignment offset " << B->getAlignmentOffset() << "\n"; 374 }); 375 376 // Zero pad up to alignment. 377 LLVM_DEBUG({ 378 if (LastBlockEnd != BlockDataPtr) 379 dbgs() << " Zero padding from " << (const void *)LastBlockEnd 380 << " to " << (const void *)BlockDataPtr << "\n"; 381 }); 382 383 while (LastBlockEnd != BlockDataPtr) 384 *LastBlockEnd++ = 0; 385 386 // Copy initial block content. 387 LLVM_DEBUG({ 388 dbgs() << " Copying block " << *B << " content, " 389 << B->getContent().size() << " bytes, from " 390 << (const void *)B->getContent().data() << " to " 391 << (const void *)BlockDataPtr << "\n"; 392 }); 393 memcpy(BlockDataPtr, B->getContent().data(), B->getContent().size()); 394 395 // Point the block's content to the fixed up buffer. 396 B->setContent(StringRef(BlockDataPtr, B->getContent().size())); 397 398 // Update block end pointer. 399 LastBlockEnd = BlockDataPtr + B->getContent().size(); 400 BlockDataPtr = LastBlockEnd; 401 } 402 403 // Zero pad the rest of the segment. 404 LLVM_DEBUG({ 405 dbgs() << " Zero padding end of segment from " 406 << (const void *)LastBlockEnd << " to " 407 << (const void *)((char *)SegMem.data() + SegMem.size()) << "\n"; 408 }); 409 while (LastBlockEnd != SegMem.data() + SegMem.size()) 410 *LastBlockEnd++ = 0; 411 } 412 } 413 414 void JITLinkerBase::deallocateAndBailOut(Error Err) { 415 assert(Err && "Should not be bailing out on success value"); 416 assert(Alloc && "can not call deallocateAndBailOut before allocation"); 417 Ctx->notifyFailed(joinErrors(std::move(Err), Alloc->deallocate())); 418 } 419 420 void JITLinkerBase::dumpGraph(raw_ostream &OS) { 421 assert(G && "Graph is not set yet"); 422 G->dump(dbgs(), [this](Edge::Kind K) { return getEdgeKindName(K); }); 423 } 424 425 void prune(LinkGraph &G) { 426 std::vector<Symbol *> Worklist; 427 DenseSet<Block *> VisitedBlocks; 428 429 // Build the initial worklist from all symbols initially live. 430 for (auto *Sym : G.defined_symbols()) 431 if (Sym->isLive()) 432 Worklist.push_back(Sym); 433 434 // Propagate live flags to all symbols reachable from the initial live set. 435 while (!Worklist.empty()) { 436 auto *Sym = Worklist.back(); 437 Worklist.pop_back(); 438 439 auto &B = Sym->getBlock(); 440 441 // Skip addressables that we've visited before. 442 if (VisitedBlocks.count(&B)) 443 continue; 444 445 VisitedBlocks.insert(&B); 446 447 for (auto &E : Sym->getBlock().edges()) { 448 // If the edge target is a defined symbol that is being newly marked live 449 // then add it to the worklist. 450 if (E.getTarget().isDefined() && !E.getTarget().isLive()) 451 Worklist.push_back(&E.getTarget()); 452 453 // Mark the target live. 454 E.getTarget().setLive(true); 455 } 456 } 457 458 // Collect all defined symbols to remove, then remove them. 459 { 460 LLVM_DEBUG(dbgs() << "Dead-stripping defined symbols:\n"); 461 std::vector<Symbol *> SymbolsToRemove; 462 for (auto *Sym : G.defined_symbols()) 463 if (!Sym->isLive()) 464 SymbolsToRemove.push_back(Sym); 465 for (auto *Sym : SymbolsToRemove) { 466 LLVM_DEBUG(dbgs() << " " << *Sym << "...\n"); 467 G.removeDefinedSymbol(*Sym); 468 } 469 } 470 471 // Delete any unused blocks. 472 { 473 LLVM_DEBUG(dbgs() << "Dead-stripping blocks:\n"); 474 std::vector<Block *> BlocksToRemove; 475 for (auto *B : G.blocks()) 476 if (!VisitedBlocks.count(B)) 477 BlocksToRemove.push_back(B); 478 for (auto *B : BlocksToRemove) { 479 LLVM_DEBUG(dbgs() << " " << *B << "...\n"); 480 G.removeBlock(*B); 481 } 482 } 483 484 // Collect all external symbols to remove, then remove them. 485 { 486 LLVM_DEBUG(dbgs() << "Removing unused external symbols:\n"); 487 std::vector<Symbol *> SymbolsToRemove; 488 for (auto *Sym : G.external_symbols()) 489 if (!Sym->isLive()) 490 SymbolsToRemove.push_back(Sym); 491 for (auto *Sym : SymbolsToRemove) { 492 LLVM_DEBUG(dbgs() << " " << *Sym << "...\n"); 493 G.removeExternalSymbol(*Sym); 494 } 495 } 496 } 497 498 } // end namespace jitlink 499 } // end namespace llvm 500