xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 8f5beb4c)
1 //===- Writer.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 "Writer.h"
10 #include "Config.h"
11 #include "InputFiles.h"
12 #include "InputSection.h"
13 #include "OutputSegment.h"
14 #include "SymbolTable.h"
15 #include "Symbols.h"
16 #include "SyntheticSections.h"
17 #include "Target.h"
18 
19 #include "lld/Common/ErrorHandler.h"
20 #include "lld/Common/Memory.h"
21 #include "llvm/BinaryFormat/MachO.h"
22 #include "llvm/Support/MathExtras.h"
23 
24 using namespace llvm;
25 using namespace llvm::MachO;
26 using namespace lld;
27 using namespace lld::macho;
28 
29 namespace {
30 class LCLinkEdit;
31 class LCDyldInfo;
32 class LCSymtab;
33 
34 class Writer {
35 public:
36   Writer() : buffer(errorHandler().outputBuffer) {}
37 
38   void scanRelocations();
39   void createHiddenSections();
40   void sortSections();
41   void createLoadCommands();
42   void assignAddresses(OutputSegment *);
43   void createSymtabContents();
44 
45   void openFile();
46   void writeSections();
47 
48   void run();
49 
50   std::unique_ptr<FileOutputBuffer> &buffer;
51   uint64_t addr = 0;
52   uint64_t fileOff = 0;
53   MachHeaderSection *headerSection = nullptr;
54   BindingSection *bindingSection = nullptr;
55 };
56 
57 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
58 class LCDyldInfo : public LoadCommand {
59 public:
60   LCDyldInfo(BindingSection *bindingSection) : bindingSection(bindingSection) {}
61 
62   uint32_t getSize() const override { return sizeof(dyld_info_command); }
63 
64   void writeTo(uint8_t *buf) const override {
65     auto *c = reinterpret_cast<dyld_info_command *>(buf);
66     c->cmd = LC_DYLD_INFO_ONLY;
67     c->cmdsize = getSize();
68     if (bindingSection->isNeeded()) {
69       c->bind_off = bindingSection->getFileOffset();
70       c->bind_size = bindingSection->getFileSize();
71     }
72     c->export_off = exportOff;
73     c->export_size = exportSize;
74   }
75 
76   BindingSection *bindingSection;
77   uint64_t exportOff = 0;
78   uint64_t exportSize = 0;
79 };
80 
81 class LCDysymtab : public LoadCommand {
82 public:
83   uint32_t getSize() const override { return sizeof(dysymtab_command); }
84 
85   void writeTo(uint8_t *buf) const override {
86     auto *c = reinterpret_cast<dysymtab_command *>(buf);
87     c->cmd = LC_DYSYMTAB;
88     c->cmdsize = getSize();
89   }
90 };
91 
92 class LCSegment : public LoadCommand {
93 public:
94   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
95 
96   uint32_t getSize() const override {
97     return sizeof(segment_command_64) +
98            seg->numNonHiddenSections * sizeof(section_64);
99   }
100 
101   void writeTo(uint8_t *buf) const override {
102     auto *c = reinterpret_cast<segment_command_64 *>(buf);
103     buf += sizeof(segment_command_64);
104 
105     c->cmd = LC_SEGMENT_64;
106     c->cmdsize = getSize();
107     memcpy(c->segname, name.data(), name.size());
108     c->fileoff = seg->fileOff;
109     c->maxprot = seg->maxProt;
110     c->initprot = seg->initProt;
111 
112     if (seg->getSections().empty())
113       return;
114 
115     c->vmaddr = seg->firstSection()->addr;
116     c->vmsize =
117         seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr;
118     c->nsects = seg->numNonHiddenSections;
119 
120     for (auto &p : seg->getSections()) {
121       StringRef s = p.first;
122       ArrayRef<InputSection *> sections = p.second;
123       for (InputSection *isec : sections)
124         c->filesize += isec->getFileSize();
125       if (sections[0]->isHidden())
126         continue;
127 
128       auto *sectHdr = reinterpret_cast<section_64 *>(buf);
129       buf += sizeof(section_64);
130 
131       memcpy(sectHdr->sectname, s.data(), s.size());
132       memcpy(sectHdr->segname, name.data(), name.size());
133 
134       sectHdr->addr = sections[0]->addr;
135       sectHdr->offset = sections[0]->getFileOffset();
136       sectHdr->align = sections[0]->align;
137       uint32_t maxAlign = 0;
138       for (const InputSection *section : sections)
139         maxAlign = std::max(maxAlign, section->align);
140       sectHdr->align = Log2_32(maxAlign);
141       sectHdr->flags = sections[0]->flags;
142       sectHdr->size = sections.back()->addr + sections.back()->getSize() -
143                       sections[0]->addr;
144     }
145   }
146 
147 private:
148   StringRef name;
149   OutputSegment *seg;
150 };
151 
152 class LCMain : public LoadCommand {
153   uint32_t getSize() const override { return sizeof(entry_point_command); }
154 
155   void writeTo(uint8_t *buf) const override {
156     auto *c = reinterpret_cast<entry_point_command *>(buf);
157     c->cmd = LC_MAIN;
158     c->cmdsize = getSize();
159     c->entryoff = config->entry->getVA();
160     c->stacksize = 0;
161   }
162 };
163 
164 class LCSymtab : public LoadCommand {
165 public:
166   uint32_t getSize() const override { return sizeof(symtab_command); }
167 
168   void writeTo(uint8_t *buf) const override {
169     auto *c = reinterpret_cast<symtab_command *>(buf);
170     c->cmd = LC_SYMTAB;
171     c->cmdsize = getSize();
172   }
173 };
174 
175 class LCLoadDylib : public LoadCommand {
176 public:
177   LCLoadDylib(StringRef path) : path(path) {}
178 
179   uint32_t getSize() const override {
180     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
181   }
182 
183   void writeTo(uint8_t *buf) const override {
184     auto *c = reinterpret_cast<dylib_command *>(buf);
185     buf += sizeof(dylib_command);
186 
187     c->cmd = LC_LOAD_DYLIB;
188     c->cmdsize = getSize();
189     c->dylib.name = sizeof(dylib_command);
190 
191     memcpy(buf, path.data(), path.size());
192     buf[path.size()] = '\0';
193   }
194 
195 private:
196   StringRef path;
197 };
198 
199 class LCLoadDylinker : public LoadCommand {
200 public:
201   uint32_t getSize() const override {
202     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
203   }
204 
205   void writeTo(uint8_t *buf) const override {
206     auto *c = reinterpret_cast<dylinker_command *>(buf);
207     buf += sizeof(dylinker_command);
208 
209     c->cmd = LC_LOAD_DYLINKER;
210     c->cmdsize = getSize();
211     c->name = sizeof(dylinker_command);
212 
213     memcpy(buf, path.data(), path.size());
214     buf[path.size()] = '\0';
215   }
216 
217 private:
218   // Recent versions of Darwin won't run any binary that has dyld at a
219   // different location.
220   const StringRef path = "/usr/lib/dyld";
221 };
222 
223 class SectionComparator {
224 public:
225   struct OrderInfo {
226     uint32_t segmentOrder;
227     DenseMap<StringRef, uint32_t> sectionOrdering;
228   };
229 
230   SectionComparator() {
231     // This defines the order of segments and the sections within each segment.
232     // Segments that are not mentioned here will end up at defaultPosition;
233     // sections that are not mentioned will end up at the end of the section
234     // list for their given segment.
235     std::vector<std::pair<StringRef, std::vector<StringRef>>> ordering{
236         {segment_names::pageZero, {}},
237         {segment_names::text, {section_names::header}},
238         {defaultPosition, {}},
239         // Make sure __LINKEDIT is the last segment (i.e. all its hidden
240         // sections must be ordered after other sections).
241         {segment_names::linkEdit, {section_names::binding}},
242     };
243 
244     for (uint32_t i = 0, n = ordering.size(); i < n; ++i) {
245       auto &p = ordering[i];
246       StringRef segname = p.first;
247       const std::vector<StringRef> &sectOrdering = p.second;
248       OrderInfo &info = orderMap[segname];
249       info.segmentOrder = i;
250       for (uint32_t j = 0, m = sectOrdering.size(); j < m; ++j)
251         info.sectionOrdering[sectOrdering[j]] = j;
252     }
253   }
254 
255   // Return a {segmentOrder, sectionOrder} pair. Using this as a key will
256   // ensure that all sections in the same segment are sorted contiguously.
257   std::pair<uint32_t, uint32_t> order(const InputSection *isec) {
258     auto it = orderMap.find(isec->segname);
259     if (it == orderMap.end())
260       return {orderMap[defaultPosition].segmentOrder, 0};
261     OrderInfo &info = it->second;
262     auto sectIt = info.sectionOrdering.find(isec->name);
263     if (sectIt != info.sectionOrdering.end())
264       return {info.segmentOrder, sectIt->second};
265     return {info.segmentOrder, info.sectionOrdering.size()};
266   }
267 
268   bool operator()(const InputSection *a, const InputSection *b) {
269     return order(a) < order(b);
270   }
271 
272 private:
273   const StringRef defaultPosition = StringRef();
274   DenseMap<StringRef, OrderInfo> orderMap;
275 };
276 
277 } // namespace
278 
279 template <typename SectionType, typename... ArgT>
280 SectionType *createInputSection(ArgT &&... args) {
281   auto *section = make<SectionType>(std::forward<ArgT>(args)...);
282   inputSections.push_back(section);
283   return section;
284 }
285 
286 void Writer::scanRelocations() {
287   for (InputSection *sect : inputSections)
288     for (Reloc &r : sect->relocs)
289       if (auto *s = r.target.dyn_cast<Symbol *>())
290         if (auto *dylibSymbol = dyn_cast<DylibSymbol>(s))
291           in.got->addEntry(*dylibSymbol);
292 }
293 
294 void Writer::createLoadCommands() {
295   headerSection->addLoadCommand(make<LCDyldInfo>(bindingSection));
296   headerSection->addLoadCommand(make<LCLoadDylinker>());
297   headerSection->addLoadCommand(make<LCSymtab>());
298   headerSection->addLoadCommand(make<LCDysymtab>());
299   headerSection->addLoadCommand(make<LCMain>());
300 
301   uint8_t segIndex = 0;
302   for (OutputSegment *seg : outputSegments) {
303     if (seg->isNeeded()) {
304       headerSection->addLoadCommand(make<LCSegment>(seg->name, seg));
305       seg->index = segIndex++;
306     }
307   }
308 
309   uint64_t dylibOrdinal = 1;
310   for (InputFile *file : inputFiles) {
311     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
312       headerSection->addLoadCommand(make<LCLoadDylib>(dylibFile->dylibName));
313       dylibFile->ordinal = dylibOrdinal++;
314     }
315   }
316 
317   // TODO: dyld requires libSystem to be loaded. libSystem is a universal
318   // binary and we don't have support for that yet, so mock it out here.
319   headerSection->addLoadCommand(
320       make<LCLoadDylib>("/usr/lib/libSystem.B.dylib"));
321 }
322 
323 void Writer::createHiddenSections() {
324   headerSection = createInputSection<MachHeaderSection>();
325   bindingSection = createInputSection<BindingSection>();
326   createInputSection<PageZeroSection>();
327 }
328 
329 void Writer::sortSections() {
330   llvm::stable_sort(inputSections, SectionComparator());
331 
332   // TODO This is wrong; input sections ought to be grouped into
333   // output sections, which are then organized like this.
334   uint32_t sectionIndex = 0;
335   // Add input sections to output segments.
336   for (InputSection *isec : inputSections) {
337     if (isec->isNeeded()) {
338       if (!isec->isHidden())
339         isec->sectionIndex = ++sectionIndex;
340       getOrCreateOutputSegment(isec->segname)->addSection(isec);
341     }
342   }
343 }
344 
345 void Writer::assignAddresses(OutputSegment *seg) {
346   addr = alignTo(addr, PageSize);
347   fileOff = alignTo(fileOff, PageSize);
348   seg->fileOff = fileOff;
349 
350   for (auto &p : seg->getSections()) {
351     ArrayRef<InputSection *> sections = p.second;
352     for (InputSection *isec : sections) {
353       addr = alignTo(addr, isec->align);
354       isec->addr = addr;
355       addr += isec->getSize();
356       fileOff += isec->getFileSize();
357     }
358   }
359 }
360 
361 void Writer::openFile() {
362   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
363       FileOutputBuffer::create(config->outputFile, fileOff,
364                                FileOutputBuffer::F_executable);
365 
366   if (!bufferOrErr)
367     error("failed to open " + config->outputFile + ": " +
368           llvm::toString(bufferOrErr.takeError()));
369   else
370     buffer = std::move(*bufferOrErr);
371 }
372 
373 void Writer::writeSections() {
374   uint8_t *buf = buffer->getBufferStart();
375   for (OutputSegment *seg : outputSegments) {
376     uint64_t fileOff = seg->fileOff;
377     for (auto &sect : seg->getSections()) {
378       for (InputSection *isec : sect.second) {
379         isec->writeTo(buf + fileOff);
380         fileOff += isec->getFileSize();
381       }
382     }
383   }
384 }
385 
386 void Writer::run() {
387   scanRelocations();
388   createHiddenSections();
389   // Sort and assign sections to their respective segments. No more sections can
390   // be created after this method runs.
391   sortSections();
392   // dyld requires __LINKEDIT segment to always exist (even if empty).
393   getOrCreateOutputSegment(segment_names::linkEdit);
394   // No more segments can be created after this method runs.
395   createLoadCommands();
396 
397   // Ensure that segments (and the sections they contain) are allocated
398   // addresses in ascending order, which dyld requires.
399   //
400   // Note that at this point, __LINKEDIT sections are empty, but we need to
401   // determine addresses of other segments/sections before generating its
402   // contents.
403   for (OutputSegment *seg : outputSegments)
404     assignAddresses(seg);
405 
406   // Fill __LINKEDIT contents.
407   bindingSection->finalizeContents();
408 
409   // Now that __LINKEDIT is filled out, do a proper calculation of its
410   // addresses and offsets. We don't have to recalculate the other segments
411   // since sortSections() ensures that __LINKEDIT is the last segment.
412   assignAddresses(getOutputSegment(segment_names::linkEdit));
413 
414   openFile();
415   if (errorCount())
416     return;
417 
418   writeSections();
419 
420   if (auto e = buffer->commit())
421     error("failed to write to the output file: " + toString(std::move(e)));
422 }
423 
424 void macho::writeResult() { Writer().run(); }
425 
426 void macho::createSyntheticSections() {
427   in.got = createInputSection<GotSection>();
428 }
429