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