1 //===- UnwindInfoSection.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 "UnwindInfoSection.h" 10 #include "ConcatOutputSection.h" 11 #include "Config.h" 12 #include "InputSection.h" 13 #include "OutputSection.h" 14 #include "OutputSegment.h" 15 #include "SymbolTable.h" 16 #include "Symbols.h" 17 #include "SyntheticSections.h" 18 #include "Target.h" 19 20 #include "lld/Common/ErrorHandler.h" 21 #include "lld/Common/Memory.h" 22 #include "llvm/ADT/DenseMap.h" 23 #include "llvm/ADT/STLExtras.h" 24 #include "llvm/BinaryFormat/MachO.h" 25 #include "llvm/Support/Parallel.h" 26 27 #include <numeric> 28 29 using namespace llvm; 30 using namespace llvm::MachO; 31 using namespace lld; 32 using namespace lld::macho; 33 34 #define COMMON_ENCODINGS_MAX 127 35 #define COMPACT_ENCODINGS_MAX 256 36 37 #define SECOND_LEVEL_PAGE_BYTES 4096 38 #define SECOND_LEVEL_PAGE_WORDS (SECOND_LEVEL_PAGE_BYTES / sizeof(uint32_t)) 39 #define REGULAR_SECOND_LEVEL_ENTRIES_MAX \ 40 ((SECOND_LEVEL_PAGE_BYTES - \ 41 sizeof(unwind_info_regular_second_level_page_header)) / \ 42 sizeof(unwind_info_regular_second_level_entry)) 43 #define COMPRESSED_SECOND_LEVEL_ENTRIES_MAX \ 44 ((SECOND_LEVEL_PAGE_BYTES - \ 45 sizeof(unwind_info_compressed_second_level_page_header)) / \ 46 sizeof(uint32_t)) 47 48 #define COMPRESSED_ENTRY_FUNC_OFFSET_BITS 24 49 #define COMPRESSED_ENTRY_FUNC_OFFSET_MASK \ 50 UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(~0) 51 52 // Compact Unwind format is a Mach-O evolution of DWARF Unwind that 53 // optimizes space and exception-time lookup. Most DWARF unwind 54 // entries can be replaced with Compact Unwind entries, but the ones 55 // that cannot are retained in DWARF form. 56 // 57 // This comment will address macro-level organization of the pre-link 58 // and post-link compact unwind tables. For micro-level organization 59 // pertaining to the bitfield layout of the 32-bit compact unwind 60 // entries, see libunwind/include/mach-o/compact_unwind_encoding.h 61 // 62 // Important clarifying factoids: 63 // 64 // * __LD,__compact_unwind is the compact unwind format for compiler 65 // output and linker input. It is never a final output. It could be 66 // an intermediate output with the `-r` option which retains relocs. 67 // 68 // * __TEXT,__unwind_info is the compact unwind format for final 69 // linker output. It is never an input. 70 // 71 // * __TEXT,__eh_frame is the DWARF format for both linker input and output. 72 // 73 // * __TEXT,__unwind_info entries are divided into 4 KiB pages (2nd 74 // level) by ascending address, and the pages are referenced by an 75 // index (1st level) in the section header. 76 // 77 // * Following the headers in __TEXT,__unwind_info, the bulk of the 78 // section contains a vector of compact unwind entries 79 // `{functionOffset, encoding}` sorted by ascending `functionOffset`. 80 // Adjacent entries with the same encoding can be folded to great 81 // advantage, achieving a 3-order-of-magnitude reduction in the 82 // number of entries. 83 // 84 // * The __TEXT,__unwind_info format can accommodate up to 127 unique 85 // encodings for the space-efficient compressed format. In practice, 86 // fewer than a dozen unique encodings are used by C++ programs of 87 // all sizes. Therefore, we don't even bother implementing the regular 88 // non-compressed format. Time will tell if anyone in the field ever 89 // overflows the 127-encodings limit. 90 // 91 // Refer to the definition of unwind_info_section_header in 92 // compact_unwind_encoding.h for an overview of the format we are encoding 93 // here. 94 95 // TODO(gkm): prune __eh_frame entries superseded by __unwind_info, PR50410 96 // TODO(gkm): how do we align the 2nd-level pages? 97 98 template <class Ptr> struct CompactUnwindLayout { 99 Ptr functionAddress; 100 uint32_t functionLength; 101 compact_unwind_encoding_t encoding; 102 Ptr personality; 103 Ptr lsda; 104 }; 105 106 struct CompactUnwindEntry { 107 uint64_t functionAddress; 108 uint32_t functionLength; 109 compact_unwind_encoding_t encoding; 110 Symbol *personality; 111 InputSection *lsda; 112 }; 113 114 using EncodingMap = DenseMap<compact_unwind_encoding_t, size_t>; 115 116 struct SecondLevelPage { 117 uint32_t kind; 118 size_t entryIndex; 119 size_t entryCount; 120 size_t byteCount; 121 std::vector<compact_unwind_encoding_t> localEncodings; 122 EncodingMap localEncodingIndexes; 123 }; 124 125 template <class Ptr> 126 class UnwindInfoSectionImpl final : public UnwindInfoSection { 127 public: 128 void prepareRelocations(ConcatInputSection *) override; 129 void relocateCompactUnwind(std::vector<CompactUnwindEntry> &); 130 void encodePersonalities(); 131 void finalize() override; 132 void writeTo(uint8_t *buf) const override; 133 134 private: 135 std::vector<std::pair<compact_unwind_encoding_t, size_t>> commonEncodings; 136 EncodingMap commonEncodingIndexes; 137 // The entries here will be in the same order as their originating symbols 138 // in symbolsVec. 139 std::vector<CompactUnwindEntry> cuEntries; 140 // Indices into the cuEntries vector. 141 std::vector<size_t> cuIndices; 142 std::vector<Symbol *> personalities; 143 SmallDenseMap<std::pair<InputSection *, uint64_t /* addend */>, Symbol *> 144 personalityTable; 145 // Indices into cuEntries for CUEs with a non-null LSDA. 146 std::vector<size_t> entriesWithLsda; 147 // Map of cuEntries index to an index within the LSDA array. 148 DenseMap<size_t, uint32_t> lsdaIndex; 149 std::vector<SecondLevelPage> secondLevelPages; 150 uint64_t level2PagesOffset = 0; 151 }; 152 153 UnwindInfoSection::UnwindInfoSection() 154 : SyntheticSection(segment_names::text, section_names::unwindInfo) { 155 align = 4; 156 } 157 158 void UnwindInfoSection::prepareRelocations() { 159 // This iteration needs to be deterministic, since prepareRelocations may add 160 // entries to the GOT. Hence the use of a MapVector for 161 // UnwindInfoSection::symbols. 162 for (const Defined *d : make_second_range(symbols)) 163 if (d->unwindEntry) 164 prepareRelocations(d->unwindEntry); 165 } 166 167 // Record function symbols that may need entries emitted in __unwind_info, which 168 // stores unwind data for address ranges. 169 // 170 // Note that if several adjacent functions have the same unwind encoding, LSDA, 171 // and personality function, they share one unwind entry. For this to work, 172 // functions without unwind info need explicit "no unwind info" unwind entries 173 // -- else the unwinder would think they have the unwind info of the closest 174 // function with unwind info right before in the image. Thus, we add function 175 // symbols for each unique address regardless of whether they have associated 176 // unwind info. 177 void UnwindInfoSection::addSymbol(const Defined *d) { 178 if (d->unwindEntry) 179 allEntriesAreOmitted = false; 180 // We don't yet know the final output address of this symbol, but we know that 181 // they are uniquely determined by a combination of the isec and value, so 182 // we use that as the key here. 183 auto p = symbols.insert({{d->isec, d->value}, d}); 184 // If we have multiple symbols at the same address, only one of them can have 185 // an associated CUE. 186 if (!p.second && d->unwindEntry) { 187 assert(!p.first->second->unwindEntry); 188 p.first->second = d; 189 } 190 } 191 192 // Compact unwind relocations have different semantics, so we handle them in a 193 // separate code path from regular relocations. First, we do not wish to add 194 // rebase opcodes for __LD,__compact_unwind, because that section doesn't 195 // actually end up in the final binary. Second, personality pointers always 196 // reside in the GOT and must be treated specially. 197 template <class Ptr> 198 void UnwindInfoSectionImpl<Ptr>::prepareRelocations(ConcatInputSection *isec) { 199 assert(!isec->shouldOmitFromOutput() && 200 "__compact_unwind section should not be omitted"); 201 202 // FIXME: Make this skip relocations for CompactUnwindEntries that 203 // point to dead-stripped functions. That might save some amount of 204 // work. But since there are usually just few personality functions 205 // that are referenced from many places, at least some of them likely 206 // live, it wouldn't reduce number of got entries. 207 for (size_t i = 0; i < isec->relocs.size(); ++i) { 208 Reloc &r = isec->relocs[i]; 209 assert(target->hasAttr(r.type, RelocAttrBits::UNSIGNED)); 210 211 // Functions and LSDA entries always reside in the same object file as the 212 // compact unwind entries that references them, and thus appear as section 213 // relocs. There is no need to prepare them. We only prepare relocs for 214 // personality functions. 215 if (r.offset != offsetof(CompactUnwindLayout<Ptr>, personality)) 216 continue; 217 218 if (auto *s = r.referent.dyn_cast<Symbol *>()) { 219 // Personality functions are nearly always system-defined (e.g., 220 // ___gxx_personality_v0 for C++) and relocated as dylib symbols. When an 221 // application provides its own personality function, it might be 222 // referenced by an extern Defined symbol reloc, or a local section reloc. 223 if (auto *defined = dyn_cast<Defined>(s)) { 224 // XXX(vyng) This is a a special case for handling duplicate personality 225 // symbols. Note that LD64's behavior is a bit different and it is 226 // inconsistent with how symbol resolution usually work 227 // 228 // So we've decided not to follow it. Instead, simply pick the symbol 229 // with the same name from the symbol table to replace the local one. 230 // 231 // (See discussions/alternatives already considered on D107533) 232 if (!defined->isExternal()) 233 if (Symbol *sym = symtab->find(defined->getName())) 234 if (!sym->isLazy()) 235 r.referent = s = sym; 236 } 237 if (auto *undefined = dyn_cast<Undefined>(s)) { 238 treatUndefinedSymbol(*undefined); 239 // treatUndefinedSymbol() can replace s with a DylibSymbol; re-check. 240 if (isa<Undefined>(s)) 241 continue; 242 } 243 244 if (auto *defined = dyn_cast<Defined>(s)) { 245 // Check if we have created a synthetic symbol at the same address. 246 Symbol *&personality = 247 personalityTable[{defined->isec, defined->value}]; 248 if (personality == nullptr) { 249 personality = defined; 250 in.got->addEntry(defined); 251 } else if (personality != defined) { 252 r.referent = personality; 253 } 254 continue; 255 } 256 assert(isa<DylibSymbol>(s)); 257 in.got->addEntry(s); 258 continue; 259 } 260 261 if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) { 262 assert(!isCoalescedWeak(referentIsec)); 263 // Personality functions can be referenced via section relocations 264 // if they live in the same object file. Create placeholder synthetic 265 // symbols for them in the GOT. 266 Symbol *&s = personalityTable[{referentIsec, r.addend}]; 267 if (s == nullptr) { 268 // This runs after dead stripping, so the noDeadStrip argument does not 269 // matter. 270 s = make<Defined>("<internal>", /*file=*/nullptr, referentIsec, 271 r.addend, /*size=*/0, /*isWeakDef=*/false, 272 /*isExternal=*/false, /*isPrivateExtern=*/false, 273 /*isThumb=*/false, /*isReferencedDynamically=*/false, 274 /*noDeadStrip=*/false); 275 in.got->addEntry(s); 276 } 277 r.referent = s; 278 r.addend = 0; 279 } 280 } 281 } 282 283 // We need to apply the relocations to the pre-link compact unwind section 284 // before converting it to post-link form. There should only be absolute 285 // relocations here: since we are not emitting the pre-link CU section, there 286 // is no source address to make a relative location meaningful. 287 template <class Ptr> 288 void UnwindInfoSectionImpl<Ptr>::relocateCompactUnwind( 289 std::vector<CompactUnwindEntry> &cuEntries) { 290 parallelForEachN(0, symbolsVec.size(), [&](size_t i) { 291 CompactUnwindEntry &cu = cuEntries[i]; 292 const Defined *d = symbolsVec[i].second; 293 cu.functionAddress = d->getVA(); 294 if (!d->unwindEntry) 295 return; 296 297 auto buf = reinterpret_cast<const uint8_t *>(d->unwindEntry->data.data()) - 298 sizeof(Ptr); 299 cu.functionLength = support::endian::read32le( 300 buf + offsetof(CompactUnwindLayout<Ptr>, functionLength)); 301 cu.encoding = support::endian::read32le( 302 buf + offsetof(CompactUnwindLayout<Ptr>, encoding)); 303 for (const Reloc &r : d->unwindEntry->relocs) { 304 if (r.offset == offsetof(CompactUnwindLayout<Ptr>, personality)) { 305 cu.personality = r.referent.get<Symbol *>(); 306 } else if (r.offset == offsetof(CompactUnwindLayout<Ptr>, lsda)) { 307 if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) 308 cu.lsda = cast<Defined>(referentSym)->isec; 309 else 310 cu.lsda = r.referent.get<InputSection *>(); 311 } 312 } 313 }); 314 } 315 316 // There should only be a handful of unique personality pointers, so we can 317 // encode them as 2-bit indices into a small array. 318 template <class Ptr> void UnwindInfoSectionImpl<Ptr>::encodePersonalities() { 319 for (size_t idx : cuIndices) { 320 CompactUnwindEntry &cu = cuEntries[idx]; 321 if (cu.personality == nullptr) 322 continue; 323 // Linear search is fast enough for a small array. 324 auto it = find(personalities, cu.personality); 325 uint32_t personalityIndex; // 1-based index 326 if (it != personalities.end()) { 327 personalityIndex = std::distance(personalities.begin(), it) + 1; 328 } else { 329 personalities.push_back(cu.personality); 330 personalityIndex = personalities.size(); 331 } 332 cu.encoding |= 333 personalityIndex << countTrailingZeros( 334 static_cast<compact_unwind_encoding_t>(UNWIND_PERSONALITY_MASK)); 335 } 336 if (personalities.size() > 3) 337 error("too many personalities (" + Twine(personalities.size()) + 338 ") for compact unwind to encode"); 339 } 340 341 static bool canFoldEncoding(compact_unwind_encoding_t encoding) { 342 // From compact_unwind_encoding.h: 343 // UNWIND_X86_64_MODE_STACK_IND: 344 // A "frameless" (RBP not used as frame pointer) function large constant 345 // stack size. This case is like the previous, except the stack size is too 346 // large to encode in the compact unwind encoding. Instead it requires that 347 // the function contains "subq $nnnnnnnn,RSP" in its prolog. The compact 348 // encoding contains the offset to the nnnnnnnn value in the function in 349 // UNWIND_X86_64_FRAMELESS_STACK_SIZE. 350 // Since this means the unwinder has to look at the `subq` in the function 351 // of the unwind info's unwind address, two functions that have identical 352 // unwind info can't be folded if it's using this encoding since both 353 // entries need unique addresses. 354 static_assert(UNWIND_X86_64_MODE_MASK == UNWIND_X86_MODE_MASK, ""); 355 static_assert(UNWIND_X86_64_MODE_STACK_IND == UNWIND_X86_MODE_STACK_IND, ""); 356 if ((target->cpuType == CPU_TYPE_X86_64 || target->cpuType == CPU_TYPE_X86) && 357 (encoding & UNWIND_X86_64_MODE_MASK) == UNWIND_X86_64_MODE_STACK_IND) { 358 // FIXME: Consider passing in the two function addresses and getting 359 // their two stack sizes off the `subq` and only returning false if they're 360 // actually different. 361 return false; 362 } 363 return true; 364 } 365 366 // Scan the __LD,__compact_unwind entries and compute the space needs of 367 // __TEXT,__unwind_info and __TEXT,__eh_frame. 368 template <class Ptr> void UnwindInfoSectionImpl<Ptr>::finalize() { 369 if (symbols.empty()) 370 return; 371 372 // At this point, the address space for __TEXT,__text has been 373 // assigned, so we can relocate the __LD,__compact_unwind entries 374 // into a temporary buffer. Relocation is necessary in order to sort 375 // the CU entries by function address. Sorting is necessary so that 376 // we can fold adjacent CU entries with identical 377 // encoding+personality+lsda. Folding is necessary because it reduces 378 // the number of CU entries by as much as 3 orders of magnitude! 379 cuEntries.resize(symbols.size()); 380 // The "map" part of the symbols MapVector was only needed for deduplication 381 // in addSymbol(). Now that we are done adding, move the contents to a plain 382 // std::vector for indexed access. 383 symbolsVec = symbols.takeVector(); 384 relocateCompactUnwind(cuEntries); 385 386 // Rather than sort & fold the 32-byte entries directly, we create a 387 // vector of indices to entries and sort & fold that instead. 388 cuIndices.resize(cuEntries.size()); 389 std::iota(cuIndices.begin(), cuIndices.end(), 0); 390 llvm::sort(cuIndices, [&](size_t a, size_t b) { 391 return cuEntries[a].functionAddress < cuEntries[b].functionAddress; 392 }); 393 394 // Fold adjacent entries with matching encoding+personality+lsda 395 // We use three iterators on the same cuIndices to fold in-situ: 396 // (1) `foldBegin` is the first of a potential sequence of matching entries 397 // (2) `foldEnd` is the first non-matching entry after `foldBegin`. 398 // The semi-open interval [ foldBegin .. foldEnd ) contains a range 399 // entries that can be folded into a single entry and written to ... 400 // (3) `foldWrite` 401 auto foldWrite = cuIndices.begin(); 402 for (auto foldBegin = cuIndices.begin(); foldBegin < cuIndices.end();) { 403 auto foldEnd = foldBegin; 404 while (++foldEnd < cuIndices.end() && 405 cuEntries[*foldBegin].encoding == cuEntries[*foldEnd].encoding && 406 cuEntries[*foldBegin].personality == 407 cuEntries[*foldEnd].personality && 408 cuEntries[*foldBegin].lsda == cuEntries[*foldEnd].lsda && 409 canFoldEncoding(cuEntries[*foldEnd].encoding)) 410 ; 411 *foldWrite++ = *foldBegin; 412 foldBegin = foldEnd; 413 } 414 cuIndices.erase(foldWrite, cuIndices.end()); 415 416 encodePersonalities(); 417 418 // Count frequencies of the folded encodings 419 EncodingMap encodingFrequencies; 420 for (size_t idx : cuIndices) 421 encodingFrequencies[cuEntries[idx].encoding]++; 422 423 // Make a vector of encodings, sorted by descending frequency 424 for (const auto &frequency : encodingFrequencies) 425 commonEncodings.emplace_back(frequency); 426 llvm::sort(commonEncodings, 427 [](const std::pair<compact_unwind_encoding_t, size_t> &a, 428 const std::pair<compact_unwind_encoding_t, size_t> &b) { 429 if (a.second == b.second) 430 // When frequencies match, secondarily sort on encoding 431 // to maintain parity with validate-unwind-info.py 432 return a.first > b.first; 433 return a.second > b.second; 434 }); 435 436 // Truncate the vector to 127 elements. 437 // Common encoding indexes are limited to 0..126, while encoding 438 // indexes 127..255 are local to each second-level page 439 if (commonEncodings.size() > COMMON_ENCODINGS_MAX) 440 commonEncodings.resize(COMMON_ENCODINGS_MAX); 441 442 // Create a map from encoding to common-encoding-table index 443 for (size_t i = 0; i < commonEncodings.size(); i++) 444 commonEncodingIndexes[commonEncodings[i].first] = i; 445 446 // Split folded encodings into pages, where each page is limited by ... 447 // (a) 4 KiB capacity 448 // (b) 24-bit difference between first & final function address 449 // (c) 8-bit compact-encoding-table index, 450 // for which 0..126 references the global common-encodings table, 451 // and 127..255 references a local per-second-level-page table. 452 // First we try the compact format and determine how many entries fit. 453 // If more entries fit in the regular format, we use that. 454 for (size_t i = 0; i < cuIndices.size();) { 455 size_t idx = cuIndices[i]; 456 secondLevelPages.emplace_back(); 457 SecondLevelPage &page = secondLevelPages.back(); 458 page.entryIndex = i; 459 uintptr_t functionAddressMax = 460 cuEntries[idx].functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK; 461 size_t n = commonEncodings.size(); 462 size_t wordsRemaining = 463 SECOND_LEVEL_PAGE_WORDS - 464 sizeof(unwind_info_compressed_second_level_page_header) / 465 sizeof(uint32_t); 466 while (wordsRemaining >= 1 && i < cuIndices.size()) { 467 idx = cuIndices[i]; 468 const CompactUnwindEntry *cuPtr = &cuEntries[idx]; 469 if (cuPtr->functionAddress >= functionAddressMax) { 470 break; 471 } else if (commonEncodingIndexes.count(cuPtr->encoding) || 472 page.localEncodingIndexes.count(cuPtr->encoding)) { 473 i++; 474 wordsRemaining--; 475 } else if (wordsRemaining >= 2 && n < COMPACT_ENCODINGS_MAX) { 476 page.localEncodings.emplace_back(cuPtr->encoding); 477 page.localEncodingIndexes[cuPtr->encoding] = n++; 478 i++; 479 wordsRemaining -= 2; 480 } else { 481 break; 482 } 483 } 484 page.entryCount = i - page.entryIndex; 485 486 // If this is not the final page, see if it's possible to fit more 487 // entries by using the regular format. This can happen when there 488 // are many unique encodings, and we we saturated the local 489 // encoding table early. 490 if (i < cuIndices.size() && 491 page.entryCount < REGULAR_SECOND_LEVEL_ENTRIES_MAX) { 492 page.kind = UNWIND_SECOND_LEVEL_REGULAR; 493 page.entryCount = std::min(REGULAR_SECOND_LEVEL_ENTRIES_MAX, 494 cuIndices.size() - page.entryIndex); 495 i = page.entryIndex + page.entryCount; 496 } else { 497 page.kind = UNWIND_SECOND_LEVEL_COMPRESSED; 498 } 499 } 500 501 for (size_t idx : cuIndices) { 502 lsdaIndex[idx] = entriesWithLsda.size(); 503 if (cuEntries[idx].lsda) 504 entriesWithLsda.push_back(idx); 505 } 506 507 // compute size of __TEXT,__unwind_info section 508 level2PagesOffset = sizeof(unwind_info_section_header) + 509 commonEncodings.size() * sizeof(uint32_t) + 510 personalities.size() * sizeof(uint32_t) + 511 // The extra second-level-page entry is for the sentinel 512 (secondLevelPages.size() + 1) * 513 sizeof(unwind_info_section_header_index_entry) + 514 entriesWithLsda.size() * 515 sizeof(unwind_info_section_header_lsda_index_entry); 516 unwindInfoSize = 517 level2PagesOffset + secondLevelPages.size() * SECOND_LEVEL_PAGE_BYTES; 518 } 519 520 // All inputs are relocated and output addresses are known, so write! 521 522 template <class Ptr> 523 void UnwindInfoSectionImpl<Ptr>::writeTo(uint8_t *buf) const { 524 assert(!cuIndices.empty() && "call only if there is unwind info"); 525 526 // section header 527 auto *uip = reinterpret_cast<unwind_info_section_header *>(buf); 528 uip->version = 1; 529 uip->commonEncodingsArraySectionOffset = sizeof(unwind_info_section_header); 530 uip->commonEncodingsArrayCount = commonEncodings.size(); 531 uip->personalityArraySectionOffset = 532 uip->commonEncodingsArraySectionOffset + 533 (uip->commonEncodingsArrayCount * sizeof(uint32_t)); 534 uip->personalityArrayCount = personalities.size(); 535 uip->indexSectionOffset = uip->personalityArraySectionOffset + 536 (uip->personalityArrayCount * sizeof(uint32_t)); 537 uip->indexCount = secondLevelPages.size() + 1; 538 539 // Common encodings 540 auto *i32p = reinterpret_cast<uint32_t *>(&uip[1]); 541 for (const auto &encoding : commonEncodings) 542 *i32p++ = encoding.first; 543 544 // Personalities 545 for (const Symbol *personality : personalities) 546 *i32p++ = personality->getGotVA() - in.header->addr; 547 548 // Level-1 index 549 uint32_t lsdaOffset = 550 uip->indexSectionOffset + 551 uip->indexCount * sizeof(unwind_info_section_header_index_entry); 552 uint64_t l2PagesOffset = level2PagesOffset; 553 auto *iep = reinterpret_cast<unwind_info_section_header_index_entry *>(i32p); 554 for (const SecondLevelPage &page : secondLevelPages) { 555 size_t idx = cuIndices[page.entryIndex]; 556 iep->functionOffset = cuEntries[idx].functionAddress - in.header->addr; 557 iep->secondLevelPagesSectionOffset = l2PagesOffset; 558 iep->lsdaIndexArraySectionOffset = 559 lsdaOffset + lsdaIndex.lookup(idx) * 560 sizeof(unwind_info_section_header_lsda_index_entry); 561 iep++; 562 l2PagesOffset += SECOND_LEVEL_PAGE_BYTES; 563 } 564 // Level-1 sentinel 565 const CompactUnwindEntry &cuEnd = cuEntries[cuIndices.back()]; 566 iep->functionOffset = 567 cuEnd.functionAddress - in.header->addr + cuEnd.functionLength; 568 iep->secondLevelPagesSectionOffset = 0; 569 iep->lsdaIndexArraySectionOffset = 570 lsdaOffset + entriesWithLsda.size() * 571 sizeof(unwind_info_section_header_lsda_index_entry); 572 iep++; 573 574 // LSDAs 575 auto *lep = 576 reinterpret_cast<unwind_info_section_header_lsda_index_entry *>(iep); 577 for (size_t idx : entriesWithLsda) { 578 const CompactUnwindEntry &cu = cuEntries[idx]; 579 lep->lsdaOffset = cu.lsda->getVA(/*off=*/0) - in.header->addr; 580 lep->functionOffset = cu.functionAddress - in.header->addr; 581 lep++; 582 } 583 584 // Level-2 pages 585 auto *pp = reinterpret_cast<uint32_t *>(lep); 586 for (const SecondLevelPage &page : secondLevelPages) { 587 if (page.kind == UNWIND_SECOND_LEVEL_COMPRESSED) { 588 uintptr_t functionAddressBase = 589 cuEntries[cuIndices[page.entryIndex]].functionAddress; 590 auto *p2p = 591 reinterpret_cast<unwind_info_compressed_second_level_page_header *>( 592 pp); 593 p2p->kind = page.kind; 594 p2p->entryPageOffset = 595 sizeof(unwind_info_compressed_second_level_page_header); 596 p2p->entryCount = page.entryCount; 597 p2p->encodingsPageOffset = 598 p2p->entryPageOffset + p2p->entryCount * sizeof(uint32_t); 599 p2p->encodingsCount = page.localEncodings.size(); 600 auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]); 601 for (size_t i = 0; i < page.entryCount; i++) { 602 const CompactUnwindEntry &cue = 603 cuEntries[cuIndices[page.entryIndex + i]]; 604 auto it = commonEncodingIndexes.find(cue.encoding); 605 if (it == commonEncodingIndexes.end()) 606 it = page.localEncodingIndexes.find(cue.encoding); 607 *ep++ = (it->second << COMPRESSED_ENTRY_FUNC_OFFSET_BITS) | 608 (cue.functionAddress - functionAddressBase); 609 } 610 if (!page.localEncodings.empty()) 611 memcpy(ep, page.localEncodings.data(), 612 page.localEncodings.size() * sizeof(uint32_t)); 613 } else { 614 auto *p2p = 615 reinterpret_cast<unwind_info_regular_second_level_page_header *>(pp); 616 p2p->kind = page.kind; 617 p2p->entryPageOffset = 618 sizeof(unwind_info_regular_second_level_page_header); 619 p2p->entryCount = page.entryCount; 620 auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]); 621 for (size_t i = 0; i < page.entryCount; i++) { 622 const CompactUnwindEntry &cue = 623 cuEntries[cuIndices[page.entryIndex + i]]; 624 *ep++ = cue.functionAddress; 625 *ep++ = cue.encoding; 626 } 627 } 628 pp += SECOND_LEVEL_PAGE_WORDS; 629 } 630 } 631 632 UnwindInfoSection *macho::makeUnwindInfoSection() { 633 if (target->wordSize == 8) 634 return make<UnwindInfoSectionImpl<uint64_t>>(); 635 else 636 return make<UnwindInfoSectionImpl<uint32_t>>(); 637 } 638