1 //===- ConcatOutputSection.cpp --------------------------------------------===// 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 #include "ConcatOutputSection.h" 10 #include "Config.h" 11 #include "OutputSegment.h" 12 #include "SymbolTable.h" 13 #include "Symbols.h" 14 #include "SyntheticSections.h" 15 #include "Target.h" 16 #include "lld/Common/ErrorHandler.h" 17 #include "lld/Common/Memory.h" 18 #include "llvm/BinaryFormat/MachO.h" 19 #include "llvm/Support/ScopedPrinter.h" 20 #include "llvm/Support/TimeProfiler.h" 21 22 using namespace llvm; 23 using namespace llvm::MachO; 24 using namespace lld; 25 using namespace lld::macho; 26 27 MapVector<NamePair, ConcatOutputSection *> macho::concatOutputSections; 28 29 void ConcatOutputSection::addInput(ConcatInputSection *input) { 30 assert(input->parent == this); 31 if (inputs.empty()) { 32 align = input->align; 33 flags = input->getFlags(); 34 } else { 35 align = std::max(align, input->align); 36 finalizeFlags(input); 37 } 38 inputs.push_back(input); 39 } 40 41 // Branch-range extension can be implemented in two ways, either through ... 42 // 43 // (1) Branch islands: Single branch instructions (also of limited range), 44 // that might be chained in multiple hops to reach the desired 45 // destination. On ARM64, as 16 branch islands are needed to hop between 46 // opposite ends of a 2 GiB program. LD64 uses branch islands exclusively, 47 // even when it needs excessive hops. 48 // 49 // (2) Thunks: Instruction(s) to load the destination address into a scratch 50 // register, followed by a register-indirect branch. Thunks are 51 // constructed to reach any arbitrary address, so need not be 52 // chained. Although thunks need not be chained, a program might need 53 // multiple thunks to the same destination distributed throughout a large 54 // program so that all call sites can have one within range. 55 // 56 // The optimal approach is to mix islands for destinations within two hops, 57 // and use thunks for destinations at greater distance. For now, we only 58 // implement thunks. TODO: Adding support for branch islands! 59 // 60 // Internally -- as expressed in LLD's data structures -- a 61 // branch-range-extension thunk comprises ... 62 // 63 // (1) new Defined privateExtern symbol for the thunk named 64 // <FUNCTION>.thunk.<SEQUENCE>, which references ... 65 // (2) new InputSection, which contains ... 66 // (3.1) new data for the instructions to load & branch to the far address + 67 // (3.2) new Relocs on instructions to load the far address, which reference ... 68 // (4.1) existing Defined extern symbol for the real function in __text, or 69 // (4.2) existing DylibSymbol for the real function in a dylib 70 // 71 // Nearly-optimal thunk-placement algorithm features: 72 // 73 // * Single pass: O(n) on the number of call sites. 74 // 75 // * Accounts for the exact space overhead of thunks - no heuristics 76 // 77 // * Exploits the full range of call instructions - forward & backward 78 // 79 // Data: 80 // 81 // * DenseMap<Symbol *, ThunkInfo> thunkMap: Maps the function symbol 82 // to its thunk bookkeeper. 83 // 84 // * struct ThunkInfo (bookkeeper): Call instructions have limited range, and 85 // distant call sites might be unable to reach the same thunk, so multiple 86 // thunks are necessary to serve all call sites in a very large program. A 87 // thunkInfo stores state for all thunks associated with a particular 88 // function: (a) thunk symbol, (b) input section containing stub code, and 89 // (c) sequence number for the active thunk incarnation. When an old thunk 90 // goes out of range, we increment the sequence number and create a new 91 // thunk named <FUNCTION>.thunk.<SEQUENCE>. 92 // 93 // * A thunk incarnation comprises (a) private-extern Defined symbol pointing 94 // to (b) an InputSection holding machine instructions (similar to a MachO 95 // stub), and (c) Reloc(s) that reference the real function for fixing-up 96 // the stub code. 97 // 98 // * std::vector<InputSection *> MergedInputSection::thunks: A vector parallel 99 // to the inputs vector. We store new thunks via cheap vector append, rather 100 // than costly insertion into the inputs vector. 101 // 102 // Control Flow: 103 // 104 // * During address assignment, MergedInputSection::finalize() examines call 105 // sites by ascending address and creates thunks. When a function is beyond 106 // the range of a call site, we need a thunk. Place it at the largest 107 // available forward address from the call site. Call sites increase 108 // monotonically and thunks are always placed as far forward as possible; 109 // thus, we place thunks at monotonically increasing addresses. Once a thunk 110 // is placed, it and all previous input-section addresses are final. 111 // 112 // * ConcatInputSection::finalize() and ConcatInputSection::writeTo() merge 113 // the inputs and thunks vectors (both ordered by ascending address), which 114 // is simple and cheap. 115 116 DenseMap<Symbol *, ThunkInfo> lld::macho::thunkMap; 117 118 // Determine whether we need thunks, which depends on the target arch -- RISC 119 // (i.e., ARM) generally does because it has limited-range branch/call 120 // instructions, whereas CISC (i.e., x86) generally doesn't. RISC only needs 121 // thunks for programs so large that branch source & destination addresses 122 // might differ more than the range of branch instruction(s). 123 bool ConcatOutputSection::needsThunks() const { 124 if (!target->usesThunks()) 125 return false; 126 uint64_t isecAddr = addr; 127 for (InputSection *isec : inputs) 128 isecAddr = alignTo(isecAddr, isec->align) + isec->getSize(); 129 if (isecAddr - addr + in.stubs->getSize() <= 130 std::min(target->backwardBranchRange, target->forwardBranchRange)) 131 return false; 132 // Yes, this program is large enough to need thunks. 133 for (InputSection *isec : inputs) { 134 for (Reloc &r : isec->relocs) { 135 if (!target->hasAttr(r.type, RelocAttrBits::BRANCH)) 136 continue; 137 auto *sym = r.referent.get<Symbol *>(); 138 // Pre-populate the thunkMap and memoize call site counts for every 139 // InputSection and ThunkInfo. We do this for the benefit of 140 // ConcatOutputSection::estimateStubsInRangeVA() 141 ThunkInfo &thunkInfo = thunkMap[sym]; 142 // Knowing ThunkInfo call site count will help us know whether or not we 143 // might need to create more for this referent at the time we are 144 // estimating distance to __stubs in estimateStubsInRangeVA(). 145 ++thunkInfo.callSiteCount; 146 // Knowing InputSection call site count will help us avoid work on those 147 // that have no BRANCH relocs. 148 ++isec->callSiteCount; 149 } 150 } 151 return true; 152 } 153 154 // Since __stubs is placed after __text, we must estimate the address 155 // beyond which stubs are within range of a simple forward branch. 156 // This is called exactly once, when the last input section has been finalized. 157 uint64_t ConcatOutputSection::estimateStubsInRangeVA(size_t callIdx) const { 158 // Tally the functions which still have call sites remaining to process, 159 // which yields the maximum number of thunks we might yet place. 160 size_t maxPotentialThunks = 0; 161 for (auto &tp : thunkMap) { 162 ThunkInfo &ti = tp.second; 163 // This overcounts: Only sections that are in forward jump range from the 164 // currently-active section get finalized, and all input sections are 165 // finalized when estimateStubsInRangeVA() is called. So only backward 166 // jumps will need thunks, but we count all jumps. 167 if (ti.callSitesUsed < ti.callSiteCount) 168 maxPotentialThunks += 1; 169 } 170 // Tally the total size of input sections remaining to process. 171 uint64_t isecVA = inputs[callIdx]->getVA(); 172 uint64_t isecEnd = isecVA; 173 for (size_t i = callIdx; i < inputs.size(); i++) { 174 InputSection *isec = inputs[i]; 175 isecEnd = alignTo(isecEnd, isec->align) + isec->getSize(); 176 } 177 // Estimate the address after which call sites can safely call stubs 178 // directly rather than through intermediary thunks. 179 uint64_t forwardBranchRange = target->forwardBranchRange; 180 assert(isecEnd > forwardBranchRange && 181 "should not run thunk insertion if all code fits in jump range"); 182 assert(isecEnd - isecVA <= forwardBranchRange && 183 "should only finalize sections in jump range"); 184 uint64_t stubsInRangeVA = isecEnd + maxPotentialThunks * target->thunkSize + 185 in.stubs->getSize() - forwardBranchRange; 186 log("thunks = " + std::to_string(thunkMap.size()) + 187 ", potential = " + std::to_string(maxPotentialThunks) + 188 ", stubs = " + std::to_string(in.stubs->getSize()) + ", isecVA = " + 189 to_hexString(isecVA) + ", threshold = " + to_hexString(stubsInRangeVA) + 190 ", isecEnd = " + to_hexString(isecEnd) + 191 ", tail = " + to_hexString(isecEnd - isecVA) + 192 ", slop = " + to_hexString(forwardBranchRange - (isecEnd - isecVA))); 193 return stubsInRangeVA; 194 } 195 196 void ConcatOutputSection::finalize() { 197 uint64_t isecAddr = addr; 198 uint64_t isecFileOff = fileOff; 199 auto finalizeOne = [&](ConcatInputSection *isec) { 200 isecAddr = alignTo(isecAddr, isec->align); 201 isecFileOff = alignTo(isecFileOff, isec->align); 202 isec->outSecOff = isecAddr - addr; 203 isec->isFinal = true; 204 isecAddr += isec->getSize(); 205 isecFileOff += isec->getFileSize(); 206 }; 207 208 if (!needsThunks()) { 209 for (ConcatInputSection *isec : inputs) 210 finalizeOne(isec); 211 size = isecAddr - addr; 212 fileSize = isecFileOff - fileOff; 213 return; 214 } 215 216 uint64_t forwardBranchRange = target->forwardBranchRange; 217 uint64_t backwardBranchRange = target->backwardBranchRange; 218 uint64_t stubsInRangeVA = TargetInfo::outOfRangeVA; 219 size_t thunkSize = target->thunkSize; 220 size_t relocCount = 0; 221 size_t callSiteCount = 0; 222 size_t thunkCallCount = 0; 223 size_t thunkCount = 0; 224 225 // Walk all sections in order. Finalize all sections that are less than 226 // forwardBranchRange in front of it. 227 // isecVA is the address of the current section. 228 // isecAddr is the start address of the first non-finalized section. 229 230 // inputs[finalIdx] is for finalization (address-assignment) 231 size_t finalIdx = 0; 232 // Kick-off by ensuring that the first input section has an address 233 for (size_t callIdx = 0, endIdx = inputs.size(); callIdx < endIdx; 234 ++callIdx) { 235 if (finalIdx == callIdx) 236 finalizeOne(inputs[finalIdx++]); 237 ConcatInputSection *isec = inputs[callIdx]; 238 assert(isec->isFinal); 239 uint64_t isecVA = isec->getVA(); 240 241 // Assign addresses up-to the forward branch-range limit. 242 // Every call instruction needs a small number of bytes (on Arm64: 4), 243 // and each inserted thunk needs a slightly larger number of bytes 244 // (on Arm64: 12). If a section starts with a branch instruction and 245 // contains several branch instructions in succession, then the distance 246 // from the current position to the position where the thunks are inserted 247 // grows. So leave room for a bunch of thunks. 248 unsigned slop = 100 * thunkSize; 249 while (finalIdx < endIdx && isecAddr + inputs[finalIdx]->getSize() < 250 isecVA + forwardBranchRange - slop) 251 finalizeOne(inputs[finalIdx++]); 252 253 if (isec->callSiteCount == 0) 254 continue; 255 256 if (finalIdx == endIdx && stubsInRangeVA == TargetInfo::outOfRangeVA) { 257 // When we have finalized all input sections, __stubs (destined 258 // to follow __text) comes within range of forward branches and 259 // we can estimate the threshold address after which we can 260 // reach any stub with a forward branch. Note that although it 261 // sits in the middle of a loop, this code executes only once. 262 // It is in the loop because we need to call it at the proper 263 // time: the earliest call site from which the end of __text 264 // (and start of __stubs) comes within range of a forward branch. 265 stubsInRangeVA = estimateStubsInRangeVA(callIdx); 266 } 267 // Process relocs by ascending address, i.e., ascending offset within isec 268 std::vector<Reloc> &relocs = isec->relocs; 269 // FIXME: This property does not hold for object files produced by ld64's 270 // `-r` mode. 271 assert(is_sorted(relocs, 272 [](Reloc &a, Reloc &b) { return a.offset > b.offset; })); 273 for (Reloc &r : reverse(relocs)) { 274 ++relocCount; 275 if (!target->hasAttr(r.type, RelocAttrBits::BRANCH)) 276 continue; 277 ++callSiteCount; 278 // Calculate branch reachability boundaries 279 uint64_t callVA = isecVA + r.offset; 280 uint64_t lowVA = 281 backwardBranchRange < callVA ? callVA - backwardBranchRange : 0; 282 uint64_t highVA = callVA + forwardBranchRange; 283 // Calculate our call referent address 284 auto *funcSym = r.referent.get<Symbol *>(); 285 ThunkInfo &thunkInfo = thunkMap[funcSym]; 286 // The referent is not reachable, so we need to use a thunk ... 287 if (funcSym->isInStubs() && callVA >= stubsInRangeVA) { 288 assert(callVA != TargetInfo::outOfRangeVA); 289 // ... Oh, wait! We are close enough to the end that __stubs 290 // are now within range of a simple forward branch. 291 continue; 292 } 293 uint64_t funcVA = funcSym->resolveBranchVA(); 294 ++thunkInfo.callSitesUsed; 295 if (lowVA <= funcVA && funcVA <= highVA) { 296 // The referent is reachable with a simple call instruction. 297 continue; 298 } 299 ++thunkInfo.thunkCallCount; 300 ++thunkCallCount; 301 // If an existing thunk is reachable, use it ... 302 if (thunkInfo.sym) { 303 uint64_t thunkVA = thunkInfo.isec->getVA(); 304 if (lowVA <= thunkVA && thunkVA <= highVA) { 305 r.referent = thunkInfo.sym; 306 continue; 307 } 308 } 309 // ... otherwise, create a new thunk. 310 if (isecAddr > highVA) { 311 // There were too many consecutive branch instructions for `slop` 312 // above. If you hit this: For the current algorithm, just bumping up 313 // slop above and trying again is probably simplest. (See also PR51578 314 // comment 5). 315 fatal(Twine(__FUNCTION__) + ": FIXME: thunk range overrun"); 316 } 317 thunkInfo.isec = 318 make<ConcatInputSection>(isec->getSegName(), isec->getName()); 319 thunkInfo.isec->parent = this; 320 321 // This code runs after dead code removal. Need to set the `live` bit 322 // on the thunk isec so that asserts that check that only live sections 323 // get written are happy. 324 thunkInfo.isec->live = true; 325 326 StringRef thunkName = saver.save(funcSym->getName() + ".thunk." + 327 std::to_string(thunkInfo.sequence++)); 328 r.referent = thunkInfo.sym = symtab->addDefined( 329 thunkName, /*file=*/nullptr, thunkInfo.isec, /*value=*/0, 330 /*size=*/thunkSize, /*isWeakDef=*/false, /*isPrivateExtern=*/true, 331 /*isThumb=*/false, /*isReferencedDynamically=*/false, 332 /*noDeadStrip=*/false); 333 thunkInfo.sym->used = true; 334 target->populateThunk(thunkInfo.isec, funcSym); 335 finalizeOne(thunkInfo.isec); 336 thunks.push_back(thunkInfo.isec); 337 ++thunkCount; 338 } 339 } 340 size = isecAddr - addr; 341 fileSize = isecFileOff - fileOff; 342 343 log("thunks for " + parent->name + "," + name + 344 ": funcs = " + std::to_string(thunkMap.size()) + 345 ", relocs = " + std::to_string(relocCount) + 346 ", all calls = " + std::to_string(callSiteCount) + 347 ", thunk calls = " + std::to_string(thunkCallCount) + 348 ", thunks = " + std::to_string(thunkCount)); 349 } 350 351 void ConcatOutputSection::writeTo(uint8_t *buf) const { 352 // Merge input sections from thunk & ordinary vectors 353 size_t i = 0, ie = inputs.size(); 354 size_t t = 0, te = thunks.size(); 355 while (i < ie || t < te) { 356 while (i < ie && (t == te || inputs[i]->empty() || 357 inputs[i]->outSecOff < thunks[t]->outSecOff)) { 358 inputs[i]->writeTo(buf + inputs[i]->outSecOff); 359 ++i; 360 } 361 while (t < te && (i == ie || thunks[t]->outSecOff < inputs[i]->outSecOff)) { 362 thunks[t]->writeTo(buf + thunks[t]->outSecOff); 363 ++t; 364 } 365 } 366 } 367 368 void ConcatOutputSection::finalizeFlags(InputSection *input) { 369 switch (sectionType(input->getFlags())) { 370 default /*type-unspec'ed*/: 371 // FIXME: Add additional logic here when supporting emitting obj files. 372 break; 373 case S_4BYTE_LITERALS: 374 case S_8BYTE_LITERALS: 375 case S_16BYTE_LITERALS: 376 case S_CSTRING_LITERALS: 377 case S_ZEROFILL: 378 case S_LAZY_SYMBOL_POINTERS: 379 case S_MOD_TERM_FUNC_POINTERS: 380 case S_THREAD_LOCAL_REGULAR: 381 case S_THREAD_LOCAL_ZEROFILL: 382 case S_THREAD_LOCAL_VARIABLES: 383 case S_THREAD_LOCAL_INIT_FUNCTION_POINTERS: 384 case S_THREAD_LOCAL_VARIABLE_POINTERS: 385 case S_NON_LAZY_SYMBOL_POINTERS: 386 case S_SYMBOL_STUBS: 387 flags |= input->getFlags(); 388 break; 389 } 390 } 391 392 ConcatOutputSection * 393 ConcatOutputSection::getOrCreateForInput(const InputSection *isec) { 394 NamePair names = maybeRenameSection({isec->getSegName(), isec->getName()}); 395 ConcatOutputSection *&osec = concatOutputSections[names]; 396 if (!osec) 397 osec = make<ConcatOutputSection>(names.second); 398 return osec; 399 } 400 401 NamePair macho::maybeRenameSection(NamePair key) { 402 auto newNames = config->sectionRenameMap.find(key); 403 if (newNames != config->sectionRenameMap.end()) 404 return newNames->second; 405 return key; 406 } 407