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