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 UnwindInfoSection::UnwindInfoSection()
95     : SyntheticSection(segment_names::text, section_names::unwindInfo) {
96   align = 4; // mimic ld64
97 }
98 
99 bool UnwindInfoSection::isNeeded() const {
100   return (compactUnwindSection != nullptr);
101 }
102 
103 // Compact unwind relocations have different semantics, so we handle them in a
104 // separate code path from regular relocations. First, we do not wish to add
105 // rebase opcodes for __LD,__compact_unwind, because that section doesn't
106 // actually end up in the final binary. Second, personality pointers always
107 // reside in the GOT and must be treated specially.
108 void macho::prepareCompactUnwind(InputSection *isec) {
109   assert(isec->segname == segment_names::ld &&
110          isec->name == section_names::compactUnwind);
111 
112   DenseMap<std::pair<InputSection *, uint64_t /* addend */>, macho::Symbol *>
113       anonPersonalitySymbols;
114   for (Reloc &r : isec->relocs) {
115     // TODO: generalize for other archs
116     assert(r.type == X86_64_RELOC_UNSIGNED);
117     if (r.offset % sizeof(CompactUnwindEntry64) !=
118         offsetof(struct CompactUnwindEntry64, personality))
119       continue;
120 
121     if (auto *s = r.referent.dyn_cast<lld::macho::Symbol *>()) {
122       if (auto *undefined = dyn_cast<Undefined>(s))
123         treatUndefinedSymbol(*undefined);
124       else
125         in.got->addEntry(s);
126     } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
127       // Personality functions can be referenced via section relocations
128       // if they live in an object file (instead of a dylib). Create
129       // placeholder synthetic symbols for them in the GOT.
130       macho::Symbol *&s = anonPersonalitySymbols[{referentIsec, r.addend}];
131       if (s == nullptr) {
132         s = make<Defined>("<internal>", nullptr, referentIsec, r.addend, false,
133                           false, false);
134         in.got->addEntry(s);
135       }
136       r.referent = s;
137       r.addend = 0;
138     }
139   }
140 }
141 
142 // Unwind info lives in __DATA, and finalization of __TEXT will occur before
143 // finalization of __DATA. Moreover, the finalization of unwind info depends on
144 // the exact addresses that it references. So it is safe for compact unwind to
145 // reference addresses in __TEXT, but not addresses in any other segment.
146 static void checkTextSegment(InputSection *isec) {
147   if (isec->segname != segment_names::text)
148     error("compact unwind references address in " + toString(isec) +
149           " which is not in segment __TEXT");
150 }
151 
152 // We need to apply the relocations to the pre-link compact unwind section
153 // before converting it to post-link form. There should only be absolute
154 // relocations here: since we are not emitting the pre-link CU section, there
155 // is no source address to make a relative location meaningful.
156 static void relocateCompactUnwind(MergedOutputSection *compactUnwindSection,
157                                   std::vector<CompactUnwindEntry64> &cuVector) {
158   for (InputSection *isec : compactUnwindSection->inputs) {
159     uint8_t *buf =
160         reinterpret_cast<uint8_t *>(cuVector.data()) + isec->outSecFileOff;
161     memcpy(buf, isec->data.data(), isec->data.size());
162 
163     for (Reloc &r : isec->relocs) {
164       uint64_t referentVA = 0;
165       if (auto *referentSym = r.referent.dyn_cast<macho::Symbol *>()) {
166         if (!isa<Undefined>(referentSym)) {
167           assert(referentSym->isInGot());
168           if (auto *defined = dyn_cast<Defined>(referentSym))
169             checkTextSegment(defined->isec);
170           // At this point in the link, we may not yet know the final address of
171           // the GOT, so we just encode the index. We make it a 1-based index so
172           // that we can distinguish the null pointer case.
173           referentVA = referentSym->gotIndex + 1;
174         }
175       } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
176         checkTextSegment(referentIsec);
177         referentVA = referentIsec->getVA() + r.addend;
178       }
179       support::endian::write64le(buf + r.offset, referentVA);
180     }
181   }
182 }
183 
184 // There should only be a handful of unique personality pointers, so we can
185 // encode them as 2-bit indices into a small array.
186 void encodePersonalities(const std::vector<CompactUnwindEntry64 *> &cuPtrVector,
187                          std::vector<uint32_t> &personalities) {
188   for (CompactUnwindEntry64 *cu : cuPtrVector) {
189     if (cu->personality == 0)
190       continue;
191     uint32_t personalityOffset = cu->personality - in.header->addr;
192     // Linear search is fast enough for a small array.
193     auto it = find(personalities, personalityOffset);
194     uint32_t personalityIndex; // 1-based index
195     if (it != personalities.end()) {
196       personalityIndex = std::distance(personalities.begin(), it) + 1;
197     } else {
198       personalities.push_back(cu->personality);
199       personalityIndex = personalities.size();
200     }
201     cu->encoding |=
202         personalityIndex << countTrailingZeros(
203             static_cast<compact_unwind_encoding_t>(UNWIND_PERSONALITY_MASK));
204   }
205   if (personalities.size() > 3)
206     error("too many personalities (" + std::to_string(personalities.size()) +
207           ") for compact unwind to encode");
208 }
209 
210 // Scan the __LD,__compact_unwind entries and compute the space needs of
211 // __TEXT,__unwind_info and __TEXT,__eh_frame
212 void UnwindInfoSection::finalize() {
213   if (compactUnwindSection == nullptr)
214     return;
215 
216   // At this point, the address space for __TEXT,__text has been
217   // assigned, so we can relocate the __LD,__compact_unwind entries
218   // into a temporary buffer. Relocation is necessary in order to sort
219   // the CU entries by function address. Sorting is necessary so that
220   // we can fold adjacent CU entries with identical
221   // encoding+personality+lsda. Folding is necessary because it reduces
222   // the number of CU entries by as much as 3 orders of magnitude!
223   compactUnwindSection->finalize();
224   assert(compactUnwindSection->getSize() % sizeof(CompactUnwindEntry64) == 0);
225   size_t cuCount =
226       compactUnwindSection->getSize() / sizeof(CompactUnwindEntry64);
227   cuVector.resize(cuCount);
228   // Relocate all __LD,__compact_unwind entries
229   relocateCompactUnwind(compactUnwindSection, cuVector);
230 
231   // Rather than sort & fold the 32-byte entries directly, we create a
232   // vector of pointers to entries and sort & fold that instead.
233   cuPtrVector.reserve(cuCount);
234   for (CompactUnwindEntry64 &cuEntry : cuVector)
235     cuPtrVector.emplace_back(&cuEntry);
236   std::sort(cuPtrVector.begin(), cuPtrVector.end(),
237             [](const CompactUnwindEntry64 *a, const CompactUnwindEntry64 *b) {
238               return a->functionAddress < b->functionAddress;
239             });
240 
241   // Fold adjacent entries with matching encoding+personality+lsda
242   // We use three iterators on the same cuPtrVector to fold in-situ:
243   // (1) `foldBegin` is the first of a potential sequence of matching entries
244   // (2) `foldEnd` is the first non-matching entry after `foldBegin`.
245   // The semi-open interval [ foldBegin .. foldEnd ) contains a range
246   // entries that can be folded into a single entry and written to ...
247   // (3) `foldWrite`
248   auto foldWrite = cuPtrVector.begin();
249   for (auto foldBegin = cuPtrVector.begin(); foldBegin < cuPtrVector.end();) {
250     auto foldEnd = foldBegin;
251     while (++foldEnd < cuPtrVector.end() &&
252            (*foldBegin)->encoding == (*foldEnd)->encoding &&
253            (*foldBegin)->personality == (*foldEnd)->personality &&
254            (*foldBegin)->lsda == (*foldEnd)->lsda)
255       ;
256     *foldWrite++ = *foldBegin;
257     foldBegin = foldEnd;
258   }
259   cuPtrVector.erase(foldWrite, cuPtrVector.end());
260 
261   encodePersonalities(cuPtrVector, personalities);
262 
263   // Count frequencies of the folded encodings
264   EncodingMap encodingFrequencies;
265   for (auto cuPtrEntry : cuPtrVector)
266     encodingFrequencies[cuPtrEntry->encoding]++;
267 
268   // Make a vector of encodings, sorted by descending frequency
269   for (const auto &frequency : encodingFrequencies)
270     commonEncodings.emplace_back(frequency);
271   std::sort(commonEncodings.begin(), commonEncodings.end(),
272             [](const std::pair<compact_unwind_encoding_t, size_t> &a,
273                const std::pair<compact_unwind_encoding_t, size_t> &b) {
274               if (a.second == b.second)
275                 // When frequencies match, secondarily sort on encoding
276                 // to maintain parity with validate-unwind-info.py
277                 return a.first > b.first;
278               return a.second > b.second;
279             });
280 
281   // Truncate the vector to 127 elements.
282   // Common encoding indexes are limited to 0..126, while encoding
283   // indexes 127..255 are local to each second-level page
284   if (commonEncodings.size() > COMMON_ENCODINGS_MAX)
285     commonEncodings.resize(COMMON_ENCODINGS_MAX);
286 
287   // Create a map from encoding to common-encoding-table index
288   for (size_t i = 0; i < commonEncodings.size(); i++)
289     commonEncodingIndexes[commonEncodings[i].first] = i;
290 
291   // Split folded encodings into pages, where each page is limited by ...
292   // (a) 4 KiB capacity
293   // (b) 24-bit difference between first & final function address
294   // (c) 8-bit compact-encoding-table index,
295   //     for which 0..126 references the global common-encodings table,
296   //     and 127..255 references a local per-second-level-page table.
297   // First we try the compact format and determine how many entries fit.
298   // If more entries fit in the regular format, we use that.
299   for (size_t i = 0; i < cuPtrVector.size();) {
300     secondLevelPages.emplace_back();
301     auto &page = secondLevelPages.back();
302     page.entryIndex = i;
303     uintptr_t functionAddressMax =
304         cuPtrVector[i]->functionAddress + COMPRESSED_ENTRY_FUNC_OFFSET_MASK;
305     size_t n = commonEncodings.size();
306     size_t wordsRemaining =
307         SECOND_LEVEL_PAGE_WORDS -
308         sizeof(unwind_info_compressed_second_level_page_header) /
309             sizeof(uint32_t);
310     while (wordsRemaining >= 1 && i < cuPtrVector.size()) {
311       const auto *cuPtr = cuPtrVector[i];
312       if (cuPtr->functionAddress >= functionAddressMax) {
313         break;
314       } else if (commonEncodingIndexes.count(cuPtr->encoding) ||
315                  page.localEncodingIndexes.count(cuPtr->encoding)) {
316         i++;
317         wordsRemaining--;
318       } else if (wordsRemaining >= 2 && n < COMPACT_ENCODINGS_MAX) {
319         page.localEncodings.emplace_back(cuPtr->encoding);
320         page.localEncodingIndexes[cuPtr->encoding] = n++;
321         i++;
322         wordsRemaining -= 2;
323       } else {
324         break;
325       }
326     }
327     page.entryCount = i - page.entryIndex;
328 
329     // If this is not the final page, see if it's possible to fit more
330     // entries by using the regular format. This can happen when there
331     // are many unique encodings, and we we saturated the local
332     // encoding table early.
333     if (i < cuPtrVector.size() &&
334         page.entryCount < REGULAR_SECOND_LEVEL_ENTRIES_MAX) {
335       page.kind = UNWIND_SECOND_LEVEL_REGULAR;
336       page.entryCount = std::min(REGULAR_SECOND_LEVEL_ENTRIES_MAX,
337                                  cuPtrVector.size() - page.entryIndex);
338       i = page.entryIndex + page.entryCount;
339     } else {
340       page.kind = UNWIND_SECOND_LEVEL_COMPRESSED;
341     }
342   }
343 
344   for (const CompactUnwindEntry64 *cu : cuPtrVector) {
345     uint32_t functionOffset = cu->functionAddress - in.header->addr;
346     functionToLsdaIndex[functionOffset] = lsdaEntries.size();
347     if (cu->lsda != 0)
348       lsdaEntries.push_back(
349           {functionOffset, static_cast<uint32_t>(cu->lsda - in.header->addr)});
350   }
351 
352   // compute size of __TEXT,__unwind_info section
353   level2PagesOffset =
354       sizeof(unwind_info_section_header) +
355       commonEncodings.size() * sizeof(uint32_t) +
356       personalities.size() * sizeof(uint32_t) +
357       // The extra second-level-page entry is for the sentinel
358       (secondLevelPages.size() + 1) *
359           sizeof(unwind_info_section_header_index_entry) +
360       lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry);
361   unwindInfoSize =
362       level2PagesOffset + secondLevelPages.size() * SECOND_LEVEL_PAGE_BYTES;
363 }
364 
365 // All inputs are relocated and output addresses are known, so write!
366 
367 void UnwindInfoSection::writeTo(uint8_t *buf) const {
368   // section header
369   auto *uip = reinterpret_cast<unwind_info_section_header *>(buf);
370   uip->version = 1;
371   uip->commonEncodingsArraySectionOffset = sizeof(unwind_info_section_header);
372   uip->commonEncodingsArrayCount = commonEncodings.size();
373   uip->personalityArraySectionOffset =
374       uip->commonEncodingsArraySectionOffset +
375       (uip->commonEncodingsArrayCount * sizeof(uint32_t));
376   uip->personalityArrayCount = personalities.size();
377   uip->indexSectionOffset = uip->personalityArraySectionOffset +
378                             (uip->personalityArrayCount * sizeof(uint32_t));
379   uip->indexCount = secondLevelPages.size() + 1;
380 
381   // Common encodings
382   auto *i32p = reinterpret_cast<uint32_t *>(&uip[1]);
383   for (const auto &encoding : commonEncodings)
384     *i32p++ = encoding.first;
385 
386   // Personalities
387   for (const uint32_t &personality : personalities)
388     *i32p++ = in.got->addr + (personality - 1) * WordSize;
389 
390   // Level-1 index
391   uint32_t lsdaOffset =
392       uip->indexSectionOffset +
393       uip->indexCount * sizeof(unwind_info_section_header_index_entry);
394   uint64_t l2PagesOffset = level2PagesOffset;
395   auto *iep = reinterpret_cast<unwind_info_section_header_index_entry *>(i32p);
396   for (const SecondLevelPage &page : secondLevelPages) {
397     iep->functionOffset =
398         cuPtrVector[page.entryIndex]->functionAddress - in.header->addr;
399     iep->secondLevelPagesSectionOffset = l2PagesOffset;
400     iep->lsdaIndexArraySectionOffset =
401         lsdaOffset + functionToLsdaIndex.lookup(iep->functionOffset) *
402                          sizeof(unwind_info_section_header_lsda_index_entry);
403     iep++;
404     l2PagesOffset += SECOND_LEVEL_PAGE_BYTES;
405   }
406   // Level-1 sentinel
407   const CompactUnwindEntry64 &cuEnd = cuVector.back();
408   iep->functionOffset = cuEnd.functionAddress + cuEnd.functionLength;
409   iep->secondLevelPagesSectionOffset = 0;
410   iep->lsdaIndexArraySectionOffset =
411       lsdaOffset +
412       lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry);
413   iep++;
414 
415   // LSDAs
416   size_t lsdaBytes =
417       lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry);
418   if (lsdaBytes > 0)
419     memcpy(iep, lsdaEntries.data(), lsdaBytes);
420 
421   // Level-2 pages
422   auto *pp = reinterpret_cast<uint32_t *>(reinterpret_cast<uint8_t *>(iep) +
423                                           lsdaBytes);
424   for (const SecondLevelPage &page : secondLevelPages) {
425     if (page.kind == UNWIND_SECOND_LEVEL_COMPRESSED) {
426       uintptr_t functionAddressBase =
427           cuPtrVector[page.entryIndex]->functionAddress;
428       auto *p2p =
429           reinterpret_cast<unwind_info_compressed_second_level_page_header *>(
430               pp);
431       p2p->kind = page.kind;
432       p2p->entryPageOffset =
433           sizeof(unwind_info_compressed_second_level_page_header);
434       p2p->entryCount = page.entryCount;
435       p2p->encodingsPageOffset =
436           p2p->entryPageOffset + p2p->entryCount * sizeof(uint32_t);
437       p2p->encodingsCount = page.localEncodings.size();
438       auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]);
439       for (size_t i = 0; i < page.entryCount; i++) {
440         const CompactUnwindEntry64 *cuep = cuPtrVector[page.entryIndex + i];
441         auto it = commonEncodingIndexes.find(cuep->encoding);
442         if (it == commonEncodingIndexes.end())
443           it = page.localEncodingIndexes.find(cuep->encoding);
444         *ep++ = (it->second << COMPRESSED_ENTRY_FUNC_OFFSET_BITS) |
445                 (cuep->functionAddress - functionAddressBase);
446       }
447       if (page.localEncodings.size() != 0)
448         memcpy(ep, page.localEncodings.data(),
449                page.localEncodings.size() * sizeof(uint32_t));
450     } else {
451       auto *p2p =
452           reinterpret_cast<unwind_info_regular_second_level_page_header *>(pp);
453       p2p->kind = page.kind;
454       p2p->entryPageOffset =
455           sizeof(unwind_info_regular_second_level_page_header);
456       p2p->entryCount = page.entryCount;
457       auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]);
458       for (size_t i = 0; i < page.entryCount; i++) {
459         const CompactUnwindEntry64 *cuep = cuPtrVector[page.entryIndex + i];
460         *ep++ = cuep->functionAddress;
461         *ep++ = cuep->encoding;
462       }
463     }
464     pp += SECOND_LEVEL_PAGE_WORDS;
465   }
466 }
467