1 //===- SyntheticSections.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 "SyntheticSections.h"
10 #include "Config.h"
11 #include "ExportTrie.h"
12 #include "InputFiles.h"
13 #include "OutputSegment.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "Writer.h"
17 
18 #include "lld/Common/ErrorHandler.h"
19 #include "llvm/Support/EndianStream.h"
20 #include "llvm/Support/LEB128.h"
21 
22 using namespace llvm;
23 using namespace llvm::MachO;
24 using namespace llvm::support;
25 using namespace llvm::support::endian;
26 
27 namespace lld {
28 namespace macho {
29 
30 SyntheticSection::SyntheticSection(const char *segname, const char *name)
31     : OutputSection(SyntheticKind, name) {
32   // Synthetic sections always know which segment they belong to so hook
33   // them up when they're made
34   getOrCreateOutputSegment(segname)->addOutputSection(this);
35 }
36 
37 // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
38 // from the beginning of the file (i.e. the header).
39 MachHeaderSection::MachHeaderSection()
40     : SyntheticSection(segment_names::text, section_names::header) {}
41 
42 void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
43   loadCommands.push_back(lc);
44   sizeOfCmds += lc->getSize();
45 }
46 
47 size_t MachHeaderSection::getSize() const {
48   return sizeof(mach_header_64) + sizeOfCmds;
49 }
50 
51 void MachHeaderSection::writeTo(uint8_t *buf) const {
52   auto *hdr = reinterpret_cast<mach_header_64 *>(buf);
53   hdr->magic = MH_MAGIC_64;
54   hdr->cputype = CPU_TYPE_X86_64;
55   hdr->cpusubtype = CPU_SUBTYPE_X86_64_ALL | CPU_SUBTYPE_LIB64;
56   hdr->filetype = config->outputType;
57   hdr->ncmds = loadCommands.size();
58   hdr->sizeofcmds = sizeOfCmds;
59   hdr->flags = MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL;
60   if (config->outputType == MH_DYLIB && !config->hasReexports)
61     hdr->flags |= MH_NO_REEXPORTED_DYLIBS;
62 
63   uint8_t *p = reinterpret_cast<uint8_t *>(hdr + 1);
64   for (LoadCommand *lc : loadCommands) {
65     lc->writeTo(p);
66     p += lc->getSize();
67   }
68 }
69 
70 PageZeroSection::PageZeroSection()
71     : SyntheticSection(segment_names::pageZero, section_names::pageZero) {}
72 
73 GotSection::GotSection()
74     : SyntheticSection(segment_names::dataConst, section_names::got) {
75   align = 8;
76   flags = S_NON_LAZY_SYMBOL_POINTERS;
77 
78   // TODO: section_64::reserved1 should be an index into the indirect symbol
79   // table, which we do not currently emit
80 }
81 
82 void GotSection::addEntry(DylibSymbol &sym) {
83   if (entries.insert(&sym)) {
84     sym.gotIndex = entries.size() - 1;
85   }
86 }
87 
88 BindingSection::BindingSection()
89     : SyntheticSection(segment_names::linkEdit, section_names::binding) {}
90 
91 bool BindingSection::isNeeded() const { return in.got->isNeeded(); }
92 
93 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
94 // interprets to update a record with the following fields:
95 //  * segment index (of the segment to write the symbol addresses to, typically
96 //    the __DATA_CONST segment which contains the GOT)
97 //  * offset within the segment, indicating the next location to write a binding
98 //  * symbol type
99 //  * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
100 //  * symbol name
101 //  * addend
102 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
103 // a symbol in the GOT, and increments the segment offset to point to the next
104 // entry. It does *not* clear the record state after doing the bind, so
105 // subsequent opcodes only need to encode the differences between bindings.
106 void BindingSection::finalizeContents() {
107   if (!isNeeded())
108     return;
109 
110   raw_svector_ostream os{contents};
111   os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
112                              in.got->parent->index);
113   encodeULEB128(in.got->getSegmentOffset(), os);
114   for (const DylibSymbol *sym : in.got->getEntries()) {
115     // TODO: Implement compact encoding -- we only need to encode the
116     // differences between consecutive symbol entries.
117     if (sym->file->ordinal <= BIND_IMMEDIATE_MASK) {
118       os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
119                                  sym->file->ordinal);
120     } else {
121       error("TODO: Support larger dylib symbol ordinals");
122       continue;
123     }
124     os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
125        << sym->getName() << '\0'
126        << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER)
127        << static_cast<uint8_t>(BIND_OPCODE_DO_BIND);
128   }
129 
130   os << static_cast<uint8_t>(BIND_OPCODE_DONE);
131 }
132 
133 void BindingSection::writeTo(uint8_t *buf) const {
134   memcpy(buf, contents.data(), contents.size());
135 }
136 
137 StubsSection::StubsSection()
138     : SyntheticSection(segment_names::text, "__stubs") {}
139 
140 size_t StubsSection::getSize() const {
141   return entries.size() * target->stubSize;
142 }
143 
144 void StubsSection::writeTo(uint8_t *buf) const {
145   size_t off = 0;
146   for (const DylibSymbol *sym : in.stubs->getEntries()) {
147     target->writeStub(buf + off, *sym);
148     off += target->stubSize;
149   }
150 }
151 
152 void StubsSection::addEntry(DylibSymbol &sym) {
153   if (entries.insert(&sym))
154     sym.stubsIndex = entries.size() - 1;
155 }
156 
157 StubHelperSection::StubHelperSection()
158     : SyntheticSection(segment_names::text, "__stub_helper") {}
159 
160 size_t StubHelperSection::getSize() const {
161   return target->stubHelperHeaderSize +
162          in.stubs->getEntries().size() * target->stubHelperEntrySize;
163 }
164 
165 bool StubHelperSection::isNeeded() const {
166   return !in.stubs->getEntries().empty();
167 }
168 
169 void StubHelperSection::writeTo(uint8_t *buf) const {
170   target->writeStubHelperHeader(buf);
171   size_t off = target->stubHelperHeaderSize;
172   for (const DylibSymbol *sym : in.stubs->getEntries()) {
173     target->writeStubHelperEntry(buf + off, *sym, addr + off);
174     off += target->stubHelperEntrySize;
175   }
176 }
177 
178 void StubHelperSection::setup() {
179   stubBinder = dyn_cast_or_null<DylibSymbol>(symtab->find("dyld_stub_binder"));
180   if (stubBinder == nullptr) {
181     error("symbol dyld_stub_binder not found (normally in libSystem.dylib). "
182           "Needed to perform lazy binding.");
183     return;
184   }
185   in.got->addEntry(*stubBinder);
186 
187   inputSections.push_back(in.imageLoaderCache);
188   symtab->addDefined("__dyld_private", in.imageLoaderCache, 0);
189 }
190 
191 ImageLoaderCacheSection::ImageLoaderCacheSection() {
192   segname = segment_names::data;
193   name = "__data";
194 }
195 
196 LazyPointerSection::LazyPointerSection()
197     : SyntheticSection(segment_names::data, "__la_symbol_ptr") {
198   align = 8;
199   flags = S_LAZY_SYMBOL_POINTERS;
200 }
201 
202 size_t LazyPointerSection::getSize() const {
203   return in.stubs->getEntries().size() * WordSize;
204 }
205 
206 bool LazyPointerSection::isNeeded() const {
207   return !in.stubs->getEntries().empty();
208 }
209 
210 void LazyPointerSection::writeTo(uint8_t *buf) const {
211   size_t off = 0;
212   for (const DylibSymbol *sym : in.stubs->getEntries()) {
213     uint64_t stubHelperOffset = target->stubHelperHeaderSize +
214                                 sym->stubsIndex * target->stubHelperEntrySize;
215     write64le(buf + off, in.stubHelper->addr + stubHelperOffset);
216     off += WordSize;
217   }
218 }
219 
220 LazyBindingSection::LazyBindingSection()
221     : SyntheticSection(segment_names::linkEdit, section_names::lazyBinding) {}
222 
223 bool LazyBindingSection::isNeeded() const { return in.stubs->isNeeded(); }
224 
225 void LazyBindingSection::finalizeContents() {
226   // TODO: Just precompute output size here instead of writing to a temporary
227   // buffer
228   for (DylibSymbol *sym : in.stubs->getEntries())
229     sym->lazyBindOffset = encode(*sym);
230 }
231 
232 void LazyBindingSection::writeTo(uint8_t *buf) const {
233   memcpy(buf, contents.data(), contents.size());
234 }
235 
236 // Unlike the non-lazy binding section, the bind opcodes in this section aren't
237 // interpreted all at once. Rather, dyld will start interpreting opcodes at a
238 // given offset, typically only binding a single symbol before it finds a
239 // BIND_OPCODE_DONE terminator. As such, unlike in the non-lazy-binding case,
240 // we cannot encode just the differences between symbols; we have to emit the
241 // complete bind information for each symbol.
242 uint32_t LazyBindingSection::encode(const DylibSymbol &sym) {
243   uint32_t opstreamOffset = contents.size();
244   OutputSegment *dataSeg = in.lazyPointers->parent;
245   os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
246                              dataSeg->index);
247   uint64_t offset = in.lazyPointers->addr - dataSeg->firstSection()->addr +
248                     sym.stubsIndex * WordSize;
249   encodeULEB128(offset, os);
250   if (sym.file->ordinal <= BIND_IMMEDIATE_MASK)
251     os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
252                                sym.file->ordinal);
253   else
254     fatal("TODO: Support larger dylib symbol ordinals");
255 
256   os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
257      << sym.getName() << '\0' << static_cast<uint8_t>(BIND_OPCODE_DO_BIND)
258      << static_cast<uint8_t>(BIND_OPCODE_DONE);
259   return opstreamOffset;
260 }
261 
262 ExportSection::ExportSection()
263     : SyntheticSection(segment_names::linkEdit, section_names::export_) {}
264 
265 void ExportSection::finalizeContents() {
266   // TODO: We should check symbol visibility.
267   for (const Symbol *sym : symtab->getSymbols())
268     if (auto *defined = dyn_cast<Defined>(sym))
269       trieBuilder.addSymbol(*defined);
270   size = trieBuilder.build();
271 }
272 
273 void ExportSection::writeTo(uint8_t *buf) const { trieBuilder.writeTo(buf); }
274 
275 SymtabSection::SymtabSection(StringTableSection &stringTableSection)
276     : SyntheticSection(segment_names::linkEdit, section_names::symbolTable),
277       stringTableSection(stringTableSection) {
278   // TODO: When we introduce the SyntheticSections superclass, we should make
279   // all synthetic sections aligned to WordSize by default.
280   align = WordSize;
281 }
282 
283 size_t SymtabSection::getSize() const {
284   return symbols.size() * sizeof(nlist_64);
285 }
286 
287 void SymtabSection::finalizeContents() {
288   // TODO support other symbol types
289   for (Symbol *sym : symtab->getSymbols())
290     if (isa<Defined>(sym))
291       symbols.push_back({sym, stringTableSection.addString(sym->getName())});
292 }
293 
294 void SymtabSection::writeTo(uint8_t *buf) const {
295   auto *nList = reinterpret_cast<nlist_64 *>(buf);
296   for (const SymtabEntry &entry : symbols) {
297     nList->n_strx = entry.strx;
298     // TODO support other symbol types
299     // TODO populate n_desc
300     if (auto *defined = dyn_cast<Defined>(entry.sym)) {
301       nList->n_type = N_EXT | N_SECT;
302       nList->n_sect = defined->isec->parent->index;
303       // For the N_SECT symbol type, n_value is the address of the symbol
304       nList->n_value = defined->value + defined->isec->getVA();
305     }
306     ++nList;
307   }
308 }
309 
310 StringTableSection::StringTableSection()
311     : SyntheticSection(segment_names::linkEdit, section_names::stringTable) {}
312 
313 uint32_t StringTableSection::addString(StringRef str) {
314   uint32_t strx = size;
315   strings.push_back(str);
316   size += str.size() + 1; // account for null terminator
317   return strx;
318 }
319 
320 void StringTableSection::writeTo(uint8_t *buf) const {
321   uint32_t off = 0;
322   for (StringRef str : strings) {
323     memcpy(buf + off, str.data(), str.size());
324     off += str.size() + 1; // account for null terminator
325   }
326 }
327 
328 InStruct in;
329 
330 } // namespace macho
331 } // namespace lld
332