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 
26 namespace lld {
27 namespace macho {
28 
29 MachHeaderSection::MachHeaderSection() {
30   // dyld3's MachOLoaded::getSlide() assumes that the __TEXT segment starts
31   // from the beginning of the file (i.e. the header).
32   segname = segment_names::text;
33   name = section_names::header;
34 }
35 
36 void MachHeaderSection::addLoadCommand(LoadCommand *lc) {
37   loadCommands.push_back(lc);
38   sizeOfCmds += lc->getSize();
39 }
40 
41 size_t MachHeaderSection::getSize() const {
42   return sizeof(mach_header_64) + sizeOfCmds;
43 }
44 
45 void MachHeaderSection::writeTo(uint8_t *buf) {
46   auto *hdr = reinterpret_cast<mach_header_64 *>(buf);
47   hdr->magic = MH_MAGIC_64;
48   hdr->cputype = CPU_TYPE_X86_64;
49   hdr->cpusubtype = CPU_SUBTYPE_X86_64_ALL | CPU_SUBTYPE_LIB64;
50   hdr->filetype = config->outputType;
51   hdr->ncmds = loadCommands.size();
52   hdr->sizeofcmds = sizeOfCmds;
53   hdr->flags = MH_NOUNDEFS | MH_DYLDLINK | MH_TWOLEVEL;
54 
55   uint8_t *p = reinterpret_cast<uint8_t *>(hdr + 1);
56   for (LoadCommand *lc : loadCommands) {
57     lc->writeTo(p);
58     p += lc->getSize();
59   }
60 }
61 
62 PageZeroSection::PageZeroSection() {
63   segname = segment_names::pageZero;
64   name = section_names::pageZero;
65 }
66 
67 GotSection::GotSection() {
68   segname = "__DATA_CONST";
69   name = "__got";
70   align = 8;
71   flags = S_NON_LAZY_SYMBOL_POINTERS;
72 
73   // TODO: section_64::reserved1 should be an index into the indirect symbol
74   // table, which we do not currently emit
75 }
76 
77 void GotSection::addEntry(DylibSymbol &sym) {
78   if (entries.insert(&sym)) {
79     sym.gotIndex = entries.size() - 1;
80   }
81 }
82 
83 BindingSection::BindingSection() {
84   segname = segment_names::linkEdit;
85   name = section_names::binding;
86 }
87 
88 bool BindingSection::isNeeded() const { return in.got->isNeeded(); }
89 
90 // Emit bind opcodes, which are a stream of byte-sized opcodes that dyld
91 // interprets to update a record with the following fields:
92 //  * segment index (of the segment to write the symbol addresses to, typically
93 //    the __DATA_CONST segment which contains the GOT)
94 //  * offset within the segment, indicating the next location to write a binding
95 //  * symbol type
96 //  * symbol library ordinal (the index of its library's LC_LOAD_DYLIB command)
97 //  * symbol name
98 //  * addend
99 // When dyld sees BIND_OPCODE_DO_BIND, it uses the current record state to bind
100 // a symbol in the GOT, and increments the segment offset to point to the next
101 // entry. It does *not* clear the record state after doing the bind, so
102 // subsequent opcodes only need to encode the differences between bindings.
103 void BindingSection::finalizeContents() {
104   if (!isNeeded())
105     return;
106 
107   raw_svector_ostream os{contents};
108   os << static_cast<uint8_t>(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB |
109                              in.got->parent->index);
110   encodeULEB128(in.got->addr - in.got->parent->firstSection()->addr, os);
111   for (const DylibSymbol *sym : in.got->getEntries()) {
112     // TODO: Implement compact encoding -- we only need to encode the
113     // differences between consecutive symbol entries.
114     if (sym->file->ordinal <= BIND_IMMEDIATE_MASK) {
115       os << static_cast<uint8_t>(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM |
116                                  sym->file->ordinal);
117     } else {
118       error("TODO: Support larger dylib symbol ordinals");
119       continue;
120     }
121     os << static_cast<uint8_t>(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM)
122        << sym->getName() << '\0'
123        << static_cast<uint8_t>(BIND_OPCODE_SET_TYPE_IMM | BIND_TYPE_POINTER)
124        << static_cast<uint8_t>(BIND_OPCODE_DO_BIND);
125   }
126 
127   os << static_cast<uint8_t>(BIND_OPCODE_DONE);
128 }
129 
130 void BindingSection::writeTo(uint8_t *buf) {
131   memcpy(buf, contents.data(), contents.size());
132 }
133 
134 ExportSection::ExportSection() {
135   segname = segment_names::linkEdit;
136   name = section_names::export_;
137 }
138 
139 void ExportSection::finalizeContents() {
140   // TODO: We should check symbol visibility.
141   for (const Symbol *sym : symtab->getSymbols())
142     if (auto *defined = dyn_cast<Defined>(sym))
143       trieBuilder.addSymbol(*defined);
144   size = trieBuilder.build();
145 }
146 
147 void ExportSection::writeTo(uint8_t *buf) { trieBuilder.writeTo(buf); }
148 
149 SymtabSection::SymtabSection(StringTableSection &stringTableSection)
150     : stringTableSection(stringTableSection) {
151   segname = segment_names::linkEdit;
152   name = section_names::symbolTable;
153   // TODO: When we introduce the SyntheticSections superclass, we should make
154   // all synthetic sections aligned to WordSize by default.
155   align = WordSize;
156 }
157 
158 size_t SymtabSection::getSize() const {
159   return symbols.size() * sizeof(nlist_64);
160 }
161 
162 void SymtabSection::finalizeContents() {
163   // TODO support other symbol types
164   for (Symbol *sym : symtab->getSymbols())
165     if (isa<Defined>(sym))
166       symbols.push_back({sym, stringTableSection.addString(sym->getName())});
167 }
168 
169 void SymtabSection::writeTo(uint8_t *buf) {
170   auto *nList = reinterpret_cast<nlist_64 *>(buf);
171   for (const SymtabEntry &entry : symbols) {
172     nList->n_strx = entry.strx;
173     // TODO support other symbol types
174     // TODO populate n_desc
175     if (auto defined = dyn_cast<Defined>(entry.sym)) {
176       nList->n_type = N_EXT | N_SECT;
177       nList->n_sect = defined->isec->sectionIndex;
178       // For the N_SECT symbol type, n_value is the address of the symbol
179       nList->n_value = defined->value + defined->isec->addr;
180     }
181     ++nList;
182   }
183 }
184 
185 StringTableSection::StringTableSection() {
186   segname = segment_names::linkEdit;
187   name = section_names::stringTable;
188 }
189 
190 uint32_t StringTableSection::addString(StringRef str) {
191   uint32_t strx = size;
192   strings.push_back(str);
193   size += str.size() + 1; // account for null terminator
194   return strx;
195 }
196 
197 void StringTableSection::writeTo(uint8_t *buf) {
198   uint32_t off = 0;
199   for (StringRef str : strings) {
200     memcpy(buf + off, str.data(), str.size());
201     off += str.size() + 1; // account for null terminator
202   }
203 }
204 
205 InStruct in;
206 
207 } // namespace macho
208 } // namespace lld
209