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 "Symbols.h"
16 #include "SyntheticSections.h"
17 #include "Target.h"
18
19 #include "lld/Common/ErrorHandler.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/BinaryFormat/MachO.h"
22
23 using namespace llvm;
24 using namespace llvm::MachO;
25 using namespace lld;
26 using namespace lld::macho;
27
28 // Compact Unwind format is a Mach-O evolution of DWARF Unwind that
29 // optimizes space and exception-time lookup. Most DWARF unwind
30 // entries can be replaced with Compact Unwind entries, but the ones
31 // that cannot are retained in DWARF form.
32 //
33 // This comment will address macro-level organization of the pre-link
34 // and post-link compact unwind tables. For micro-level organization
35 // pertaining to the bitfield layout of the 32-bit compact unwind
36 // entries, see libunwind/include/mach-o/compact_unwind_encoding.h
37 //
38 // Important clarifying factoids:
39 //
40 // * __LD,__compact_unwind is the compact unwind format for compiler
41 // output and linker input. It is never a final output. It could be
42 // an intermediate output with the `-r` option which retains relocs.
43 //
44 // * __TEXT,__unwind_info is the compact unwind format for final
45 // linker output. It is never an input.
46 //
47 // * __TEXT,__eh_frame is the DWARF format for both linker input and output.
48 //
49 // * __TEXT,__unwind_info entries are divided into 4 KiB pages (2nd
50 // level) by ascending address, and the pages are referenced by an
51 // index (1st level) in the section header.
52 //
53 // * Following the headers in __TEXT,__unwind_info, the bulk of the
54 // section contains a vector of compact unwind entries
55 // `{functionOffset, encoding}` sorted by ascending `functionOffset`.
56 // Adjacent entries with the same encoding can be folded to great
57 // advantage, achieving a 3-order-of-magnitude reduction in the
58 // number of entries.
59 //
60 // * The __TEXT,__unwind_info format can accommodate up to 127 unique
61 // encodings for the space-efficient compressed format. In practice,
62 // fewer than a dozen unique encodings are used by C++ programs of
63 // all sizes. Therefore, we don't even bother implementing the regular
64 // non-compressed format. Time will tell if anyone in the field ever
65 // overflows the 127-encodings limit.
66
67 // TODO(gkm): prune __eh_frame entries superseded by __unwind_info
68 // TODO(gkm): how do we align the 2nd-level pages?
69
UnwindInfoSection()70 UnwindInfoSection::UnwindInfoSection()
71 : SyntheticSection(segment_names::text, section_names::unwindInfo) {
72 align = WordSize; // TODO(gkm): make this 4 KiB ?
73 }
74
isNeeded() const75 bool UnwindInfoSection::isNeeded() const {
76 return (compactUnwindSection != nullptr);
77 }
78
79 // Scan the __LD,__compact_unwind entries and compute the space needs of
80 // __TEXT,__unwind_info and __TEXT,__eh_frame
81
finalize()82 void UnwindInfoSection::finalize() {
83 if (compactUnwindSection == nullptr)
84 return;
85
86 // At this point, the address space for __TEXT,__text has been
87 // assigned, so we can relocate the __LD,__compact_unwind entries
88 // into a temporary buffer. Relocation is necessary in order to sort
89 // the CU entries by function address. Sorting is necessary so that
90 // we can fold adjacent CU entries with identical
91 // encoding+personality+lsda. Folding is necessary because it reduces
92 // the number of CU entries by as much as 3 orders of magnitude!
93 compactUnwindSection->finalize();
94 assert(compactUnwindSection->getSize() % sizeof(CompactUnwindEntry64) == 0);
95 size_t cuCount =
96 compactUnwindSection->getSize() / sizeof(CompactUnwindEntry64);
97 cuVector.resize(cuCount);
98 // Relocate all __LD,__compact_unwind entries
99 compactUnwindSection->writeTo(reinterpret_cast<uint8_t *>(cuVector.data()));
100
101 // Rather than sort & fold the 32-byte entries directly, we create a
102 // vector of pointers to entries and sort & fold that instead.
103 cuPtrVector.reserve(cuCount);
104 for (const auto &cuEntry : cuVector)
105 cuPtrVector.emplace_back(&cuEntry);
106 std::sort(cuPtrVector.begin(), cuPtrVector.end(),
107 [](const CompactUnwindEntry64 *a, const CompactUnwindEntry64 *b) {
108 return a->functionAddress < b->functionAddress;
109 });
110
111 // Fold adjacent entries with matching encoding+personality+lsda
112 // We use three iterators on the same cuPtrVector to fold in-situ:
113 // (1) `foldBegin` is the first of a potential sequence of matching entries
114 // (2) `foldEnd` is the first non-matching entry after `foldBegin`.
115 // The semi-open interval [ foldBegin .. foldEnd ) contains a range
116 // entries that can be folded into a single entry and written to ...
117 // (3) `foldWrite`
118 auto foldWrite = cuPtrVector.begin();
119 for (auto foldBegin = cuPtrVector.begin(); foldBegin < cuPtrVector.end();) {
120 auto foldEnd = foldBegin;
121 while (++foldEnd < cuPtrVector.end() &&
122 (*foldBegin)->encoding == (*foldEnd)->encoding &&
123 (*foldBegin)->personality == (*foldEnd)->personality &&
124 (*foldBegin)->lsda == (*foldEnd)->lsda)
125 ;
126 *foldWrite++ = *foldBegin;
127 foldBegin = foldEnd;
128 }
129 cuPtrVector.erase(foldWrite, cuPtrVector.end());
130
131 // Count frequencies of the folded encodings
132 llvm::DenseMap<compact_unwind_encoding_t, size_t> encodingFrequencies;
133 for (auto cuPtrEntry : cuPtrVector)
134 encodingFrequencies[cuPtrEntry->encoding]++;
135 if (encodingFrequencies.size() > UNWIND_INFO_COMMON_ENCODINGS_MAX)
136 error("TODO(gkm): handle common encodings table overflow");
137
138 // Make a table of encodings, sorted by descending frequency
139 for (const auto &frequency : encodingFrequencies)
140 commonEncodings.emplace_back(frequency);
141 std::sort(commonEncodings.begin(), commonEncodings.end(),
142 [](const std::pair<compact_unwind_encoding_t, size_t> &a,
143 const std::pair<compact_unwind_encoding_t, size_t> &b) {
144 if (a.second == b.second)
145 // When frequencies match, secondarily sort on encoding
146 // to maintain parity with validate-unwind-info.py
147 return a.first > b.first;
148 return a.second > b.second;
149 });
150
151 // Split folded encodings into pages, limited by capacity of a page
152 // and the 24-bit range of function offset
153 //
154 // Record the page splits as a vector of iterators on cuPtrVector
155 // such that successive elements form a semi-open interval. E.g.,
156 // page X's bounds are thus: [ pageBounds[X] .. pageBounds[X+1] )
157 //
158 // Note that pageBounds.size() is one greater than the number of
159 // pages, and pageBounds.back() holds the sentinel cuPtrVector.cend()
160 pageBounds.push_back(cuPtrVector.cbegin());
161 // TODO(gkm): cut 1st page entries short to accommodate section headers ???
162 CompactUnwindEntry64 cuEntryKey;
163 for (size_t i = 0;;) {
164 // Limit the search to entries that can fit within a 4 KiB page.
165 const auto pageBegin = pageBounds[0] + i;
166 const auto pageMax =
167 pageBounds[0] +
168 std::min(i + UNWIND_INFO_COMPRESSED_SECOND_LEVEL_ENTRIES_MAX,
169 cuPtrVector.size());
170 // Exclude entries with functionOffset that would overflow 24 bits
171 cuEntryKey.functionAddress = (*pageBegin)->functionAddress +
172 UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET_MASK;
173 const auto pageBreak = std::lower_bound(
174 pageBegin, pageMax, &cuEntryKey,
175 [](const CompactUnwindEntry64 *a, const CompactUnwindEntry64 *b) {
176 return a->functionAddress < b->functionAddress;
177 });
178 pageBounds.push_back(pageBreak);
179 if (pageBreak == cuPtrVector.cend())
180 break;
181 i = pageBreak - cuPtrVector.cbegin();
182 }
183
184 // compute size of __TEXT,__unwind_info section
185 level2PagesOffset =
186 sizeof(unwind_info_section_header) +
187 commonEncodings.size() * sizeof(uint32_t) +
188 personalities.size() * sizeof(uint32_t) +
189 pageBounds.size() * sizeof(unwind_info_section_header_index_entry) +
190 lsdaEntries.size() * sizeof(unwind_info_section_header_lsda_index_entry);
191 unwindInfoSize = level2PagesOffset +
192 (pageBounds.size() - 1) *
193 sizeof(unwind_info_compressed_second_level_page_header) +
194 cuPtrVector.size() * sizeof(uint32_t);
195 }
196
197 // All inputs are relocated and output addresses are known, so write!
198
writeTo(uint8_t * buf) const199 void UnwindInfoSection::writeTo(uint8_t *buf) const {
200 // section header
201 auto *uip = reinterpret_cast<unwind_info_section_header *>(buf);
202 uip->version = 1;
203 uip->commonEncodingsArraySectionOffset = sizeof(unwind_info_section_header);
204 uip->commonEncodingsArrayCount = commonEncodings.size();
205 uip->personalityArraySectionOffset =
206 uip->commonEncodingsArraySectionOffset +
207 (uip->commonEncodingsArrayCount * sizeof(uint32_t));
208 uip->personalityArrayCount = personalities.size();
209 uip->indexSectionOffset = uip->personalityArraySectionOffset +
210 (uip->personalityArrayCount * sizeof(uint32_t));
211 uip->indexCount = pageBounds.size();
212
213 // Common encodings
214 auto *i32p = reinterpret_cast<uint32_t *>(&uip[1]);
215 for (const auto &encoding : commonEncodings)
216 *i32p++ = encoding.first;
217
218 // Personalities
219 for (const auto &personality : personalities)
220 *i32p++ = personality;
221
222 // Level-1 index
223 uint32_t lsdaOffset =
224 uip->indexSectionOffset +
225 uip->indexCount * sizeof(unwind_info_section_header_index_entry);
226 uint64_t l2PagesOffset = level2PagesOffset;
227 auto *iep = reinterpret_cast<unwind_info_section_header_index_entry *>(i32p);
228 for (size_t i = 0; i < pageBounds.size() - 1; i++) {
229 iep->functionOffset = (*pageBounds[i])->functionAddress;
230 iep->secondLevelPagesSectionOffset = l2PagesOffset;
231 iep->lsdaIndexArraySectionOffset = lsdaOffset;
232 iep++;
233 // TODO(gkm): pad to 4 KiB page boundary ???
234 size_t entryCount = pageBounds[i + 1] - pageBounds[i];
235 uint64_t pageSize = sizeof(unwind_info_section_header_index_entry) +
236 entryCount * sizeof(uint32_t);
237 l2PagesOffset += pageSize;
238 }
239 // Level-1 sentinel
240 const CompactUnwindEntry64 &cuEnd = cuVector.back();
241 iep->functionOffset = cuEnd.functionAddress + cuEnd.functionLength;
242 iep->secondLevelPagesSectionOffset = 0;
243 iep->lsdaIndexArraySectionOffset = lsdaOffset;
244 iep++;
245
246 // LSDAs
247 auto *lep =
248 reinterpret_cast<unwind_info_section_header_lsda_index_entry *>(iep);
249 for (const auto &lsda : lsdaEntries) {
250 lep->functionOffset = lsda.functionOffset;
251 lep->lsdaOffset = lsda.lsdaOffset;
252 }
253
254 // create map from encoding to common-encoding-table index compact
255 // encoding entries use 7 bits to index the common-encoding table
256 size_t i = 0;
257 llvm::DenseMap<compact_unwind_encoding_t, size_t> commonEncodingIndexes;
258 for (const auto &encoding : commonEncodings)
259 commonEncodingIndexes[encoding.first] = i++;
260
261 // Level-2 pages
262 auto *p2p =
263 reinterpret_cast<unwind_info_compressed_second_level_page_header *>(lep);
264 for (size_t i = 0; i < pageBounds.size() - 1; i++) {
265 p2p->kind = UNWIND_SECOND_LEVEL_COMPRESSED;
266 p2p->entryPageOffset =
267 sizeof(unwind_info_compressed_second_level_page_header);
268 p2p->entryCount = pageBounds[i + 1] - pageBounds[i];
269 p2p->encodingsPageOffset =
270 p2p->entryPageOffset + p2p->entryCount * sizeof(uint32_t);
271 p2p->encodingsCount = 0;
272 auto *ep = reinterpret_cast<uint32_t *>(&p2p[1]);
273 auto cuPtrVectorIt = pageBounds[i];
274 uintptr_t functionAddressBase = (*cuPtrVectorIt)->functionAddress;
275 while (cuPtrVectorIt < pageBounds[i + 1]) {
276 const CompactUnwindEntry64 *cuep = *cuPtrVectorIt++;
277 size_t cueIndex = commonEncodingIndexes.lookup(cuep->encoding);
278 *ep++ = ((cueIndex << UNWIND_INFO_COMPRESSED_ENTRY_FUNC_OFFSET_BITS) |
279 (cuep->functionAddress - functionAddressBase));
280 }
281 p2p =
282 reinterpret_cast<unwind_info_compressed_second_level_page_header *>(ep);
283 }
284 assert(getSize() ==
285 static_cast<size_t>((reinterpret_cast<uint8_t *>(p2p) - buf)));
286 }
287