xref: /freebsd/contrib/llvm-project/lld/MachO/SyntheticSections.h (revision ae7e8a02e6e93455e026036132c4d053b2c12ad9)
1 //===- SyntheticSections.h -------------------------------------*- C++ -*-===//
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 #ifndef LLD_MACHO_SYNTHETIC_SECTIONS_H
10 #define LLD_MACHO_SYNTHETIC_SECTIONS_H
11 
12 #include "Config.h"
13 #include "ExportTrie.h"
14 #include "InputSection.h"
15 #include "OutputSection.h"
16 #include "OutputSegment.h"
17 #include "Target.h"
18 
19 #include "llvm/ADT/PointerUnion.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 namespace llvm {
24 class DWARFUnit;
25 } // namespace llvm
26 
27 namespace lld {
28 namespace macho {
29 
30 namespace section_names {
31 
32 constexpr const char pageZero[] = "__pagezero";
33 constexpr const char common[] = "__common";
34 constexpr const char header[] = "__mach_header";
35 constexpr const char rebase[] = "__rebase";
36 constexpr const char binding[] = "__binding";
37 constexpr const char weakBinding[] = "__weak_binding";
38 constexpr const char lazyBinding[] = "__lazy_binding";
39 constexpr const char export_[] = "__export";
40 constexpr const char symbolTable[] = "__symbol_table";
41 constexpr const char indirectSymbolTable[] = "__ind_sym_tab";
42 constexpr const char stringTable[] = "__string_table";
43 constexpr const char got[] = "__got";
44 constexpr const char threadPtrs[] = "__thread_ptrs";
45 constexpr const char unwindInfo[] = "__unwind_info";
46 // these are not synthetic, but in service of synthetic __unwind_info
47 constexpr const char compactUnwind[] = "__compact_unwind";
48 constexpr const char ehFrame[] = "__eh_frame";
49 
50 } // namespace section_names
51 
52 class Defined;
53 class DylibSymbol;
54 class LoadCommand;
55 class ObjFile;
56 
57 class SyntheticSection : public OutputSection {
58 public:
59   SyntheticSection(const char *segname, const char *name);
60   virtual ~SyntheticSection() = default;
61 
62   static bool classof(const OutputSection *sec) {
63     return sec->kind() == SyntheticKind;
64   }
65 
66   const StringRef segname;
67 };
68 
69 // All sections in __LINKEDIT should inherit from this.
70 class LinkEditSection : public SyntheticSection {
71 public:
72   LinkEditSection(const char *segname, const char *name)
73       : SyntheticSection(segname, name) {
74     align = WordSize;
75   }
76 
77   // Sections in __LINKEDIT are special: their offsets are recorded in the
78   // load commands like LC_DYLD_INFO_ONLY and LC_SYMTAB, instead of in section
79   // headers.
80   bool isHidden() const override final { return true; }
81 
82   virtual uint64_t getRawSize() const = 0;
83 
84   // codesign (or more specifically libstuff) checks that each section in
85   // __LINKEDIT ends where the next one starts -- no gaps are permitted. We
86   // therefore align every section's start and end points to WordSize.
87   //
88   // NOTE: This assumes that the extra bytes required for alignment can be
89   // zero-valued bytes.
90   uint64_t getSize() const override final {
91     return llvm::alignTo(getRawSize(), WordSize);
92   }
93 };
94 
95 // The header of the Mach-O file, which must have a file offset of zero.
96 class MachHeaderSection : public SyntheticSection {
97 public:
98   MachHeaderSection();
99   void addLoadCommand(LoadCommand *);
100   bool isHidden() const override { return true; }
101   uint64_t getSize() const override;
102   void writeTo(uint8_t *buf) const override;
103 
104 private:
105   std::vector<LoadCommand *> loadCommands;
106   uint32_t sizeOfCmds = 0;
107 };
108 
109 // A hidden section that exists solely for the purpose of creating the
110 // __PAGEZERO segment, which is used to catch null pointer dereferences.
111 class PageZeroSection : public SyntheticSection {
112 public:
113   PageZeroSection();
114   bool isHidden() const override { return true; }
115   uint64_t getSize() const override { return PageZeroSize; }
116   uint64_t getFileSize() const override { return 0; }
117   void writeTo(uint8_t *buf) const override {}
118 };
119 
120 // This is the base class for the GOT and TLVPointer sections, which are nearly
121 // functionally identical -- they will both be populated by dyld with addresses
122 // to non-lazily-loaded dylib symbols. The main difference is that the
123 // TLVPointerSection stores references to thread-local variables.
124 class NonLazyPointerSectionBase : public SyntheticSection {
125 public:
126   NonLazyPointerSectionBase(const char *segname, const char *name);
127 
128   const llvm::SetVector<const Symbol *> &getEntries() const { return entries; }
129 
130   bool isNeeded() const override { return !entries.empty(); }
131 
132   uint64_t getSize() const override { return entries.size() * WordSize; }
133 
134   void writeTo(uint8_t *buf) const override;
135 
136   void addEntry(Symbol *sym);
137 
138 private:
139   llvm::SetVector<const Symbol *> entries;
140 };
141 
142 class GotSection : public NonLazyPointerSectionBase {
143 public:
144   GotSection()
145       : NonLazyPointerSectionBase(segment_names::dataConst,
146                                   section_names::got) {
147     // TODO: section_64::reserved1 should be an index into the indirect symbol
148     // table, which we do not currently emit
149   }
150 };
151 
152 class TlvPointerSection : public NonLazyPointerSectionBase {
153 public:
154   TlvPointerSection()
155       : NonLazyPointerSectionBase(segment_names::data,
156                                   section_names::threadPtrs) {}
157 };
158 
159 using SectionPointerUnion =
160     llvm::PointerUnion<const InputSection *, const OutputSection *>;
161 
162 struct Location {
163   SectionPointerUnion section = nullptr;
164   uint64_t offset = 0;
165 
166   Location(SectionPointerUnion section, uint64_t offset)
167       : section(section), offset(offset) {}
168   uint64_t getVA() const;
169 };
170 
171 // Stores rebase opcodes, which tell dyld where absolute addresses have been
172 // encoded in the binary. If the binary is not loaded at its preferred address,
173 // dyld has to rebase these addresses by adding an offset to them.
174 class RebaseSection : public LinkEditSection {
175 public:
176   RebaseSection();
177   void finalizeContents();
178   uint64_t getRawSize() const override { return contents.size(); }
179   bool isNeeded() const override { return !locations.empty(); }
180   void writeTo(uint8_t *buf) const override;
181 
182   void addEntry(SectionPointerUnion section, uint64_t offset) {
183     if (config->isPic)
184       locations.push_back({section, offset});
185   }
186 
187 private:
188   std::vector<Location> locations;
189   SmallVector<char, 128> contents;
190 };
191 
192 struct BindingEntry {
193   const DylibSymbol *dysym;
194   int64_t addend;
195   Location target;
196   BindingEntry(const DylibSymbol *dysym, int64_t addend, Location target)
197       : dysym(dysym), addend(addend), target(std::move(target)) {}
198 };
199 
200 // Stores bind opcodes for telling dyld which symbols to load non-lazily.
201 class BindingSection : public LinkEditSection {
202 public:
203   BindingSection();
204   void finalizeContents();
205   uint64_t getRawSize() const override { return contents.size(); }
206   bool isNeeded() const override { return !bindings.empty(); }
207   void writeTo(uint8_t *buf) const override;
208 
209   void addEntry(const DylibSymbol *dysym, SectionPointerUnion section,
210                 uint64_t offset, int64_t addend = 0) {
211     bindings.emplace_back(dysym, addend, Location(section, offset));
212   }
213 
214 private:
215   std::vector<BindingEntry> bindings;
216   SmallVector<char, 128> contents;
217 };
218 
219 struct WeakBindingEntry {
220   const Symbol *symbol;
221   int64_t addend;
222   Location target;
223   WeakBindingEntry(const Symbol *symbol, int64_t addend, Location target)
224       : symbol(symbol), addend(addend), target(std::move(target)) {}
225 };
226 
227 // Stores bind opcodes for telling dyld which weak symbols need coalescing.
228 // There are two types of entries in this section:
229 //
230 //   1) Non-weak definitions: This is a symbol definition that weak symbols in
231 //   other dylibs should coalesce to.
232 //
233 //   2) Weak bindings: These tell dyld that a given symbol reference should
234 //   coalesce to a non-weak definition if one is found. Note that unlike in the
235 //   entries in the BindingSection, the bindings here only refer to these
236 //   symbols by name, but do not specify which dylib to load them from.
237 class WeakBindingSection : public LinkEditSection {
238 public:
239   WeakBindingSection();
240   void finalizeContents();
241   uint64_t getRawSize() const override { return contents.size(); }
242   bool isNeeded() const override {
243     return !bindings.empty() || !definitions.empty();
244   }
245 
246   void writeTo(uint8_t *buf) const override;
247 
248   void addEntry(const Symbol *symbol, SectionPointerUnion section,
249                 uint64_t offset, int64_t addend = 0) {
250     bindings.emplace_back(symbol, addend, Location(section, offset));
251   }
252 
253   bool hasEntry() const { return !bindings.empty(); }
254 
255   void addNonWeakDefinition(const Defined *defined) {
256     definitions.emplace_back(defined);
257   }
258 
259   bool hasNonWeakDefinition() const { return !definitions.empty(); }
260 
261 private:
262   std::vector<WeakBindingEntry> bindings;
263   std::vector<const Defined *> definitions;
264   SmallVector<char, 128> contents;
265 };
266 
267 // Whether a given symbol's address can only be resolved at runtime.
268 bool needsBinding(const Symbol *);
269 
270 // Add bindings for symbols that need weak or non-lazy bindings.
271 void addNonLazyBindingEntries(const Symbol *, SectionPointerUnion,
272                               uint64_t offset, int64_t addend = 0);
273 
274 // The following sections implement lazy symbol binding -- very similar to the
275 // PLT mechanism in ELF.
276 //
277 // ELF's .plt section is broken up into two sections in Mach-O: StubsSection
278 // and StubHelperSection. Calls to functions in dylibs will end up calling into
279 // StubsSection, which contains indirect jumps to addresses stored in the
280 // LazyPointerSection (the counterpart to ELF's .plt.got).
281 //
282 // We will first describe how non-weak symbols are handled.
283 //
284 // At program start, the LazyPointerSection contains addresses that point into
285 // one of the entry points in the middle of the StubHelperSection. The code in
286 // StubHelperSection will push on the stack an offset into the
287 // LazyBindingSection. The push is followed by a jump to the beginning of the
288 // StubHelperSection (similar to PLT0), which then calls into dyld_stub_binder.
289 // dyld_stub_binder is a non-lazily-bound symbol, so this call looks it up in
290 // the GOT.
291 //
292 // The stub binder will look up the bind opcodes in the LazyBindingSection at
293 // the given offset. The bind opcodes will tell the binder to update the
294 // address in the LazyPointerSection to point to the symbol, so that subsequent
295 // calls don't have to redo the symbol resolution. The binder will then jump to
296 // the resolved symbol.
297 //
298 // With weak symbols, the situation is slightly different. Since there is no
299 // "weak lazy" lookup, function calls to weak symbols are always non-lazily
300 // bound. We emit both regular non-lazy bindings as well as weak bindings, in
301 // order that the weak bindings may overwrite the non-lazy bindings if an
302 // appropriate symbol is found at runtime. However, the bound addresses will
303 // still be written (non-lazily) into the LazyPointerSection.
304 
305 class StubsSection : public SyntheticSection {
306 public:
307   StubsSection();
308   uint64_t getSize() const override;
309   bool isNeeded() const override { return !entries.empty(); }
310   void writeTo(uint8_t *buf) const override;
311   const llvm::SetVector<Symbol *> &getEntries() const { return entries; }
312   // Returns whether the symbol was added. Note that every stubs entry will
313   // have a corresponding entry in the LazyPointerSection.
314   bool addEntry(Symbol *);
315 
316 private:
317   llvm::SetVector<Symbol *> entries;
318 };
319 
320 class StubHelperSection : public SyntheticSection {
321 public:
322   StubHelperSection();
323   uint64_t getSize() const override;
324   bool isNeeded() const override;
325   void writeTo(uint8_t *buf) const override;
326 
327   void setup();
328 
329   DylibSymbol *stubBinder = nullptr;
330   Defined *dyldPrivate = nullptr;
331 };
332 
333 // This section contains space for just a single word, and will be used by dyld
334 // to cache an address to the image loader it uses. Note that unlike the other
335 // synthetic sections, which are OutputSections, the ImageLoaderCacheSection is
336 // an InputSection that gets merged into the __data OutputSection.
337 class ImageLoaderCacheSection : public InputSection {
338 public:
339   ImageLoaderCacheSection();
340   uint64_t getSize() const override { return WordSize; }
341 };
342 
343 // Note that this section may also be targeted by non-lazy bindings. In
344 // particular, this happens when branch relocations target weak symbols.
345 class LazyPointerSection : public SyntheticSection {
346 public:
347   LazyPointerSection();
348   uint64_t getSize() const override;
349   bool isNeeded() const override;
350   void writeTo(uint8_t *buf) const override;
351 };
352 
353 class LazyBindingSection : public LinkEditSection {
354 public:
355   LazyBindingSection();
356   void finalizeContents();
357   uint64_t getRawSize() const override { return contents.size(); }
358   bool isNeeded() const override { return !entries.empty(); }
359   void writeTo(uint8_t *buf) const override;
360   // Note that every entry here will by referenced by a corresponding entry in
361   // the StubHelperSection.
362   void addEntry(DylibSymbol *dysym);
363   const llvm::SetVector<DylibSymbol *> &getEntries() const { return entries; }
364 
365 private:
366   uint32_t encode(const DylibSymbol &);
367 
368   llvm::SetVector<DylibSymbol *> entries;
369   SmallVector<char, 128> contents;
370   llvm::raw_svector_ostream os{contents};
371 };
372 
373 // Adds stubs and bindings where necessary (e.g. if the symbol is a
374 // DylibSymbol.)
375 void prepareBranchTarget(Symbol *);
376 
377 // Stores a trie that describes the set of exported symbols.
378 class ExportSection : public LinkEditSection {
379 public:
380   ExportSection();
381   void finalizeContents();
382   uint64_t getRawSize() const override { return size; }
383   void writeTo(uint8_t *buf) const override;
384 
385   bool hasWeakSymbol = false;
386 
387 private:
388   TrieBuilder trieBuilder;
389   size_t size = 0;
390 };
391 
392 // Stores the strings referenced by the symbol table.
393 class StringTableSection : public LinkEditSection {
394 public:
395   StringTableSection();
396   // Returns the start offset of the added string.
397   uint32_t addString(StringRef);
398   uint64_t getRawSize() const override { return size; }
399   void writeTo(uint8_t *buf) const override;
400 
401 private:
402   // ld64 emits string tables which start with a space and a zero byte. We
403   // match its behavior here since some tools depend on it.
404   std::vector<StringRef> strings{" "};
405   size_t size = 2;
406 };
407 
408 struct SymtabEntry {
409   Symbol *sym;
410   size_t strx;
411 };
412 
413 struct StabsEntry {
414   uint8_t type = 0;
415   uint32_t strx = 0;
416   uint8_t sect = 0;
417   uint16_t desc = 0;
418   uint64_t value = 0;
419 
420   StabsEntry() = default;
421   explicit StabsEntry(uint8_t type) : type(type) {}
422 };
423 
424 // Symbols of the same type must be laid out contiguously: we choose to emit
425 // all local symbols first, then external symbols, and finally undefined
426 // symbols. For each symbol type, the LC_DYSYMTAB load command will record the
427 // range (start index and total number) of those symbols in the symbol table.
428 class SymtabSection : public LinkEditSection {
429 public:
430   SymtabSection(StringTableSection &);
431   void finalizeContents();
432   uint32_t getNumSymbols() const;
433   uint32_t getNumLocalSymbols() const {
434     return stabs.size() + localSymbols.size();
435   }
436   uint32_t getNumExternalSymbols() const { return externalSymbols.size(); }
437   uint32_t getNumUndefinedSymbols() const { return undefinedSymbols.size(); }
438   uint64_t getRawSize() const override;
439   void writeTo(uint8_t *buf) const override;
440 
441 private:
442   void emitBeginSourceStab(llvm::DWARFUnit *compileUnit);
443   void emitEndSourceStab();
444   void emitObjectFileStab(ObjFile *);
445   void emitEndFunStab(Defined *);
446   void emitStabs();
447 
448   StringTableSection &stringTableSection;
449   // STABS symbols are always local symbols, but we represent them with special
450   // entries because they may use fields like n_sect and n_desc differently.
451   std::vector<StabsEntry> stabs;
452   std::vector<SymtabEntry> localSymbols;
453   std::vector<SymtabEntry> externalSymbols;
454   std::vector<SymtabEntry> undefinedSymbols;
455 };
456 
457 // The indirect symbol table is a list of 32-bit integers that serve as indices
458 // into the (actual) symbol table. The indirect symbol table is a
459 // concatenation of several sub-arrays of indices, each sub-array belonging to
460 // a separate section. The starting offset of each sub-array is stored in the
461 // reserved1 header field of the respective section.
462 //
463 // These sub-arrays provide symbol information for sections that store
464 // contiguous sequences of symbol references. These references can be pointers
465 // (e.g. those in the GOT and TLVP sections) or assembly sequences (e.g.
466 // function stubs).
467 class IndirectSymtabSection : public LinkEditSection {
468 public:
469   IndirectSymtabSection();
470   void finalizeContents();
471   uint32_t getNumSymbols() const;
472   uint64_t getRawSize() const override {
473     return getNumSymbols() * sizeof(uint32_t);
474   }
475   bool isNeeded() const override;
476   void writeTo(uint8_t *buf) const override;
477 };
478 
479 struct InStruct {
480   MachHeaderSection *header = nullptr;
481   RebaseSection *rebase = nullptr;
482   BindingSection *binding = nullptr;
483   WeakBindingSection *weakBinding = nullptr;
484   LazyBindingSection *lazyBinding = nullptr;
485   ExportSection *exports = nullptr;
486   GotSection *got = nullptr;
487   TlvPointerSection *tlvPointers = nullptr;
488   LazyPointerSection *lazyPointers = nullptr;
489   StubsSection *stubs = nullptr;
490   StubHelperSection *stubHelper = nullptr;
491   ImageLoaderCacheSection *imageLoaderCache = nullptr;
492 };
493 
494 extern InStruct in;
495 extern std::vector<SyntheticSection *> syntheticSections;
496 
497 } // namespace macho
498 } // namespace lld
499 
500 #endif
501