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 "Config.h" 11 #include "InputSection.h" 12 #include "MergedOutputSection.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/SmallVector.h" 23 #include "llvm/BinaryFormat/MachO.h" 24 25 using namespace llvm; 26 using namespace llvm::MachO; 27 using namespace lld; 28 using namespace lld::macho; 29 30 #define COMMON_ENCODINGS_MAX 127 31 #define COMPACT_ENCODINGS_MAX 256 32 33 #define SECOND_LEVEL_PAGE_BYTES 4096 34 #define SECOND_LEVEL_PAGE_WORDS (SECOND_LEVEL_PAGE_BYTES / sizeof(uint32_t)) 35 #define REGULAR_SECOND_LEVEL_ENTRIES_MAX \ 36 ((SECOND_LEVEL_PAGE_BYTES - \ 37 sizeof(unwind_info_regular_second_level_page_header)) / \ 38 sizeof(unwind_info_regular_second_level_entry)) 39 #define COMPRESSED_SECOND_LEVEL_ENTRIES_MAX \ 40 ((SECOND_LEVEL_PAGE_BYTES - \ 41 sizeof(unwind_info_compressed_second_level_page_header)) / \ 42 sizeof(uint32_t)) 43 44 #define COMPRESSED_ENTRY_FUNC_OFFSET_BITS 24 45 #define COMPRESSED_ENTRY_FUNC_OFFSET_MASK \ 46 UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(~0) 47 48 // Compact Unwind format is a Mach-O evolution of DWARF Unwind that 49 // optimizes space and exception-time lookup. Most DWARF unwind 50 // entries can be replaced with Compact Unwind entries, but the ones 51 // that cannot are retained in DWARF form. 52 // 53 // This comment will address macro-level organization of the pre-link 54 // and post-link compact unwind tables. For micro-level organization 55 // pertaining to the bitfield layout of the 32-bit compact unwind 56 // entries, see libunwind/include/mach-o/compact_unwind_encoding.h 57 // 58 // Important clarifying factoids: 59 // 60 // * __LD,__compact_unwind is the compact unwind format for compiler 61 // output and linker input. It is never a final output. It could be 62 // an intermediate output with the `-r` option which retains relocs. 63 // 64 // * __TEXT,__unwind_info is the compact unwind format for final 65 // linker output. It is never an input. 66 // 67 // * __TEXT,__eh_frame is the DWARF format for both linker input and output. 68 // 69 // * __TEXT,__unwind_info entries are divided into 4 KiB pages (2nd 70 // level) by ascending address, and the pages are referenced by an 71 // index (1st level) in the section header. 72 // 73 // * Following the headers in __TEXT,__unwind_info, the bulk of the 74 // section contains a vector of compact unwind entries 75 // `{functionOffset, encoding}` sorted by ascending `functionOffset`. 76 // Adjacent entries with the same encoding can be folded to great 77 // advantage, achieving a 3-order-of-magnitude reduction in the 78 // number of entries. 79 // 80 // * The __TEXT,__unwind_info format can accommodate up to 127 unique 81 // encodings for the space-efficient compressed format. In practice, 82 // fewer than a dozen unique encodings are used by C++ programs of 83 // all sizes. Therefore, we don't even bother implementing the regular 84 // non-compressed format. Time will tell if anyone in the field ever 85 // overflows the 127-encodings limit. 86 // 87 // Refer to the definition of unwind_info_section_header in 88 // compact_unwind_encoding.h for an overview of the format we are encoding 89 // here. 90 91 // TODO(gkm): prune __eh_frame entries superseded by __unwind_info 92 // TODO(gkm): how do we align the 2nd-level pages? 93 94 using EncodingMap = llvm::DenseMap<compact_unwind_encoding_t, size_t>; 95 96 template <class Ptr> struct CompactUnwindEntry { 97 Ptr functionAddress; 98 uint32_t functionLength; 99 compact_unwind_encoding_t encoding; 100 Ptr personality; 101 Ptr lsda; 102 }; 103 104 struct SecondLevelPage { 105 uint32_t kind; 106 size_t entryIndex; 107 size_t entryCount; 108 size_t byteCount; 109 std::vector<compact_unwind_encoding_t> localEncodings; 110 EncodingMap localEncodingIndexes; 111 }; 112 113 template <class Ptr> class UnwindInfoSectionImpl : public UnwindInfoSection { 114 public: 115 void prepareRelocations(InputSection *) override; 116 void finalize() override; 117 void writeTo(uint8_t *buf) const override; 118 119 private: 120 std::vector<std::pair<compact_unwind_encoding_t, size_t>> commonEncodings; 121 EncodingMap commonEncodingIndexes; 122 // Indices of personality functions within the GOT. 123 std::vector<uint32_t> personalities; 124 SmallDenseMap<std::pair<InputSection *, uint64_t /* addend */>, Symbol *> 125 personalityTable; 126 std::vector<unwind_info_section_header_lsda_index_entry> lsdaEntries; 127 // Map of function offset (from the image base) to an index within the LSDA 128 // array. 129 llvm::DenseMap<uint32_t, uint32_t> functionToLsdaIndex; 130 std::vector<CompactUnwindEntry<Ptr>> cuVector; 131 std::vector<CompactUnwindEntry<Ptr> *> cuPtrVector; 132 std::vector<SecondLevelPage> secondLevelPages; 133 uint64_t level2PagesOffset = 0; 134 }; 135 136 // Compact unwind relocations have different semantics, so we handle them in a 137 // separate code path from regular relocations. First, we do not wish to add 138 // rebase opcodes for __LD,__compact_unwind, because that section doesn't 139 // actually end up in the final binary. Second, personality pointers always 140 // reside in the GOT and must be treated specially. 141 template <class Ptr> 142 void UnwindInfoSectionImpl<Ptr>::prepareRelocations(InputSection *isec) { 143 assert(isec->segname == segment_names::ld && 144 isec->name == section_names::compactUnwind); 145 146 for (Reloc &r : isec->relocs) { 147 assert(target->hasAttr(r.type, RelocAttrBits::UNSIGNED)); 148 if (r.offset % sizeof(CompactUnwindEntry<Ptr>) != 149 offsetof(CompactUnwindEntry<Ptr>, personality)) 150 continue; 151 152 if (auto *s = r.referent.dyn_cast<Symbol *>()) { 153 if (auto *undefined = dyn_cast<Undefined>(s)) { 154 treatUndefinedSymbol(*undefined); 155 // treatUndefinedSymbol() can replace s with a DylibSymbol; re-check. 156 if (isa<Undefined>(s)) 157 continue; 158 } 159 if (auto *defined = dyn_cast<Defined>(s)) { 160 // Check if we have created a synthetic symbol at the same address. 161 Symbol *&personality = 162 personalityTable[{defined->isec, defined->value}]; 163 if (personality == nullptr) { 164 personality = defined; 165 in.got->addEntry(defined); 166 } else if (personality != defined) { 167 r.referent = personality; 168 } 169 continue; 170 } 171 assert(isa<DylibSymbol>(s)); 172 in.got->addEntry(s); 173 continue; 174 } 175 176 if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) { 177 // Personality functions can be referenced via section relocations 178 // if they live in the same object file. Create placeholder synthetic 179 // symbols for them in the GOT. 180 Symbol *&s = personalityTable[{referentIsec, r.addend}]; 181 if (s == nullptr) { 182 s = make<Defined>("<internal>", nullptr, referentIsec, r.addend, 0, 183 false, false, false); 184 in.got->addEntry(s); 185 } 186 r.referent = s; 187 r.addend = 0; 188 } 189 } 190 } 191 192 // Unwind info lives in __DATA, and finalization of __TEXT will occur before 193 // finalization of __DATA. Moreover, the finalization of unwind info depends on 194 // the exact addresses that it references. So it is safe for compact unwind to 195 // reference addresses in __TEXT, but not addresses in any other segment. 196 static void checkTextSegment(InputSection *isec) { 197 if (isec->segname != segment_names::text) 198 error("compact unwind references address in " + toString(isec) + 199 " which is not in segment __TEXT"); 200 } 201 202 // We need to apply the relocations to the pre-link compact unwind section 203 // before converting it to post-link form. There should only be absolute 204 // relocations here: since we are not emitting the pre-link CU section, there 205 // is no source address to make a relative location meaningful. 206 template <class Ptr> 207 static void 208 relocateCompactUnwind(MergedOutputSection *compactUnwindSection, 209 std::vector<CompactUnwindEntry<Ptr>> &cuVector) { 210 for (const InputSection *isec : compactUnwindSection->inputs) { 211 uint8_t *buf = 212 reinterpret_cast<uint8_t *>(cuVector.data()) + isec->outSecFileOff; 213 memcpy(buf, isec->data.data(), isec->data.size()); 214 215 for (const Reloc &r : isec->relocs) { 216 uint64_t referentVA = 0; 217 if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) { 218 if (!isa<Undefined>(referentSym)) { 219 assert(referentSym->isInGot()); 220 if (auto *defined = dyn_cast<Defined>(referentSym)) 221 checkTextSegment(defined->isec); 222 // At this point in the link, we may not yet know the final address of 223 // the GOT, so we just encode the index. We make it a 1-based index so 224 // that we can distinguish the null pointer case. 225 referentVA = referentSym->gotIndex + 1; 226 } 227 } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) { 228 checkTextSegment(referentIsec); 229 referentVA = referentIsec->getVA() + r.addend; 230 } 231 232 writeAddress(buf + r.offset, referentVA, r.length); 233 } 234 } 235 } 236 237 // There should only be a handful of unique personality pointers, so we can 238 // encode them as 2-bit indices into a small array. 239 template <class Ptr> 240 void encodePersonalities( 241 const std::vector<CompactUnwindEntry<Ptr> *> &cuPtrVector, 242 std::vector<uint32_t> &personalities) { 243 for (CompactUnwindEntry<Ptr> *cu : cuPtrVector) { 244 if (cu->personality == 0) 245 continue; 246 // Linear search is fast enough for a small array. 247 auto it = find(personalities, cu->personality); 248 uint32_t personalityIndex; // 1-based index 249 if (it != personalities.end()) { 250 personalityIndex = std::distance(personalities.begin(), it) + 1; 251 } else { 252 personalities.push_back(cu->personality); 253 personalityIndex = personalities.size(); 254 } 255 cu->encoding |= 256 personalityIndex << countTrailingZeros( 257 static_cast<compact_unwind_encoding_t>(UNWIND_PERSONALITY_MASK)); 258 } 259 if (personalities.size() > 3) 260 error("too many personalities (" + std::to_string(personalities.size()) + 261 ") for compact unwind to encode"); 262 } 263 264 // Scan the __LD,__compact_unwind entries and compute the space needs of 265 // __TEXT,__unwind_info and __TEXT,__eh_frame 266 template <class Ptr> void UnwindInfoSectionImpl<Ptr>::finalize() { 267 if (compactUnwindSection == nullptr) 268 return; 269 270 // At this point, the address space for __TEXT,__text has been 271 // assigned, so we can relocate the __LD,__compact_unwind entries 272 // into a temporary buffer. Relocation is necessary in order to sort 273 // the CU entries by function address. Sorting is necessary so that 274 // we can fold adjacent CU entries with identical 275 // encoding+personality+lsda. Folding is necessary because it reduces 276 // the number of CU entries by as much as 3 orders of magnitude! 277 compactUnwindSection->finalize(); 278 assert(compactUnwindSection->getSize() % sizeof(CompactUnwindEntry<Ptr>) == 279 0); 280 size_t cuCount = 281 compactUnwindSection->getSize() / sizeof(CompactUnwindEntry<Ptr>); 282 cuVector.resize(cuCount); 283 relocateCompactUnwind(compactUnwindSection, cuVector); 284 285 // Rather than sort & fold the 32-byte entries directly, we create a 286 // vector of pointers to entries and sort & fold that instead. 287 cuPtrVector.reserve(cuCount); 288 for (CompactUnwindEntry<Ptr> &cuEntry : cuVector) 289 cuPtrVector.emplace_back(&cuEntry); 290 std::sort( 291 cuPtrVector.begin(), cuPtrVector.end(), 292 [](const CompactUnwindEntry<Ptr> *a, const CompactUnwindEntry<Ptr> *b) { 293 return a->functionAddress < b->functionAddress; 294 }); 295 296 // Fold adjacent entries with matching encoding+personality+lsda 297 // We use three iterators on the same cuPtrVector to fold in-situ: 298 // (1) `foldBegin` is the first of a potential sequence of matching entries 299 // (2) `foldEnd` is the first non-matching entry after `foldBegin`. 300 // The semi-open interval [ foldBegin .. foldEnd ) contains a range 301 // entries that can be folded into a single entry and written to ... 302 // (3) `foldWrite` 303 auto foldWrite = cuPtrVector.begin(); 304 for (auto foldBegin = cuPtrVector.begin(); foldBegin < cuPtrVector.end();) { 305 auto foldEnd = foldBegin; 306 while (++foldEnd < cuPtrVector.end() && 307 (*foldBegin)->encoding == (*foldEnd)->encoding && 308 (*foldBegin)->personality == (*foldEnd)->personality && 309 (*foldBegin)->lsda == (*foldEnd)->lsda) 310 ; 311 *foldWrite++ = *foldBegin; 312 foldBegin = foldEnd; 313 } 314 cuPtrVector.erase(foldWrite, cuPtrVector.end()); 315 316 encodePersonalities(cuPtrVector, personalities); 317 318 // Count frequencies of the folded encodings 319 EncodingMap encodingFrequencies; 320 for (const CompactUnwindEntry<Ptr> *cuPtrEntry : cuPtrVector) 321 encodingFrequencies[cuPtrEntry->encoding]++; 322 323 // Make a vector of encodings, sorted by descending frequency 324 for (const auto &frequency : encodingFrequencies) 325 commonEncodings.emplace_back(frequency); 326 std::sort(commonEncodings.begin(), commonEncodings.end(), 327 [](const std::pair<compact_unwind_encoding_t, size_t> &a, 328 const std::pair<compact_unwind_encoding_t, size_t> &b) { 329 if (a.second == b.second) 330 // When frequencies match, secondarily sort on encoding 331 // to maintain parity with validate-unwind-info.py 332 return a.first > b.first; 333 return a.second > b.second; 334 }); 335 336 // Truncate the vector to 127 elements. 337 // Common encoding indexes are limited to 0..126, while encoding 338 // indexes 127..255 are local to each second-level page 339 if (commonEncodings.size() > COMMON_ENCODINGS_MAX) 340 commonEncodings.resize(COMMON_ENCODINGS_MAX); 341 342 // Create a map from encoding to common-encoding-table index 343 for (size_t i = 0; i < commonEncodings.size(); i++) 344 commonEncodingIndexes[commonEncodings[i].first] = i; 345 346 // Split folded encodings into pages, where each page is limited by ... 347 // (a) 4 KiB capacity 348 // (b) 24-bit difference between first & final function address 349 // (c) 8-bit compact-encoding-table index, 350 // for which 0..126 references the global common-encodings table, 351 // and 127..255 references a local per-second-level-page table. 352 // First we try the compact format and determine how many entries fit. 353 // If more entries fit in the regular format, we use that. 354 for (size_t i = 0; i < cuPtrVector.size();) { 355 secondLevelPages.emplace_back(); 356 SecondLevelPage &page = secondLevelPages.back(); 357 page.entryIndex = i; 358 uintptr_t functionAddressMax = 359 cuPtrVector[i]->functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK; 360 size_t n = commonEncodings.size(); 361 size_t wordsRemaining = 362 SECOND_LEVEL_PAGE_WORDS - 363 sizeof(unwind_info_compressed_second_level_page_header) / 364 sizeof(uint32_t); 365 while (wordsRemaining >= 1 && i < cuPtrVector.size()) { 366 const CompactUnwindEntry<Ptr> *cuPtr = cuPtrVector[i]; 367 if (cuPtr->functionAddress >= functionAddressMax) { 368 break; 369 } else if (commonEncodingIndexes.count(cuPtr->encoding) || 370 page.localEncodingIndexes.count(cuPtr->encoding)) { 371 i++; 372 wordsRemaining--; 373 } else if (wordsRemaining >= 2 && n < COMPACT_ENCODINGS_MAX) { 374 page.localEncodings.emplace_back(cuPtr->encoding); 375 page.localEncodingIndexes[cuPtr->encoding] = n++; 376 i++; 377 wordsRemaining -= 2; 378 } else { 379 break; 380 } 381 } 382 page.entryCount = i - page.entryIndex; 383 384 // If this is not the final page, see if it's possible to fit more 385 // entries by using the regular format. This can happen when there 386 // are many unique encodings, and we we saturated the local 387 // encoding table early. 388 if (i < cuPtrVector.size() && 389 page.entryCount < REGULAR_SECOND_LEVEL_ENTRIES_MAX) { 390 page.kind = UNWIND_SECOND_LEVEL_REGULAR; 391 page.entryCount = std::min(REGULAR_SECOND_LEVEL_ENTRIES_MAX, 392 cuPtrVector.size() - page.entryIndex); 393 i = page.entryIndex + page.entryCount; 394 } else { 395 page.kind = UNWIND_SECOND_LEVEL_COMPRESSED; 396 } 397 } 398 399 for (const CompactUnwindEntry<Ptr> *cu : cuPtrVector) { 400 uint32_t functionOffset = cu->functionAddress - in.header->addr; 401 functionToLsdaIndex[functionOffset] = lsdaEntries.size(); 402 if (cu->lsda != 0) 403 lsdaEntries.push_back( 404 {functionOffset, static_cast<uint32_t>(cu->lsda - in.header->addr)}); 405 } 406 407 // compute size of __TEXT,__unwind_info section 408 level2PagesOffset = 409 sizeof(unwind_info_section_header) + 410 commonEncodings.size() * sizeof(uint32_t) + 411 personalities.size() * sizeof(uint32_t) + 412 // The extra second-level-page entry is for the sentinel 413 (secondLevelPages.size() + 1) * 414 sizeof(unwind_info_section_header_index_entry) + 415 lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry); 416 unwindInfoSize = 417 level2PagesOffset + secondLevelPages.size() * SECOND_LEVEL_PAGE_BYTES; 418 } 419 420 // All inputs are relocated and output addresses are known, so write! 421 422 template <class Ptr> 423 void UnwindInfoSectionImpl<Ptr>::writeTo(uint8_t *buf) const { 424 // section header 425 auto *uip = reinterpret_cast<unwind_info_section_header *>(buf); 426 uip->version = 1; 427 uip->commonEncodingsArraySectionOffset = sizeof(unwind_info_section_header); 428 uip->commonEncodingsArrayCount = commonEncodings.size(); 429 uip->personalityArraySectionOffset = 430 uip->commonEncodingsArraySectionOffset + 431 (uip->commonEncodingsArrayCount * sizeof(uint32_t)); 432 uip->personalityArrayCount = personalities.size(); 433 uip->indexSectionOffset = uip->personalityArraySectionOffset + 434 (uip->personalityArrayCount * sizeof(uint32_t)); 435 uip->indexCount = secondLevelPages.size() + 1; 436 437 // Common encodings 438 auto *i32p = reinterpret_cast<uint32_t *>(&uip[1]); 439 for (const auto &encoding : commonEncodings) 440 *i32p++ = encoding.first; 441 442 // Personalities 443 for (const uint32_t &personality : personalities) 444 *i32p++ = 445 in.got->addr + (personality - 1) * target->wordSize - in.header->addr; 446 447 // Level-1 index 448 uint32_t lsdaOffset = 449 uip->indexSectionOffset + 450 uip->indexCount * sizeof(unwind_info_section_header_index_entry); 451 uint64_t l2PagesOffset = level2PagesOffset; 452 auto *iep = reinterpret_cast<unwind_info_section_header_index_entry *>(i32p); 453 for (const SecondLevelPage &page : secondLevelPages) { 454 iep->functionOffset = 455 cuPtrVector[page.entryIndex]->functionAddress - in.header->addr; 456 iep->secondLevelPagesSectionOffset = l2PagesOffset; 457 iep->lsdaIndexArraySectionOffset = 458 lsdaOffset + functionToLsdaIndex.lookup(iep->functionOffset) * 459 sizeof(unwind_info_section_header_lsda_index_entry); 460 iep++; 461 l2PagesOffset += SECOND_LEVEL_PAGE_BYTES; 462 } 463 // Level-1 sentinel 464 const CompactUnwindEntry<Ptr> &cuEnd = cuVector.back(); 465 iep->functionOffset = cuEnd.functionAddress + cuEnd.functionLength; 466 iep->secondLevelPagesSectionOffset = 0; 467 iep->lsdaIndexArraySectionOffset = 468 lsdaOffset + 469 lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry); 470 iep++; 471 472 // LSDAs 473 size_t lsdaBytes = 474 lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry); 475 if (lsdaBytes > 0) 476 memcpy(iep, lsdaEntries.data(), lsdaBytes); 477 478 // Level-2 pages 479 auto *pp = reinterpret_cast<uint32_t *>(reinterpret_cast<uint8_t *>(iep) + 480 lsdaBytes); 481 for (const SecondLevelPage &page : secondLevelPages) { 482 if (page.kind == UNWIND_SECOND_LEVEL_COMPRESSED) { 483 uintptr_t functionAddressBase = 484 cuPtrVector[page.entryIndex]->functionAddress; 485 auto *p2p = 486 reinterpret_cast<unwind_info_compressed_second_level_page_header *>( 487 pp); 488 p2p->kind = page.kind; 489 p2p->entryPageOffset = 490 sizeof(unwind_info_compressed_second_level_page_header); 491 p2p->entryCount = page.entryCount; 492 p2p->encodingsPageOffset = 493 p2p->entryPageOffset + p2p->entryCount * sizeof(uint32_t); 494 p2p->encodingsCount = page.localEncodings.size(); 495 auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]); 496 for (size_t i = 0; i < page.entryCount; i++) { 497 const CompactUnwindEntry<Ptr> *cuep = cuPtrVector[page.entryIndex + i]; 498 auto it = commonEncodingIndexes.find(cuep->encoding); 499 if (it == commonEncodingIndexes.end()) 500 it = page.localEncodingIndexes.find(cuep->encoding); 501 *ep++ = (it->second << COMPRESSED_ENTRY_FUNC_OFFSET_BITS) | 502 (cuep->functionAddress - functionAddressBase); 503 } 504 if (page.localEncodings.size() != 0) 505 memcpy(ep, page.localEncodings.data(), 506 page.localEncodings.size() * sizeof(uint32_t)); 507 } else { 508 auto *p2p = 509 reinterpret_cast<unwind_info_regular_second_level_page_header *>(pp); 510 p2p->kind = page.kind; 511 p2p->entryPageOffset = 512 sizeof(unwind_info_regular_second_level_page_header); 513 p2p->entryCount = page.entryCount; 514 auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]); 515 for (size_t i = 0; i < page.entryCount; i++) { 516 const CompactUnwindEntry<Ptr> *cuep = cuPtrVector[page.entryIndex + i]; 517 *ep++ = cuep->functionAddress; 518 *ep++ = cuep->encoding; 519 } 520 } 521 pp += SECOND_LEVEL_PAGE_WORDS; 522 } 523 } 524 525 UnwindInfoSection *macho::makeUnwindInfoSection() { 526 if (target->wordSize == 8) 527 return make<UnwindInfoSectionImpl<uint64_t>>(); 528 else 529 return make<UnwindInfoSectionImpl<uint32_t>>(); 530 } 531