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 = Ctx->getMemoryManager().allocate(Segments)) 270 Alloc = std::move(*AllocOrErr); 271 else 272 return AllocOrErr.takeError(); 273 274 LLVM_DEBUG({ 275 dbgs() << "JIT linker got memory (working -> target):\n"; 276 for (auto &KV : Layout) { 277 auto Prot = static_cast<sys::Memory::ProtectionFlags>(KV.first); 278 dbgs() << " " << Prot << ": " 279 << (const void *)Alloc->getWorkingMemory(Prot).data() << " -> " 280 << formatv("{0:x16}", Alloc->getTargetMemory(Prot)) << "\n"; 281 } 282 }); 283 284 // Update block target addresses. 285 for (auto &KV : Layout) { 286 auto &Prot = KV.first; 287 auto &SL = KV.second; 288 289 JITTargetAddress NextBlockAddr = 290 Alloc->getTargetMemory(static_cast<sys::Memory::ProtectionFlags>(Prot)); 291 292 for (auto *SIList : {&SL.ContentBlocks, &SL.ZeroFillBlocks}) 293 for (auto *B : *SIList) { 294 NextBlockAddr = alignToBlock(NextBlockAddr, *B); 295 B->setAddress(NextBlockAddr); 296 NextBlockAddr += B->getSize(); 297 } 298 } 299 300 return Error::success(); 301 } 302 303 JITLinkContext::LookupMap JITLinkerBase::getExternalSymbolNames() const { 304 // Identify unresolved external symbols. 305 JITLinkContext::LookupMap UnresolvedExternals; 306 for (auto *Sym : G->external_symbols()) { 307 assert(Sym->getAddress() == 0 && 308 "External has already been assigned an address"); 309 assert(Sym->getName() != StringRef() && Sym->getName() != "" && 310 "Externals must be named"); 311 SymbolLookupFlags LookupFlags = 312 Sym->getLinkage() == Linkage::Weak 313 ? SymbolLookupFlags::WeaklyReferencedSymbol 314 : SymbolLookupFlags::RequiredSymbol; 315 UnresolvedExternals[Sym->getName()] = LookupFlags; 316 } 317 return UnresolvedExternals; 318 } 319 320 void JITLinkerBase::applyLookupResult(AsyncLookupResult Result) { 321 for (auto *Sym : G->external_symbols()) { 322 assert(Sym->getOffset() == 0 && 323 "External symbol is not at the start of its addressable block"); 324 assert(Sym->getAddress() == 0 && "Symbol already resolved"); 325 assert(!Sym->isDefined() && "Symbol being resolved is already defined"); 326 auto ResultI = Result.find(Sym->getName()); 327 if (ResultI != Result.end()) 328 Sym->getAddressable().setAddress(ResultI->second.getAddress()); 329 else 330 assert(Sym->getLinkage() == Linkage::Weak && 331 "Failed to resolve non-weak reference"); 332 } 333 334 LLVM_DEBUG({ 335 dbgs() << "Externals after applying lookup result:\n"; 336 for (auto *Sym : G->external_symbols()) 337 dbgs() << " " << Sym->getName() << ": " 338 << formatv("{0:x16}", Sym->getAddress()) << "\n"; 339 }); 340 } 341 342 void JITLinkerBase::copyBlockContentToWorkingMemory( 343 const SegmentLayoutMap &Layout, JITLinkMemoryManager::Allocation &Alloc) { 344 345 LLVM_DEBUG(dbgs() << "Copying block content:\n"); 346 for (auto &KV : Layout) { 347 auto &Prot = KV.first; 348 auto &SegLayout = KV.second; 349 350 auto SegMem = 351 Alloc.getWorkingMemory(static_cast<sys::Memory::ProtectionFlags>(Prot)); 352 char *LastBlockEnd = SegMem.data(); 353 char *BlockDataPtr = LastBlockEnd; 354 355 LLVM_DEBUG({ 356 dbgs() << " Processing segment " 357 << static_cast<sys::Memory::ProtectionFlags>(Prot) << " [ " 358 << (const void *)SegMem.data() << " .. " 359 << (const void *)((char *)SegMem.data() + SegMem.size()) 360 << " ]\n Processing content sections:\n"; 361 }); 362 363 for (auto *B : SegLayout.ContentBlocks) { 364 LLVM_DEBUG(dbgs() << " " << *B << ":\n"); 365 366 // Pad to alignment/alignment-offset. 367 BlockDataPtr = alignToBlock(BlockDataPtr, *B); 368 369 LLVM_DEBUG({ 370 dbgs() << " Bumped block pointer to " << (const void *)BlockDataPtr 371 << " to meet block alignment " << B->getAlignment() 372 << " and alignment offset " << B->getAlignmentOffset() << "\n"; 373 }); 374 375 // Zero pad up to alignment. 376 LLVM_DEBUG({ 377 if (LastBlockEnd != BlockDataPtr) 378 dbgs() << " Zero padding from " << (const void *)LastBlockEnd 379 << " to " << (const void *)BlockDataPtr << "\n"; 380 }); 381 382 while (LastBlockEnd != BlockDataPtr) 383 *LastBlockEnd++ = 0; 384 385 // Copy initial block content. 386 LLVM_DEBUG({ 387 dbgs() << " Copying block " << *B << " content, " 388 << B->getContent().size() << " bytes, from " 389 << (const void *)B->getContent().data() << " to " 390 << (const void *)BlockDataPtr << "\n"; 391 }); 392 memcpy(BlockDataPtr, B->getContent().data(), B->getContent().size()); 393 394 // Point the block's content to the fixed up buffer. 395 B->setContent(StringRef(BlockDataPtr, B->getContent().size())); 396 397 // Update block end pointer. 398 LastBlockEnd = BlockDataPtr + B->getContent().size(); 399 BlockDataPtr = LastBlockEnd; 400 } 401 402 // Zero pad the rest of the segment. 403 LLVM_DEBUG({ 404 dbgs() << " Zero padding end of segment from " 405 << (const void *)LastBlockEnd << " to " 406 << (const void *)((char *)SegMem.data() + SegMem.size()) << "\n"; 407 }); 408 while (LastBlockEnd != SegMem.data() + SegMem.size()) 409 *LastBlockEnd++ = 0; 410 } 411 } 412 413 void JITLinkerBase::deallocateAndBailOut(Error Err) { 414 assert(Err && "Should not be bailing out on success value"); 415 assert(Alloc && "can not call deallocateAndBailOut before allocation"); 416 Ctx->notifyFailed(joinErrors(std::move(Err), Alloc->deallocate())); 417 } 418 419 void JITLinkerBase::dumpGraph(raw_ostream &OS) { 420 assert(G && "Graph is not set yet"); 421 G->dump(dbgs(), [this](Edge::Kind K) { return getEdgeKindName(K); }); 422 } 423 424 void prune(LinkGraph &G) { 425 std::vector<Symbol *> Worklist; 426 DenseSet<Block *> VisitedBlocks; 427 428 // Build the initial worklist from all symbols initially live. 429 for (auto *Sym : G.defined_symbols()) 430 if (Sym->isLive()) 431 Worklist.push_back(Sym); 432 433 // Propagate live flags to all symbols reachable from the initial live set. 434 while (!Worklist.empty()) { 435 auto *Sym = Worklist.back(); 436 Worklist.pop_back(); 437 438 auto &B = Sym->getBlock(); 439 440 // Skip addressables that we've visited before. 441 if (VisitedBlocks.count(&B)) 442 continue; 443 444 VisitedBlocks.insert(&B); 445 446 for (auto &E : Sym->getBlock().edges()) { 447 // If the edge target is a defined symbol that is being newly marked live 448 // then add it to the worklist. 449 if (E.getTarget().isDefined() && !E.getTarget().isLive()) 450 Worklist.push_back(&E.getTarget()); 451 452 // Mark the target live. 453 E.getTarget().setLive(true); 454 } 455 } 456 457 // Collect all defined symbols to remove, then remove them. 458 { 459 LLVM_DEBUG(dbgs() << "Dead-stripping defined symbols:\n"); 460 std::vector<Symbol *> SymbolsToRemove; 461 for (auto *Sym : G.defined_symbols()) 462 if (!Sym->isLive()) 463 SymbolsToRemove.push_back(Sym); 464 for (auto *Sym : SymbolsToRemove) { 465 LLVM_DEBUG(dbgs() << " " << *Sym << "...\n"); 466 G.removeDefinedSymbol(*Sym); 467 } 468 } 469 470 // Delete any unused blocks. 471 { 472 LLVM_DEBUG(dbgs() << "Dead-stripping blocks:\n"); 473 std::vector<Block *> BlocksToRemove; 474 for (auto *B : G.blocks()) 475 if (!VisitedBlocks.count(B)) 476 BlocksToRemove.push_back(B); 477 for (auto *B : BlocksToRemove) { 478 LLVM_DEBUG(dbgs() << " " << *B << "...\n"); 479 G.removeBlock(*B); 480 } 481 } 482 483 // Collect all external symbols to remove, then remove them. 484 { 485 LLVM_DEBUG(dbgs() << "Removing unused external symbols:\n"); 486 std::vector<Symbol *> SymbolsToRemove; 487 for (auto *Sym : G.external_symbols()) 488 if (!Sym->isLive()) 489 SymbolsToRemove.push_back(Sym); 490 for (auto *Sym : SymbolsToRemove) { 491 LLVM_DEBUG(dbgs() << " " << *Sym << "...\n"); 492 G.removeExternalSymbol(*Sym); 493 } 494 } 495 } 496 497 } // end namespace jitlink 498 } // end namespace llvm 499