xref: /freebsd-src/contrib/llvm-project/lld/MachO/UnwindInfoSection.cpp (revision 06c3fb2749bda94cb5201f81ffdb8fa6c3161b2e)
1e8d8bef9SDimitry Andric //===- UnwindInfoSection.cpp ----------------------------------------------===//
2e8d8bef9SDimitry Andric //
3e8d8bef9SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e8d8bef9SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e8d8bef9SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e8d8bef9SDimitry Andric //
7e8d8bef9SDimitry Andric //===----------------------------------------------------------------------===//
8e8d8bef9SDimitry Andric 
9e8d8bef9SDimitry Andric #include "UnwindInfoSection.h"
10e8d8bef9SDimitry Andric #include "InputSection.h"
11*06c3fb27SDimitry Andric #include "Layout.h"
12e8d8bef9SDimitry Andric #include "OutputSection.h"
13e8d8bef9SDimitry Andric #include "OutputSegment.h"
14fe6060f1SDimitry Andric #include "SymbolTable.h"
15e8d8bef9SDimitry Andric #include "Symbols.h"
16e8d8bef9SDimitry Andric #include "SyntheticSections.h"
17e8d8bef9SDimitry Andric #include "Target.h"
18e8d8bef9SDimitry Andric 
19e8d8bef9SDimitry Andric #include "lld/Common/ErrorHandler.h"
20fe6060f1SDimitry Andric #include "lld/Common/Memory.h"
21349cc55cSDimitry Andric #include "llvm/ADT/DenseMap.h"
22fe6060f1SDimitry Andric #include "llvm/ADT/STLExtras.h"
23e8d8bef9SDimitry Andric #include "llvm/BinaryFormat/MachO.h"
24349cc55cSDimitry Andric #include "llvm/Support/Parallel.h"
25349cc55cSDimitry Andric 
26bdd1243dSDimitry Andric #include "mach-o/compact_unwind_encoding.h"
27bdd1243dSDimitry Andric 
28349cc55cSDimitry Andric #include <numeric>
29e8d8bef9SDimitry Andric 
30e8d8bef9SDimitry Andric using namespace llvm;
31e8d8bef9SDimitry Andric using namespace llvm::MachO;
3281ad6265SDimitry Andric using namespace llvm::support::endian;
33e8d8bef9SDimitry Andric using namespace lld;
34e8d8bef9SDimitry Andric using namespace lld::macho;
35e8d8bef9SDimitry Andric 
36e8d8bef9SDimitry Andric #define COMMON_ENCODINGS_MAX 127
37e8d8bef9SDimitry Andric #define COMPACT_ENCODINGS_MAX 256
38e8d8bef9SDimitry Andric 
39e8d8bef9SDimitry Andric #define SECOND_LEVEL_PAGE_BYTES 4096
40e8d8bef9SDimitry Andric #define SECOND_LEVEL_PAGE_WORDS (SECOND_LEVEL_PAGE_BYTES / sizeof(uint32_t))
41e8d8bef9SDimitry Andric #define REGULAR_SECOND_LEVEL_ENTRIES_MAX                                       \
42e8d8bef9SDimitry Andric   ((SECOND_LEVEL_PAGE_BYTES -                                                  \
43e8d8bef9SDimitry Andric     sizeof(unwind_info_regular_second_level_page_header)) /                    \
44e8d8bef9SDimitry Andric    sizeof(unwind_info_regular_second_level_entry))
45e8d8bef9SDimitry Andric #define COMPRESSED_SECOND_LEVEL_ENTRIES_MAX                                    \
46e8d8bef9SDimitry Andric   ((SECOND_LEVEL_PAGE_BYTES -                                                  \
47e8d8bef9SDimitry Andric     sizeof(unwind_info_compressed_second_level_page_header)) /                 \
48e8d8bef9SDimitry Andric    sizeof(uint32_t))
49e8d8bef9SDimitry Andric 
50e8d8bef9SDimitry Andric #define COMPRESSED_ENTRY_FUNC_OFFSET_BITS 24
51e8d8bef9SDimitry Andric #define COMPRESSED_ENTRY_FUNC_OFFSET_MASK                                      \
52e8d8bef9SDimitry Andric   UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET(~0)
53e8d8bef9SDimitry Andric 
54*06c3fb27SDimitry Andric static_assert(static_cast<uint32_t>(UNWIND_X86_64_DWARF_SECTION_OFFSET) ==
55*06c3fb27SDimitry Andric                   static_cast<uint32_t>(UNWIND_ARM64_DWARF_SECTION_OFFSET) &&
56*06c3fb27SDimitry Andric               static_cast<uint32_t>(UNWIND_X86_64_DWARF_SECTION_OFFSET) ==
57*06c3fb27SDimitry Andric                   static_cast<uint32_t>(UNWIND_X86_DWARF_SECTION_OFFSET));
58*06c3fb27SDimitry Andric 
59*06c3fb27SDimitry Andric constexpr uint64_t DWARF_SECTION_OFFSET = UNWIND_X86_64_DWARF_SECTION_OFFSET;
60*06c3fb27SDimitry Andric 
61e8d8bef9SDimitry Andric // Compact Unwind format is a Mach-O evolution of DWARF Unwind that
62e8d8bef9SDimitry Andric // optimizes space and exception-time lookup.  Most DWARF unwind
63e8d8bef9SDimitry Andric // entries can be replaced with Compact Unwind entries, but the ones
64e8d8bef9SDimitry Andric // that cannot are retained in DWARF form.
65e8d8bef9SDimitry Andric //
66e8d8bef9SDimitry Andric // This comment will address macro-level organization of the pre-link
67e8d8bef9SDimitry Andric // and post-link compact unwind tables. For micro-level organization
68e8d8bef9SDimitry Andric // pertaining to the bitfield layout of the 32-bit compact unwind
69e8d8bef9SDimitry Andric // entries, see libunwind/include/mach-o/compact_unwind_encoding.h
70e8d8bef9SDimitry Andric //
71e8d8bef9SDimitry Andric // Important clarifying factoids:
72e8d8bef9SDimitry Andric //
73e8d8bef9SDimitry Andric // * __LD,__compact_unwind is the compact unwind format for compiler
74e8d8bef9SDimitry Andric // output and linker input. It is never a final output. It could be
75e8d8bef9SDimitry Andric // an intermediate output with the `-r` option which retains relocs.
76e8d8bef9SDimitry Andric //
77e8d8bef9SDimitry Andric // * __TEXT,__unwind_info is the compact unwind format for final
78e8d8bef9SDimitry Andric // linker output. It is never an input.
79e8d8bef9SDimitry Andric //
80e8d8bef9SDimitry Andric // * __TEXT,__eh_frame is the DWARF format for both linker input and output.
81e8d8bef9SDimitry Andric //
82e8d8bef9SDimitry Andric // * __TEXT,__unwind_info entries are divided into 4 KiB pages (2nd
83e8d8bef9SDimitry Andric // level) by ascending address, and the pages are referenced by an
84e8d8bef9SDimitry Andric // index (1st level) in the section header.
85e8d8bef9SDimitry Andric //
86e8d8bef9SDimitry Andric // * Following the headers in __TEXT,__unwind_info, the bulk of the
87e8d8bef9SDimitry Andric // section contains a vector of compact unwind entries
88e8d8bef9SDimitry Andric // `{functionOffset, encoding}` sorted by ascending `functionOffset`.
89e8d8bef9SDimitry Andric // Adjacent entries with the same encoding can be folded to great
90e8d8bef9SDimitry Andric // advantage, achieving a 3-order-of-magnitude reduction in the
91e8d8bef9SDimitry Andric // number of entries.
92e8d8bef9SDimitry Andric //
93fe6060f1SDimitry Andric // Refer to the definition of unwind_info_section_header in
94fe6060f1SDimitry Andric // compact_unwind_encoding.h for an overview of the format we are encoding
95fe6060f1SDimitry Andric // here.
96e8d8bef9SDimitry Andric 
97e8d8bef9SDimitry Andric // TODO(gkm): how do we align the 2nd-level pages?
98e8d8bef9SDimitry Andric 
99*06c3fb27SDimitry Andric // The various fields in the on-disk representation of each compact unwind
100*06c3fb27SDimitry Andric // entry.
101*06c3fb27SDimitry Andric #define FOR_EACH_CU_FIELD(DO)                                                  \
102*06c3fb27SDimitry Andric   DO(Ptr, functionAddress)                                                     \
103*06c3fb27SDimitry Andric   DO(uint32_t, functionLength)                                                 \
104*06c3fb27SDimitry Andric   DO(compact_unwind_encoding_t, encoding)                                      \
105*06c3fb27SDimitry Andric   DO(Ptr, personality)                                                         \
106*06c3fb27SDimitry Andric   DO(Ptr, lsda)
10781ad6265SDimitry Andric 
108*06c3fb27SDimitry Andric CREATE_LAYOUT_CLASS(CompactUnwind, FOR_EACH_CU_FIELD);
10981ad6265SDimitry Andric 
110*06c3fb27SDimitry Andric #undef FOR_EACH_CU_FIELD
11181ad6265SDimitry Andric 
11281ad6265SDimitry Andric // LLD's internal representation of a compact unwind entry.
11381ad6265SDimitry Andric struct CompactUnwindEntry {
11481ad6265SDimitry Andric   uint64_t functionAddress;
11581ad6265SDimitry Andric   uint32_t functionLength;
11681ad6265SDimitry Andric   compact_unwind_encoding_t encoding;
11781ad6265SDimitry Andric   Symbol *personality;
11881ad6265SDimitry Andric   InputSection *lsda;
11981ad6265SDimitry Andric };
120349cc55cSDimitry Andric 
121fe6060f1SDimitry Andric using EncodingMap = DenseMap<compact_unwind_encoding_t, size_t>;
122fe6060f1SDimitry Andric 
123fe6060f1SDimitry Andric struct SecondLevelPage {
124fe6060f1SDimitry Andric   uint32_t kind;
125fe6060f1SDimitry Andric   size_t entryIndex;
126fe6060f1SDimitry Andric   size_t entryCount;
127fe6060f1SDimitry Andric   size_t byteCount;
128fe6060f1SDimitry Andric   std::vector<compact_unwind_encoding_t> localEncodings;
129fe6060f1SDimitry Andric   EncodingMap localEncodingIndexes;
130fe6060f1SDimitry Andric };
131fe6060f1SDimitry Andric 
13281ad6265SDimitry Andric // UnwindInfoSectionImpl allows us to avoid cluttering our header file with a
13381ad6265SDimitry Andric // lengthy definition of UnwindInfoSection.
134fe6060f1SDimitry Andric class UnwindInfoSectionImpl final : public UnwindInfoSection {
135fe6060f1SDimitry Andric public:
136*06c3fb27SDimitry Andric   UnwindInfoSectionImpl() : cuLayout(target->wordSize) {}
13781ad6265SDimitry Andric   uint64_t getSize() const override { return unwindInfoSize; }
138f3fd488fSDimitry Andric   void prepare() override;
139fe6060f1SDimitry Andric   void finalize() override;
140fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override;
141fe6060f1SDimitry Andric 
142fe6060f1SDimitry Andric private:
14381ad6265SDimitry Andric   void prepareRelocations(ConcatInputSection *);
14481ad6265SDimitry Andric   void relocateCompactUnwind(std::vector<CompactUnwindEntry> &);
14581ad6265SDimitry Andric   void encodePersonalities();
146f3fd488fSDimitry Andric   Symbol *canonicalizePersonality(Symbol *);
14781ad6265SDimitry Andric 
14881ad6265SDimitry Andric   uint64_t unwindInfoSize = 0;
149*06c3fb27SDimitry Andric   SmallVector<decltype(symbols)::value_type, 0> symbolsVec;
150*06c3fb27SDimitry Andric   CompactUnwindLayout cuLayout;
151fe6060f1SDimitry Andric   std::vector<std::pair<compact_unwind_encoding_t, size_t>> commonEncodings;
152fe6060f1SDimitry Andric   EncodingMap commonEncodingIndexes;
153349cc55cSDimitry Andric   // The entries here will be in the same order as their originating symbols
154349cc55cSDimitry Andric   // in symbolsVec.
15581ad6265SDimitry Andric   std::vector<CompactUnwindEntry> cuEntries;
156349cc55cSDimitry Andric   // Indices into the cuEntries vector.
157349cc55cSDimitry Andric   std::vector<size_t> cuIndices;
15881ad6265SDimitry Andric   std::vector<Symbol *> personalities;
159fe6060f1SDimitry Andric   SmallDenseMap<std::pair<InputSection *, uint64_t /* addend */>, Symbol *>
160fe6060f1SDimitry Andric       personalityTable;
161349cc55cSDimitry Andric   // Indices into cuEntries for CUEs with a non-null LSDA.
162349cc55cSDimitry Andric   std::vector<size_t> entriesWithLsda;
163349cc55cSDimitry Andric   // Map of cuEntries index to an index within the LSDA array.
164349cc55cSDimitry Andric   DenseMap<size_t, uint32_t> lsdaIndex;
165fe6060f1SDimitry Andric   std::vector<SecondLevelPage> secondLevelPages;
166fe6060f1SDimitry Andric   uint64_t level2PagesOffset = 0;
167bdd1243dSDimitry Andric   // The highest-address function plus its size. The unwinder needs this to
168bdd1243dSDimitry Andric   // determine the address range that is covered by unwind info.
169bdd1243dSDimitry Andric   uint64_t cueEndBoundary = 0;
170fe6060f1SDimitry Andric };
171fe6060f1SDimitry Andric 
172e8d8bef9SDimitry Andric UnwindInfoSection::UnwindInfoSection()
173e8d8bef9SDimitry Andric     : SyntheticSection(segment_names::text, section_names::unwindInfo) {
174fe6060f1SDimitry Andric   align = 4;
175e8d8bef9SDimitry Andric }
176e8d8bef9SDimitry Andric 
177349cc55cSDimitry Andric // Record function symbols that may need entries emitted in __unwind_info, which
178349cc55cSDimitry Andric // stores unwind data for address ranges.
179349cc55cSDimitry Andric //
1806246ae0bSDimitry Andric // Note that if several adjacent functions have the same unwind encoding and
1816246ae0bSDimitry Andric // personality function and no LSDA, they share one unwind entry. For this to
1826246ae0bSDimitry Andric // work, functions without unwind info need explicit "no unwind info" unwind
1836246ae0bSDimitry Andric // entries -- else the unwinder would think they have the unwind info of the
1846246ae0bSDimitry Andric // closest function with unwind info right before in the image. Thus, we add
1856246ae0bSDimitry Andric // function symbols for each unique address regardless of whether they have
1866246ae0bSDimitry Andric // associated unwind info.
187349cc55cSDimitry Andric void UnwindInfoSection::addSymbol(const Defined *d) {
188349cc55cSDimitry Andric   if (d->unwindEntry)
189349cc55cSDimitry Andric     allEntriesAreOmitted = false;
190349cc55cSDimitry Andric   // We don't yet know the final output address of this symbol, but we know that
191349cc55cSDimitry Andric   // they are uniquely determined by a combination of the isec and value, so
192349cc55cSDimitry Andric   // we use that as the key here.
193349cc55cSDimitry Andric   auto p = symbols.insert({{d->isec, d->value}, d});
194349cc55cSDimitry Andric   // If we have multiple symbols at the same address, only one of them can have
195fcaf7f86SDimitry Andric   // an associated unwind entry.
196349cc55cSDimitry Andric   if (!p.second && d->unwindEntry) {
197bdd1243dSDimitry Andric     assert(p.first->second == d || !p.first->second->unwindEntry);
198349cc55cSDimitry Andric     p.first->second = d;
199349cc55cSDimitry Andric   }
200fe6060f1SDimitry Andric }
201fe6060f1SDimitry Andric 
202f3fd488fSDimitry Andric void UnwindInfoSectionImpl::prepare() {
20381ad6265SDimitry Andric   // This iteration needs to be deterministic, since prepareRelocations may add
20481ad6265SDimitry Andric   // entries to the GOT. Hence the use of a MapVector for
20581ad6265SDimitry Andric   // UnwindInfoSection::symbols.
20681ad6265SDimitry Andric   for (const Defined *d : make_second_range(symbols))
207f3fd488fSDimitry Andric     if (d->unwindEntry) {
208f3fd488fSDimitry Andric       if (d->unwindEntry->getName() == section_names::compactUnwind) {
20981ad6265SDimitry Andric         prepareRelocations(d->unwindEntry);
210f3fd488fSDimitry Andric       } else {
211f3fd488fSDimitry Andric         // We don't have to add entries to the GOT here because FDEs have
212f3fd488fSDimitry Andric         // explicit GOT relocations, so Writer::scanRelocations() will add those
213f3fd488fSDimitry Andric         // GOT entries. However, we still need to canonicalize the personality
214f3fd488fSDimitry Andric         // pointers (like prepareRelocations() does for CU entries) in order
215f3fd488fSDimitry Andric         // to avoid overflowing the 3-personality limit.
216f3fd488fSDimitry Andric         FDE &fde = cast<ObjFile>(d->getFile())->fdes[d->unwindEntry];
217f3fd488fSDimitry Andric         fde.personality = canonicalizePersonality(fde.personality);
218f3fd488fSDimitry Andric       }
219f3fd488fSDimitry Andric     }
22081ad6265SDimitry Andric }
22181ad6265SDimitry Andric 
222fe6060f1SDimitry Andric // Compact unwind relocations have different semantics, so we handle them in a
223fe6060f1SDimitry Andric // separate code path from regular relocations. First, we do not wish to add
224fe6060f1SDimitry Andric // rebase opcodes for __LD,__compact_unwind, because that section doesn't
225fe6060f1SDimitry Andric // actually end up in the final binary. Second, personality pointers always
226fe6060f1SDimitry Andric // reside in the GOT and must be treated specially.
22781ad6265SDimitry Andric void UnwindInfoSectionImpl::prepareRelocations(ConcatInputSection *isec) {
228fe6060f1SDimitry Andric   assert(!isec->shouldOmitFromOutput() &&
229fe6060f1SDimitry Andric          "__compact_unwind section should not be omitted");
230fe6060f1SDimitry Andric 
231fe6060f1SDimitry Andric   // FIXME: Make this skip relocations for CompactUnwindEntries that
232fe6060f1SDimitry Andric   // point to dead-stripped functions. That might save some amount of
233fe6060f1SDimitry Andric   // work. But since there are usually just few personality functions
234fe6060f1SDimitry Andric   // that are referenced from many places, at least some of them likely
235fe6060f1SDimitry Andric   // live, it wouldn't reduce number of got entries.
236fe6060f1SDimitry Andric   for (size_t i = 0; i < isec->relocs.size(); ++i) {
237fe6060f1SDimitry Andric     Reloc &r = isec->relocs[i];
238fe6060f1SDimitry Andric     assert(target->hasAttr(r.type, RelocAttrBits::UNSIGNED));
239bdd1243dSDimitry Andric     // Since compact unwind sections aren't part of the inputSections vector,
240bdd1243dSDimitry Andric     // they don't get canonicalized by scanRelocations(), so we have to do the
241bdd1243dSDimitry Andric     // canonicalization here.
242bdd1243dSDimitry Andric     if (auto *referentIsec = r.referent.dyn_cast<InputSection *>())
243bdd1243dSDimitry Andric       r.referent = referentIsec->canonical();
244fe6060f1SDimitry Andric 
245349cc55cSDimitry Andric     // Functions and LSDA entries always reside in the same object file as the
246349cc55cSDimitry Andric     // compact unwind entries that references them, and thus appear as section
247349cc55cSDimitry Andric     // relocs. There is no need to prepare them. We only prepare relocs for
248349cc55cSDimitry Andric     // personality functions.
249*06c3fb27SDimitry Andric     if (r.offset != cuLayout.personalityOffset)
250fe6060f1SDimitry Andric       continue;
251fe6060f1SDimitry Andric 
252fe6060f1SDimitry Andric     if (auto *s = r.referent.dyn_cast<Symbol *>()) {
253349cc55cSDimitry Andric       // Personality functions are nearly always system-defined (e.g.,
254349cc55cSDimitry Andric       // ___gxx_personality_v0 for C++) and relocated as dylib symbols.  When an
255349cc55cSDimitry Andric       // application provides its own personality function, it might be
256349cc55cSDimitry Andric       // referenced by an extern Defined symbol reloc, or a local section reloc.
257349cc55cSDimitry Andric       if (auto *defined = dyn_cast<Defined>(s)) {
258bdd1243dSDimitry Andric         // XXX(vyng) This is a special case for handling duplicate personality
259349cc55cSDimitry Andric         // symbols. Note that LD64's behavior is a bit different and it is
260349cc55cSDimitry Andric         // inconsistent with how symbol resolution usually work
261349cc55cSDimitry Andric         //
262349cc55cSDimitry Andric         // So we've decided not to follow it. Instead, simply pick the symbol
263349cc55cSDimitry Andric         // with the same name from the symbol table to replace the local one.
264349cc55cSDimitry Andric         //
265349cc55cSDimitry Andric         // (See discussions/alternatives already considered on D107533)
266349cc55cSDimitry Andric         if (!defined->isExternal())
2674824e7fdSDimitry Andric           if (Symbol *sym = symtab->find(defined->getName()))
26804eeddc0SDimitry Andric             if (!sym->isLazy())
2694824e7fdSDimitry Andric               r.referent = s = sym;
270349cc55cSDimitry Andric       }
271fe6060f1SDimitry Andric       if (auto *undefined = dyn_cast<Undefined>(s)) {
27281ad6265SDimitry Andric         treatUndefinedSymbol(*undefined, isec, r.offset);
273fe6060f1SDimitry Andric         // treatUndefinedSymbol() can replace s with a DylibSymbol; re-check.
274fe6060f1SDimitry Andric         if (isa<Undefined>(s))
275fe6060f1SDimitry Andric           continue;
276fe6060f1SDimitry Andric       }
277349cc55cSDimitry Andric 
278f3fd488fSDimitry Andric       // Similar to canonicalizePersonality(), but we also register a GOT entry.
279fe6060f1SDimitry Andric       if (auto *defined = dyn_cast<Defined>(s)) {
280fe6060f1SDimitry Andric         // Check if we have created a synthetic symbol at the same address.
281fe6060f1SDimitry Andric         Symbol *&personality =
282fe6060f1SDimitry Andric             personalityTable[{defined->isec, defined->value}];
283fe6060f1SDimitry Andric         if (personality == nullptr) {
284fe6060f1SDimitry Andric           personality = defined;
285fe6060f1SDimitry Andric           in.got->addEntry(defined);
286fe6060f1SDimitry Andric         } else if (personality != defined) {
287fe6060f1SDimitry Andric           r.referent = personality;
288fe6060f1SDimitry Andric         }
289fe6060f1SDimitry Andric         continue;
290fe6060f1SDimitry Andric       }
291f3fd488fSDimitry Andric 
292fe6060f1SDimitry Andric       assert(isa<DylibSymbol>(s));
293fe6060f1SDimitry Andric       in.got->addEntry(s);
294fe6060f1SDimitry Andric       continue;
295fe6060f1SDimitry Andric     }
296fe6060f1SDimitry Andric 
297fe6060f1SDimitry Andric     if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
298fe6060f1SDimitry Andric       assert(!isCoalescedWeak(referentIsec));
299fe6060f1SDimitry Andric       // Personality functions can be referenced via section relocations
300fe6060f1SDimitry Andric       // if they live in the same object file. Create placeholder synthetic
301fe6060f1SDimitry Andric       // symbols for them in the GOT.
302fe6060f1SDimitry Andric       Symbol *&s = personalityTable[{referentIsec, r.addend}];
303fe6060f1SDimitry Andric       if (s == nullptr) {
304fe6060f1SDimitry Andric         // This runs after dead stripping, so the noDeadStrip argument does not
305fe6060f1SDimitry Andric         // matter.
306fe6060f1SDimitry Andric         s = make<Defined>("<internal>", /*file=*/nullptr, referentIsec,
307fe6060f1SDimitry Andric                           r.addend, /*size=*/0, /*isWeakDef=*/false,
308fe6060f1SDimitry Andric                           /*isExternal=*/false, /*isPrivateExtern=*/false,
30981ad6265SDimitry Andric                           /*includeInSymtab=*/true,
310*06c3fb27SDimitry Andric                           /*isReferencedDynamically=*/false,
311fe6060f1SDimitry Andric                           /*noDeadStrip=*/false);
31281ad6265SDimitry Andric         s->used = true;
313fe6060f1SDimitry Andric         in.got->addEntry(s);
314fe6060f1SDimitry Andric       }
315fe6060f1SDimitry Andric       r.referent = s;
316fe6060f1SDimitry Andric       r.addend = 0;
317fe6060f1SDimitry Andric     }
318fe6060f1SDimitry Andric   }
319fe6060f1SDimitry Andric }
320fe6060f1SDimitry Andric 
321f3fd488fSDimitry Andric Symbol *UnwindInfoSectionImpl::canonicalizePersonality(Symbol *personality) {
322f3fd488fSDimitry Andric   if (auto *defined = dyn_cast_or_null<Defined>(personality)) {
323f3fd488fSDimitry Andric     // Check if we have created a synthetic symbol at the same address.
324f3fd488fSDimitry Andric     Symbol *&synth = personalityTable[{defined->isec, defined->value}];
325f3fd488fSDimitry Andric     if (synth == nullptr)
326f3fd488fSDimitry Andric       synth = defined;
327f3fd488fSDimitry Andric     else if (synth != defined)
328f3fd488fSDimitry Andric       return synth;
329f3fd488fSDimitry Andric   }
330f3fd488fSDimitry Andric   return personality;
331f3fd488fSDimitry Andric }
332f3fd488fSDimitry Andric 
333fe6060f1SDimitry Andric // We need to apply the relocations to the pre-link compact unwind section
334fe6060f1SDimitry Andric // before converting it to post-link form. There should only be absolute
335fe6060f1SDimitry Andric // relocations here: since we are not emitting the pre-link CU section, there
336fe6060f1SDimitry Andric // is no source address to make a relative location meaningful.
33781ad6265SDimitry Andric void UnwindInfoSectionImpl::relocateCompactUnwind(
33881ad6265SDimitry Andric     std::vector<CompactUnwindEntry> &cuEntries) {
33981ad6265SDimitry Andric   parallelFor(0, symbolsVec.size(), [&](size_t i) {
34081ad6265SDimitry Andric     CompactUnwindEntry &cu = cuEntries[i];
341349cc55cSDimitry Andric     const Defined *d = symbolsVec[i].second;
34281ad6265SDimitry Andric     cu.functionAddress = d->getVA();
343349cc55cSDimitry Andric     if (!d->unwindEntry)
344349cc55cSDimitry Andric       return;
345fe6060f1SDimitry Andric 
346*06c3fb27SDimitry Andric     // If we have DWARF unwind info, create a slimmed-down CU entry that points
347*06c3fb27SDimitry Andric     // to it.
34881ad6265SDimitry Andric     if (d->unwindEntry->getName() == section_names::ehFrame) {
349*06c3fb27SDimitry Andric       // The unwinder will look for the DWARF entry starting at the hint,
350*06c3fb27SDimitry Andric       // assuming the hint points to a valid CFI record start. If it
351*06c3fb27SDimitry Andric       // fails to find the record, it proceeds in a linear search through the
352*06c3fb27SDimitry Andric       // contiguous CFI records from the hint until the end of the section.
353*06c3fb27SDimitry Andric       // Ideally, in the case where the offset is too large to be encoded, we
354*06c3fb27SDimitry Andric       // would instead encode the largest possible offset to a valid CFI record,
355*06c3fb27SDimitry Andric       // but since we don't keep track of that, just encode zero -- the start of
356*06c3fb27SDimitry Andric       // the section is always the start of a CFI record.
357*06c3fb27SDimitry Andric       uint64_t dwarfOffsetHint =
358*06c3fb27SDimitry Andric           d->unwindEntry->outSecOff <= DWARF_SECTION_OFFSET
359*06c3fb27SDimitry Andric               ? d->unwindEntry->outSecOff
360*06c3fb27SDimitry Andric               : 0;
361*06c3fb27SDimitry Andric       cu.encoding = target->modeDwarfEncoding | dwarfOffsetHint;
36281ad6265SDimitry Andric       const FDE &fde = cast<ObjFile>(d->getFile())->fdes[d->unwindEntry];
36381ad6265SDimitry Andric       cu.functionLength = fde.funcLength;
364*06c3fb27SDimitry Andric       // Omit the DWARF personality from compact-unwind entry so that we
365*06c3fb27SDimitry Andric       // don't need to encode it.
366*06c3fb27SDimitry Andric       cu.personality = nullptr;
36781ad6265SDimitry Andric       cu.lsda = fde.lsda;
36881ad6265SDimitry Andric       return;
36981ad6265SDimitry Andric     }
37081ad6265SDimitry Andric 
37181ad6265SDimitry Andric     assert(d->unwindEntry->getName() == section_names::compactUnwind);
37281ad6265SDimitry Andric 
37381ad6265SDimitry Andric     auto buf = reinterpret_cast<const uint8_t *>(d->unwindEntry->data.data()) -
37481ad6265SDimitry Andric                target->wordSize;
37581ad6265SDimitry Andric     cu.functionLength =
376*06c3fb27SDimitry Andric         support::endian::read32le(buf + cuLayout.functionLengthOffset);
377*06c3fb27SDimitry Andric     cu.encoding = support::endian::read32le(buf + cuLayout.encodingOffset);
378349cc55cSDimitry Andric     for (const Reloc &r : d->unwindEntry->relocs) {
379*06c3fb27SDimitry Andric       if (r.offset == cuLayout.personalityOffset)
38081ad6265SDimitry Andric         cu.personality = r.referent.get<Symbol *>();
381*06c3fb27SDimitry Andric       else if (r.offset == cuLayout.lsdaOffset)
382*06c3fb27SDimitry Andric         cu.lsda = r.getReferentInputSection();
383fe6060f1SDimitry Andric     }
384349cc55cSDimitry Andric   });
385fe6060f1SDimitry Andric }
386fe6060f1SDimitry Andric 
387fe6060f1SDimitry Andric // There should only be a handful of unique personality pointers, so we can
388fe6060f1SDimitry Andric // encode them as 2-bit indices into a small array.
38981ad6265SDimitry Andric void UnwindInfoSectionImpl::encodePersonalities() {
390349cc55cSDimitry Andric   for (size_t idx : cuIndices) {
39181ad6265SDimitry Andric     CompactUnwindEntry &cu = cuEntries[idx];
39281ad6265SDimitry Andric     if (cu.personality == nullptr)
393fe6060f1SDimitry Andric       continue;
394fe6060f1SDimitry Andric     // Linear search is fast enough for a small array.
395349cc55cSDimitry Andric     auto it = find(personalities, cu.personality);
396fe6060f1SDimitry Andric     uint32_t personalityIndex; // 1-based index
397fe6060f1SDimitry Andric     if (it != personalities.end()) {
398fe6060f1SDimitry Andric       personalityIndex = std::distance(personalities.begin(), it) + 1;
399fe6060f1SDimitry Andric     } else {
400349cc55cSDimitry Andric       personalities.push_back(cu.personality);
401fe6060f1SDimitry Andric       personalityIndex = personalities.size();
402fe6060f1SDimitry Andric     }
403349cc55cSDimitry Andric     cu.encoding |=
404*06c3fb27SDimitry Andric         personalityIndex << llvm::countr_zero(
405fe6060f1SDimitry Andric             static_cast<compact_unwind_encoding_t>(UNWIND_PERSONALITY_MASK));
406fe6060f1SDimitry Andric   }
407fe6060f1SDimitry Andric   if (personalities.size() > 3)
40881ad6265SDimitry Andric     error("too many personalities (" + Twine(personalities.size()) +
409fe6060f1SDimitry Andric           ") for compact unwind to encode");
410fe6060f1SDimitry Andric }
411fe6060f1SDimitry Andric 
412fe6060f1SDimitry Andric static bool canFoldEncoding(compact_unwind_encoding_t encoding) {
413fe6060f1SDimitry Andric   // From compact_unwind_encoding.h:
414fe6060f1SDimitry Andric   //  UNWIND_X86_64_MODE_STACK_IND:
415fe6060f1SDimitry Andric   //  A "frameless" (RBP not used as frame pointer) function large constant
416fe6060f1SDimitry Andric   //  stack size.  This case is like the previous, except the stack size is too
417fe6060f1SDimitry Andric   //  large to encode in the compact unwind encoding.  Instead it requires that
418fe6060f1SDimitry Andric   //  the function contains "subq $nnnnnnnn,RSP" in its prolog.  The compact
419fe6060f1SDimitry Andric   //  encoding contains the offset to the nnnnnnnn value in the function in
420fe6060f1SDimitry Andric   //  UNWIND_X86_64_FRAMELESS_STACK_SIZE.
421fe6060f1SDimitry Andric   // Since this means the unwinder has to look at the `subq` in the function
422fe6060f1SDimitry Andric   // of the unwind info's unwind address, two functions that have identical
423fe6060f1SDimitry Andric   // unwind info can't be folded if it's using this encoding since both
424fe6060f1SDimitry Andric   // entries need unique addresses.
42561cfbce3SDimitry Andric   static_assert(static_cast<uint32_t>(UNWIND_X86_64_MODE_STACK_IND) ==
426bdd1243dSDimitry Andric                 static_cast<uint32_t>(UNWIND_X86_MODE_STACK_IND));
427fe6060f1SDimitry Andric   if ((target->cpuType == CPU_TYPE_X86_64 || target->cpuType == CPU_TYPE_X86) &&
428bdd1243dSDimitry Andric       (encoding & UNWIND_MODE_MASK) == UNWIND_X86_64_MODE_STACK_IND) {
429fe6060f1SDimitry Andric     // FIXME: Consider passing in the two function addresses and getting
430fe6060f1SDimitry Andric     // their two stack sizes off the `subq` and only returning false if they're
431fe6060f1SDimitry Andric     // actually different.
432fe6060f1SDimitry Andric     return false;
433fe6060f1SDimitry Andric   }
434fe6060f1SDimitry Andric   return true;
435e8d8bef9SDimitry Andric }
436e8d8bef9SDimitry Andric 
437e8d8bef9SDimitry Andric // Scan the __LD,__compact_unwind entries and compute the space needs of
4381fd87a68SDimitry Andric // __TEXT,__unwind_info and __TEXT,__eh_frame.
43981ad6265SDimitry Andric void UnwindInfoSectionImpl::finalize() {
440349cc55cSDimitry Andric   if (symbols.empty())
441e8d8bef9SDimitry Andric     return;
442e8d8bef9SDimitry Andric 
443e8d8bef9SDimitry Andric   // At this point, the address space for __TEXT,__text has been
444e8d8bef9SDimitry Andric   // assigned, so we can relocate the __LD,__compact_unwind entries
445e8d8bef9SDimitry Andric   // into a temporary buffer. Relocation is necessary in order to sort
446e8d8bef9SDimitry Andric   // the CU entries by function address. Sorting is necessary so that
4476246ae0bSDimitry Andric   // we can fold adjacent CU entries with identical encoding+personality
4486246ae0bSDimitry Andric   // and without any LSDA. Folding is necessary because it reduces the
4496246ae0bSDimitry Andric   // number of CU entries by as much as 3 orders of magnitude!
450349cc55cSDimitry Andric   cuEntries.resize(symbols.size());
451349cc55cSDimitry Andric   // The "map" part of the symbols MapVector was only needed for deduplication
452349cc55cSDimitry Andric   // in addSymbol(). Now that we are done adding, move the contents to a plain
453349cc55cSDimitry Andric   // std::vector for indexed access.
454349cc55cSDimitry Andric   symbolsVec = symbols.takeVector();
455349cc55cSDimitry Andric   relocateCompactUnwind(cuEntries);
456e8d8bef9SDimitry Andric 
457e8d8bef9SDimitry Andric   // Rather than sort & fold the 32-byte entries directly, we create a
458349cc55cSDimitry Andric   // vector of indices to entries and sort & fold that instead.
459349cc55cSDimitry Andric   cuIndices.resize(cuEntries.size());
460349cc55cSDimitry Andric   std::iota(cuIndices.begin(), cuIndices.end(), 0);
461349cc55cSDimitry Andric   llvm::sort(cuIndices, [&](size_t a, size_t b) {
462349cc55cSDimitry Andric     return cuEntries[a].functionAddress < cuEntries[b].functionAddress;
463e8d8bef9SDimitry Andric   });
464e8d8bef9SDimitry Andric 
465bdd1243dSDimitry Andric   // Record the ending boundary before we fold the entries.
466bdd1243dSDimitry Andric   cueEndBoundary = cuEntries[cuIndices.back()].functionAddress +
467bdd1243dSDimitry Andric                    cuEntries[cuIndices.back()].functionLength;
468bdd1243dSDimitry Andric 
4696246ae0bSDimitry Andric   // Fold adjacent entries with matching encoding+personality and without LSDA
470349cc55cSDimitry Andric   // We use three iterators on the same cuIndices to fold in-situ:
471e8d8bef9SDimitry Andric   // (1) `foldBegin` is the first of a potential sequence of matching entries
472e8d8bef9SDimitry Andric   // (2) `foldEnd` is the first non-matching entry after `foldBegin`.
473e8d8bef9SDimitry Andric   // The semi-open interval [ foldBegin .. foldEnd ) contains a range
474e8d8bef9SDimitry Andric   // entries that can be folded into a single entry and written to ...
475e8d8bef9SDimitry Andric   // (3) `foldWrite`
476349cc55cSDimitry Andric   auto foldWrite = cuIndices.begin();
477349cc55cSDimitry Andric   for (auto foldBegin = cuIndices.begin(); foldBegin < cuIndices.end();) {
478e8d8bef9SDimitry Andric     auto foldEnd = foldBegin;
4796246ae0bSDimitry Andric     // Common LSDA encodings (e.g. for C++ and Objective-C) contain offsets from
4806246ae0bSDimitry Andric     // a base address. The base address is normally not contained directly in
4816246ae0bSDimitry Andric     // the LSDA, and in that case, the personality function treats the starting
4826246ae0bSDimitry Andric     // address of the function (which is computed by the unwinder) as the base
4836246ae0bSDimitry Andric     // address and interprets the LSDA accordingly. The unwinder computes the
4846246ae0bSDimitry Andric     // starting address of a function as the address associated with its CU
4856246ae0bSDimitry Andric     // entry. For this reason, we cannot fold adjacent entries if they have an
4866246ae0bSDimitry Andric     // LSDA, because folding would make the unwinder compute the wrong starting
4876246ae0bSDimitry Andric     // address for the functions with the folded entries, which in turn would
4886246ae0bSDimitry Andric     // cause the personality function to misinterpret the LSDA for those
4896246ae0bSDimitry Andric     // functions. In the very rare case where the base address is encoded
4906246ae0bSDimitry Andric     // directly in the LSDA, two functions at different addresses would
4916246ae0bSDimitry Andric     // necessarily have different LSDAs, so their CU entries would not have been
4926246ae0bSDimitry Andric     // folded anyway.
493349cc55cSDimitry Andric     while (++foldEnd < cuIndices.end() &&
494349cc55cSDimitry Andric            cuEntries[*foldBegin].encoding == cuEntries[*foldEnd].encoding &&
4956246ae0bSDimitry Andric            !cuEntries[*foldBegin].lsda && !cuEntries[*foldEnd].lsda &&
4966246ae0bSDimitry Andric            // If we've gotten to this point, we don't have an LSDA, which should
4976246ae0bSDimitry Andric            // also imply that we don't have a personality function, since in all
4986246ae0bSDimitry Andric            // likelihood a personality function needs the LSDA to do anything
4996246ae0bSDimitry Andric            // useful. It can be technically valid to have a personality function
5006246ae0bSDimitry Andric            // and no LSDA though (e.g. the C++ personality __gxx_personality_v0
5016246ae0bSDimitry Andric            // is just a no-op without LSDA), so we still check for personality
5026246ae0bSDimitry Andric            // function equivalence to handle that case.
503349cc55cSDimitry Andric            cuEntries[*foldBegin].personality ==
504349cc55cSDimitry Andric                cuEntries[*foldEnd].personality &&
50581ad6265SDimitry Andric            canFoldEncoding(cuEntries[*foldEnd].encoding))
50681ad6265SDimitry Andric       ;
507e8d8bef9SDimitry Andric     *foldWrite++ = *foldBegin;
508e8d8bef9SDimitry Andric     foldBegin = foldEnd;
509e8d8bef9SDimitry Andric   }
510349cc55cSDimitry Andric   cuIndices.erase(foldWrite, cuIndices.end());
511e8d8bef9SDimitry Andric 
512349cc55cSDimitry Andric   encodePersonalities();
513fe6060f1SDimitry Andric 
514e8d8bef9SDimitry Andric   // Count frequencies of the folded encodings
515e8d8bef9SDimitry Andric   EncodingMap encodingFrequencies;
516349cc55cSDimitry Andric   for (size_t idx : cuIndices)
517349cc55cSDimitry Andric     encodingFrequencies[cuEntries[idx].encoding]++;
518e8d8bef9SDimitry Andric 
519e8d8bef9SDimitry Andric   // Make a vector of encodings, sorted by descending frequency
520e8d8bef9SDimitry Andric   for (const auto &frequency : encodingFrequencies)
521e8d8bef9SDimitry Andric     commonEncodings.emplace_back(frequency);
522fe6060f1SDimitry Andric   llvm::sort(commonEncodings,
523e8d8bef9SDimitry Andric              [](const std::pair<compact_unwind_encoding_t, size_t> &a,
524e8d8bef9SDimitry Andric                 const std::pair<compact_unwind_encoding_t, size_t> &b) {
525e8d8bef9SDimitry Andric                if (a.second == b.second)
526e8d8bef9SDimitry Andric                  // When frequencies match, secondarily sort on encoding
527e8d8bef9SDimitry Andric                  // to maintain parity with validate-unwind-info.py
528e8d8bef9SDimitry Andric                  return a.first > b.first;
529e8d8bef9SDimitry Andric                return a.second > b.second;
530e8d8bef9SDimitry Andric              });
531e8d8bef9SDimitry Andric 
532e8d8bef9SDimitry Andric   // Truncate the vector to 127 elements.
533e8d8bef9SDimitry Andric   // Common encoding indexes are limited to 0..126, while encoding
534e8d8bef9SDimitry Andric   // indexes 127..255 are local to each second-level page
535e8d8bef9SDimitry Andric   if (commonEncodings.size() > COMMON_ENCODINGS_MAX)
536e8d8bef9SDimitry Andric     commonEncodings.resize(COMMON_ENCODINGS_MAX);
537e8d8bef9SDimitry Andric 
538e8d8bef9SDimitry Andric   // Create a map from encoding to common-encoding-table index
539e8d8bef9SDimitry Andric   for (size_t i = 0; i < commonEncodings.size(); i++)
540e8d8bef9SDimitry Andric     commonEncodingIndexes[commonEncodings[i].first] = i;
541e8d8bef9SDimitry Andric 
542e8d8bef9SDimitry Andric   // Split folded encodings into pages, where each page is limited by ...
543e8d8bef9SDimitry Andric   // (a) 4 KiB capacity
544e8d8bef9SDimitry Andric   // (b) 24-bit difference between first & final function address
545e8d8bef9SDimitry Andric   // (c) 8-bit compact-encoding-table index,
546e8d8bef9SDimitry Andric   //     for which 0..126 references the global common-encodings table,
547e8d8bef9SDimitry Andric   //     and 127..255 references a local per-second-level-page table.
548e8d8bef9SDimitry Andric   // First we try the compact format and determine how many entries fit.
549e8d8bef9SDimitry Andric   // If more entries fit in the regular format, we use that.
550349cc55cSDimitry Andric   for (size_t i = 0; i < cuIndices.size();) {
551349cc55cSDimitry Andric     size_t idx = cuIndices[i];
552e8d8bef9SDimitry Andric     secondLevelPages.emplace_back();
553fe6060f1SDimitry Andric     SecondLevelPage &page = secondLevelPages.back();
554e8d8bef9SDimitry Andric     page.entryIndex = i;
555753f127fSDimitry Andric     uint64_t functionAddressMax =
556349cc55cSDimitry Andric         cuEntries[idx].functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK;
557e8d8bef9SDimitry Andric     size_t n = commonEncodings.size();
558e8d8bef9SDimitry Andric     size_t wordsRemaining =
559e8d8bef9SDimitry Andric         SECOND_LEVEL_PAGE_WORDS -
560e8d8bef9SDimitry Andric         sizeof(unwind_info_compressed_second_level_page_header) /
561e8d8bef9SDimitry Andric             sizeof(uint32_t);
562349cc55cSDimitry Andric     while (wordsRemaining >= 1 && i < cuIndices.size()) {
563349cc55cSDimitry Andric       idx = cuIndices[i];
56481ad6265SDimitry Andric       const CompactUnwindEntry *cuPtr = &cuEntries[idx];
565*06c3fb27SDimitry Andric       if (cuPtr->functionAddress >= functionAddressMax)
566e8d8bef9SDimitry Andric         break;
567*06c3fb27SDimitry Andric       if (commonEncodingIndexes.count(cuPtr->encoding) ||
568e8d8bef9SDimitry Andric           page.localEncodingIndexes.count(cuPtr->encoding)) {
569e8d8bef9SDimitry Andric         i++;
570e8d8bef9SDimitry Andric         wordsRemaining--;
571e8d8bef9SDimitry Andric       } else if (wordsRemaining >= 2 && n < COMPACT_ENCODINGS_MAX) {
572e8d8bef9SDimitry Andric         page.localEncodings.emplace_back(cuPtr->encoding);
573e8d8bef9SDimitry Andric         page.localEncodingIndexes[cuPtr->encoding] = n++;
574e8d8bef9SDimitry Andric         i++;
575e8d8bef9SDimitry Andric         wordsRemaining -= 2;
576e8d8bef9SDimitry Andric       } else {
577e8d8bef9SDimitry Andric         break;
578e8d8bef9SDimitry Andric       }
579e8d8bef9SDimitry Andric     }
580e8d8bef9SDimitry Andric     page.entryCount = i - page.entryIndex;
581e8d8bef9SDimitry Andric 
582bdd1243dSDimitry Andric     // If this is not the final page, see if it's possible to fit more entries
583bdd1243dSDimitry Andric     // by using the regular format. This can happen when there are many unique
584bdd1243dSDimitry Andric     // encodings, and we saturated the local encoding table early.
585349cc55cSDimitry Andric     if (i < cuIndices.size() &&
586e8d8bef9SDimitry Andric         page.entryCount < REGULAR_SECOND_LEVEL_ENTRIES_MAX) {
587e8d8bef9SDimitry Andric       page.kind = UNWIND_SECOND_LEVEL_REGULAR;
588e8d8bef9SDimitry Andric       page.entryCount = std::min(REGULAR_SECOND_LEVEL_ENTRIES_MAX,
589349cc55cSDimitry Andric                                  cuIndices.size() - page.entryIndex);
590e8d8bef9SDimitry Andric       i = page.entryIndex + page.entryCount;
591e8d8bef9SDimitry Andric     } else {
592e8d8bef9SDimitry Andric       page.kind = UNWIND_SECOND_LEVEL_COMPRESSED;
593e8d8bef9SDimitry Andric     }
594e8d8bef9SDimitry Andric   }
595e8d8bef9SDimitry Andric 
596349cc55cSDimitry Andric   for (size_t idx : cuIndices) {
597349cc55cSDimitry Andric     lsdaIndex[idx] = entriesWithLsda.size();
59881ad6265SDimitry Andric     if (cuEntries[idx].lsda)
599349cc55cSDimitry Andric       entriesWithLsda.push_back(idx);
600fe6060f1SDimitry Andric   }
601fe6060f1SDimitry Andric 
602e8d8bef9SDimitry Andric   // compute size of __TEXT,__unwind_info section
603349cc55cSDimitry Andric   level2PagesOffset = sizeof(unwind_info_section_header) +
604e8d8bef9SDimitry Andric                       commonEncodings.size() * sizeof(uint32_t) +
605e8d8bef9SDimitry Andric                       personalities.size() * sizeof(uint32_t) +
606e8d8bef9SDimitry Andric                       // The extra second-level-page entry is for the sentinel
607e8d8bef9SDimitry Andric                       (secondLevelPages.size() + 1) *
608e8d8bef9SDimitry Andric                           sizeof(unwind_info_section_header_index_entry) +
609349cc55cSDimitry Andric                       entriesWithLsda.size() *
610349cc55cSDimitry Andric                           sizeof(unwind_info_section_header_lsda_index_entry);
611e8d8bef9SDimitry Andric   unwindInfoSize =
612e8d8bef9SDimitry Andric       level2PagesOffset + secondLevelPages.size() * SECOND_LEVEL_PAGE_BYTES;
613e8d8bef9SDimitry Andric }
614e8d8bef9SDimitry Andric 
615e8d8bef9SDimitry Andric // All inputs are relocated and output addresses are known, so write!
616e8d8bef9SDimitry Andric 
61781ad6265SDimitry Andric void UnwindInfoSectionImpl::writeTo(uint8_t *buf) const {
618349cc55cSDimitry Andric   assert(!cuIndices.empty() && "call only if there is unwind info");
619fe6060f1SDimitry Andric 
620e8d8bef9SDimitry Andric   // section header
621e8d8bef9SDimitry Andric   auto *uip = reinterpret_cast<unwind_info_section_header *>(buf);
622e8d8bef9SDimitry Andric   uip->version = 1;
623e8d8bef9SDimitry Andric   uip->commonEncodingsArraySectionOffset = sizeof(unwind_info_section_header);
624e8d8bef9SDimitry Andric   uip->commonEncodingsArrayCount = commonEncodings.size();
625e8d8bef9SDimitry Andric   uip->personalityArraySectionOffset =
626e8d8bef9SDimitry Andric       uip->commonEncodingsArraySectionOffset +
627e8d8bef9SDimitry Andric       (uip->commonEncodingsArrayCount * sizeof(uint32_t));
628e8d8bef9SDimitry Andric   uip->personalityArrayCount = personalities.size();
629e8d8bef9SDimitry Andric   uip->indexSectionOffset = uip->personalityArraySectionOffset +
630e8d8bef9SDimitry Andric                             (uip->personalityArrayCount * sizeof(uint32_t));
631e8d8bef9SDimitry Andric   uip->indexCount = secondLevelPages.size() + 1;
632e8d8bef9SDimitry Andric 
633e8d8bef9SDimitry Andric   // Common encodings
634e8d8bef9SDimitry Andric   auto *i32p = reinterpret_cast<uint32_t *>(&uip[1]);
635e8d8bef9SDimitry Andric   for (const auto &encoding : commonEncodings)
636e8d8bef9SDimitry Andric     *i32p++ = encoding.first;
637e8d8bef9SDimitry Andric 
638e8d8bef9SDimitry Andric   // Personalities
63981ad6265SDimitry Andric   for (const Symbol *personality : personalities)
64081ad6265SDimitry Andric     *i32p++ = personality->getGotVA() - in.header->addr;
641e8d8bef9SDimitry Andric 
642bdd1243dSDimitry Andric   // FIXME: LD64 checks and warns aboutgaps or overlapse in cuEntries address
643bdd1243dSDimitry Andric   // ranges. We should do the same too
644bdd1243dSDimitry Andric 
645e8d8bef9SDimitry Andric   // Level-1 index
646e8d8bef9SDimitry Andric   uint32_t lsdaOffset =
647e8d8bef9SDimitry Andric       uip->indexSectionOffset +
648e8d8bef9SDimitry Andric       uip->indexCount * sizeof(unwind_info_section_header_index_entry);
649e8d8bef9SDimitry Andric   uint64_t l2PagesOffset = level2PagesOffset;
650e8d8bef9SDimitry Andric   auto *iep = reinterpret_cast<unwind_info_section_header_index_entry *>(i32p);
651e8d8bef9SDimitry Andric   for (const SecondLevelPage &page : secondLevelPages) {
652349cc55cSDimitry Andric     size_t idx = cuIndices[page.entryIndex];
653349cc55cSDimitry Andric     iep->functionOffset = cuEntries[idx].functionAddress - in.header->addr;
654e8d8bef9SDimitry Andric     iep->secondLevelPagesSectionOffset = l2PagesOffset;
655fe6060f1SDimitry Andric     iep->lsdaIndexArraySectionOffset =
656349cc55cSDimitry Andric         lsdaOffset + lsdaIndex.lookup(idx) *
657fe6060f1SDimitry Andric                          sizeof(unwind_info_section_header_lsda_index_entry);
658e8d8bef9SDimitry Andric     iep++;
659e8d8bef9SDimitry Andric     l2PagesOffset += SECOND_LEVEL_PAGE_BYTES;
660e8d8bef9SDimitry Andric   }
661e8d8bef9SDimitry Andric   // Level-1 sentinel
662bdd1243dSDimitry Andric   // XXX(vyng): Note that LD64 adds +1 here.
663bdd1243dSDimitry Andric   // Unsure whether it's a bug or it's their workaround for something else.
664bdd1243dSDimitry Andric   // See comments from https://reviews.llvm.org/D138320.
665bdd1243dSDimitry Andric   iep->functionOffset = cueEndBoundary - in.header->addr;
666e8d8bef9SDimitry Andric   iep->secondLevelPagesSectionOffset = 0;
667fe6060f1SDimitry Andric   iep->lsdaIndexArraySectionOffset =
668349cc55cSDimitry Andric       lsdaOffset + entriesWithLsda.size() *
669349cc55cSDimitry Andric                        sizeof(unwind_info_section_header_lsda_index_entry);
670e8d8bef9SDimitry Andric   iep++;
671e8d8bef9SDimitry Andric 
672e8d8bef9SDimitry Andric   // LSDAs
673349cc55cSDimitry Andric   auto *lep =
674349cc55cSDimitry Andric       reinterpret_cast<unwind_info_section_header_lsda_index_entry *>(iep);
675349cc55cSDimitry Andric   for (size_t idx : entriesWithLsda) {
67681ad6265SDimitry Andric     const CompactUnwindEntry &cu = cuEntries[idx];
67781ad6265SDimitry Andric     lep->lsdaOffset = cu.lsda->getVA(/*off=*/0) - in.header->addr;
678349cc55cSDimitry Andric     lep->functionOffset = cu.functionAddress - in.header->addr;
679349cc55cSDimitry Andric     lep++;
680349cc55cSDimitry Andric   }
681e8d8bef9SDimitry Andric 
682e8d8bef9SDimitry Andric   // Level-2 pages
683349cc55cSDimitry Andric   auto *pp = reinterpret_cast<uint32_t *>(lep);
684e8d8bef9SDimitry Andric   for (const SecondLevelPage &page : secondLevelPages) {
685e8d8bef9SDimitry Andric     if (page.kind == UNWIND_SECOND_LEVEL_COMPRESSED) {
686e8d8bef9SDimitry Andric       uintptr_t functionAddressBase =
687349cc55cSDimitry Andric           cuEntries[cuIndices[page.entryIndex]].functionAddress;
688e8d8bef9SDimitry Andric       auto *p2p =
689e8d8bef9SDimitry Andric           reinterpret_cast<unwind_info_compressed_second_level_page_header *>(
690e8d8bef9SDimitry Andric               pp);
691e8d8bef9SDimitry Andric       p2p->kind = page.kind;
692e8d8bef9SDimitry Andric       p2p->entryPageOffset =
693e8d8bef9SDimitry Andric           sizeof(unwind_info_compressed_second_level_page_header);
694e8d8bef9SDimitry Andric       p2p->entryCount = page.entryCount;
695e8d8bef9SDimitry Andric       p2p->encodingsPageOffset =
696e8d8bef9SDimitry Andric           p2p->entryPageOffset + p2p->entryCount * sizeof(uint32_t);
697e8d8bef9SDimitry Andric       p2p->encodingsCount = page.localEncodings.size();
698e8d8bef9SDimitry Andric       auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]);
699e8d8bef9SDimitry Andric       for (size_t i = 0; i < page.entryCount; i++) {
70081ad6265SDimitry Andric         const CompactUnwindEntry &cue =
701349cc55cSDimitry Andric             cuEntries[cuIndices[page.entryIndex + i]];
702349cc55cSDimitry Andric         auto it = commonEncodingIndexes.find(cue.encoding);
703e8d8bef9SDimitry Andric         if (it == commonEncodingIndexes.end())
704349cc55cSDimitry Andric           it = page.localEncodingIndexes.find(cue.encoding);
705e8d8bef9SDimitry Andric         *ep++ = (it->second << COMPRESSED_ENTRY_FUNC_OFFSET_BITS) |
706349cc55cSDimitry Andric                 (cue.functionAddress - functionAddressBase);
707e8d8bef9SDimitry Andric       }
708349cc55cSDimitry Andric       if (!page.localEncodings.empty())
709e8d8bef9SDimitry Andric         memcpy(ep, page.localEncodings.data(),
710e8d8bef9SDimitry Andric                page.localEncodings.size() * sizeof(uint32_t));
711e8d8bef9SDimitry Andric     } else {
712e8d8bef9SDimitry Andric       auto *p2p =
713e8d8bef9SDimitry Andric           reinterpret_cast<unwind_info_regular_second_level_page_header *>(pp);
714e8d8bef9SDimitry Andric       p2p->kind = page.kind;
715e8d8bef9SDimitry Andric       p2p->entryPageOffset =
716e8d8bef9SDimitry Andric           sizeof(unwind_info_regular_second_level_page_header);
717e8d8bef9SDimitry Andric       p2p->entryCount = page.entryCount;
718e8d8bef9SDimitry Andric       auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]);
719e8d8bef9SDimitry Andric       for (size_t i = 0; i < page.entryCount; i++) {
72081ad6265SDimitry Andric         const CompactUnwindEntry &cue =
721349cc55cSDimitry Andric             cuEntries[cuIndices[page.entryIndex + i]];
722349cc55cSDimitry Andric         *ep++ = cue.functionAddress;
723349cc55cSDimitry Andric         *ep++ = cue.encoding;
724e8d8bef9SDimitry Andric       }
725e8d8bef9SDimitry Andric     }
726e8d8bef9SDimitry Andric     pp += SECOND_LEVEL_PAGE_WORDS;
727e8d8bef9SDimitry Andric   }
728e8d8bef9SDimitry Andric }
729fe6060f1SDimitry Andric 
730fe6060f1SDimitry Andric UnwindInfoSection *macho::makeUnwindInfoSection() {
73181ad6265SDimitry Andric   return make<UnwindInfoSectionImpl>();
732fe6060f1SDimitry Andric }
733