xref: /llvm-project-15.0.7/lld/MachO/Writer.cpp (revision 6507bc56)
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 "MergedOutputSection.h"
14 #include "OutputSection.h"
15 #include "OutputSegment.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "SyntheticSections.h"
19 #include "Target.h"
20 
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/Support/LEB128.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/Path.h"
27 
28 using namespace llvm;
29 using namespace llvm::MachO;
30 using namespace lld;
31 using namespace lld::macho;
32 
33 namespace {
34 class LCLinkEdit;
35 class LCDyldInfo;
36 class LCSymtab;
37 
38 class Writer {
39 public:
40   Writer() : buffer(errorHandler().outputBuffer) {}
41 
42   void scanRelocations();
43   void createOutputSections();
44   void createLoadCommands();
45   void assignAddresses(OutputSegment *);
46   void createSymtabContents();
47 
48   void openFile();
49   void writeSections();
50 
51   void run();
52 
53   std::unique_ptr<FileOutputBuffer> &buffer;
54   uint64_t addr = 0;
55   uint64_t fileOff = 0;
56   MachHeaderSection *headerSection = nullptr;
57   BindingSection *bindingSection = nullptr;
58   LazyBindingSection *lazyBindingSection = nullptr;
59   ExportSection *exportSection = nullptr;
60   StringTableSection *stringTableSection = nullptr;
61   SymtabSection *symtabSection = nullptr;
62 };
63 
64 // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
65 class LCDyldInfo : public LoadCommand {
66 public:
67   LCDyldInfo(BindingSection *bindingSection,
68              LazyBindingSection *lazyBindingSection,
69              ExportSection *exportSection)
70       : bindingSection(bindingSection), lazyBindingSection(lazyBindingSection),
71         exportSection(exportSection) {}
72 
73   uint32_t getSize() const override { return sizeof(dyld_info_command); }
74 
75   void writeTo(uint8_t *buf) const override {
76     auto *c = reinterpret_cast<dyld_info_command *>(buf);
77     c->cmd = LC_DYLD_INFO_ONLY;
78     c->cmdsize = getSize();
79     if (bindingSection->isNeeded()) {
80       c->bind_off = bindingSection->fileOff;
81       c->bind_size = bindingSection->getFileSize();
82     }
83     if (lazyBindingSection->isNeeded()) {
84       c->lazy_bind_off = lazyBindingSection->fileOff;
85       c->lazy_bind_size = lazyBindingSection->getFileSize();
86     }
87     if (exportSection->isNeeded()) {
88       c->export_off = exportSection->fileOff;
89       c->export_size = exportSection->getFileSize();
90     }
91   }
92 
93   BindingSection *bindingSection;
94   LazyBindingSection *lazyBindingSection;
95   ExportSection *exportSection;
96 };
97 
98 class LCDysymtab : public LoadCommand {
99 public:
100   uint32_t getSize() const override { return sizeof(dysymtab_command); }
101 
102   void writeTo(uint8_t *buf) const override {
103     auto *c = reinterpret_cast<dysymtab_command *>(buf);
104     c->cmd = LC_DYSYMTAB;
105     c->cmdsize = getSize();
106   }
107 };
108 
109 class LCSegment : public LoadCommand {
110 public:
111   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
112 
113   uint32_t getSize() const override {
114     return sizeof(segment_command_64) +
115            seg->numNonHiddenSections() * sizeof(section_64);
116   }
117 
118   void writeTo(uint8_t *buf) const override {
119     auto *c = reinterpret_cast<segment_command_64 *>(buf);
120     buf += sizeof(segment_command_64);
121 
122     c->cmd = LC_SEGMENT_64;
123     c->cmdsize = getSize();
124     memcpy(c->segname, name.data(), name.size());
125     c->fileoff = seg->fileOff;
126     c->maxprot = seg->maxProt;
127     c->initprot = seg->initProt;
128 
129     if (seg->getSections().empty())
130       return;
131 
132     c->vmaddr = seg->firstSection()->addr;
133     c->vmsize =
134         seg->lastSection()->addr + seg->lastSection()->getSize() - c->vmaddr;
135     c->nsects = seg->numNonHiddenSections();
136 
137     for (OutputSection *osec : seg->getSections()) {
138       c->filesize += osec->getFileSize();
139 
140       if (osec->isHidden())
141         continue;
142 
143       auto *sectHdr = reinterpret_cast<section_64 *>(buf);
144       buf += sizeof(section_64);
145 
146       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
147       memcpy(sectHdr->segname, name.data(), name.size());
148 
149       sectHdr->addr = osec->addr;
150       sectHdr->offset = osec->fileOff;
151       sectHdr->align = Log2_32(osec->align);
152       sectHdr->flags = osec->flags;
153       sectHdr->size = osec->getSize();
154     }
155   }
156 
157 private:
158   StringRef name;
159   OutputSegment *seg;
160 };
161 
162 class LCMain : public LoadCommand {
163   uint32_t getSize() const override { return sizeof(entry_point_command); }
164 
165   void writeTo(uint8_t *buf) const override {
166     auto *c = reinterpret_cast<entry_point_command *>(buf);
167     c->cmd = LC_MAIN;
168     c->cmdsize = getSize();
169     c->entryoff = config->entry->getFileOffset();
170     c->stacksize = 0;
171   }
172 };
173 
174 class LCSymtab : public LoadCommand {
175 public:
176   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
177       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
178 
179   uint32_t getSize() const override { return sizeof(symtab_command); }
180 
181   void writeTo(uint8_t *buf) const override {
182     auto *c = reinterpret_cast<symtab_command *>(buf);
183     c->cmd = LC_SYMTAB;
184     c->cmdsize = getSize();
185     c->symoff = symtabSection->fileOff;
186     c->nsyms = symtabSection->getNumSymbols();
187     c->stroff = stringTableSection->fileOff;
188     c->strsize = stringTableSection->getFileSize();
189   }
190 
191   SymtabSection *symtabSection = nullptr;
192   StringTableSection *stringTableSection = nullptr;
193 };
194 
195 // There are several dylib load commands that share the same structure:
196 //   * LC_LOAD_DYLIB
197 //   * LC_ID_DYLIB
198 //   * LC_REEXPORT_DYLIB
199 class LCDylib : public LoadCommand {
200 public:
201   LCDylib(LoadCommandType type, StringRef path) : type(type), path(path) {}
202 
203   uint32_t getSize() const override {
204     return alignTo(sizeof(dylib_command) + path.size() + 1, 8);
205   }
206 
207   void writeTo(uint8_t *buf) const override {
208     auto *c = reinterpret_cast<dylib_command *>(buf);
209     buf += sizeof(dylib_command);
210 
211     c->cmd = type;
212     c->cmdsize = getSize();
213     c->dylib.name = sizeof(dylib_command);
214 
215     memcpy(buf, path.data(), path.size());
216     buf[path.size()] = '\0';
217   }
218 
219 private:
220   LoadCommandType type;
221   StringRef path;
222 };
223 
224 class LCLoadDylinker : public LoadCommand {
225 public:
226   uint32_t getSize() const override {
227     return alignTo(sizeof(dylinker_command) + path.size() + 1, 8);
228   }
229 
230   void writeTo(uint8_t *buf) const override {
231     auto *c = reinterpret_cast<dylinker_command *>(buf);
232     buf += sizeof(dylinker_command);
233 
234     c->cmd = LC_LOAD_DYLINKER;
235     c->cmdsize = getSize();
236     c->name = sizeof(dylinker_command);
237 
238     memcpy(buf, path.data(), path.size());
239     buf[path.size()] = '\0';
240   }
241 
242 private:
243   // Recent versions of Darwin won't run any binary that has dyld at a
244   // different location.
245   const StringRef path = "/usr/lib/dyld";
246 };
247 } // namespace
248 
249 void Writer::scanRelocations() {
250   for (InputSection *isec : inputSections) {
251     for (Reloc &r : isec->relocs) {
252       if (auto *s = r.target.dyn_cast<lld::macho::Symbol *>()) {
253         if (isa<Undefined>(s))
254           error("undefined symbol " + s->getName() + ", referenced from " +
255                 sys::path::filename(isec->file->getName()));
256         else
257           target->prepareSymbolRelocation(*s, r.type);
258       }
259     }
260   }
261 }
262 
263 void Writer::createLoadCommands() {
264   headerSection->addLoadCommand(
265       make<LCDyldInfo>(bindingSection, lazyBindingSection, exportSection));
266   headerSection->addLoadCommand(
267       make<LCSymtab>(symtabSection, stringTableSection));
268   headerSection->addLoadCommand(make<LCDysymtab>());
269 
270   switch (config->outputType) {
271   case MH_EXECUTE:
272     headerSection->addLoadCommand(make<LCMain>());
273     headerSection->addLoadCommand(make<LCLoadDylinker>());
274     break;
275   case MH_DYLIB:
276     headerSection->addLoadCommand(
277         make<LCDylib>(LC_ID_DYLIB, config->installName));
278     break;
279   default:
280     llvm_unreachable("unhandled output file type");
281   }
282 
283   uint8_t segIndex = 0;
284   for (OutputSegment *seg : outputSegments) {
285     headerSection->addLoadCommand(make<LCSegment>(seg->name, seg));
286     seg->index = segIndex++;
287   }
288 
289   uint64_t dylibOrdinal = 1;
290   for (InputFile *file : inputFiles) {
291     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
292       headerSection->addLoadCommand(
293           make<LCDylib>(LC_LOAD_DYLIB, dylibFile->dylibName));
294       dylibFile->ordinal = dylibOrdinal++;
295 
296       if (dylibFile->reexport)
297         headerSection->addLoadCommand(
298             make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->dylibName));
299     }
300   }
301 }
302 
303 static size_t getSymbolPriority(const SymbolPriorityEntry &entry,
304                                 const InputFile &file) {
305   return std::max(entry.objectFiles.lookup(sys::path::filename(file.getName())),
306                   entry.anyObjectFile);
307 }
308 
309 // Each section gets assigned the priority of the highest-priority symbol it
310 // contains.
311 static DenseMap<const InputSection *, size_t> buildInputSectionPriorities() {
312   DenseMap<const InputSection *, size_t> sectionPriorities;
313 
314   if (config->priorities.empty())
315     return sectionPriorities;
316 
317   auto addSym = [&](Defined &sym) {
318     auto it = config->priorities.find(sym.getName());
319     if (it == config->priorities.end())
320       return;
321 
322     SymbolPriorityEntry &entry = it->second;
323     size_t &priority = sectionPriorities[sym.isec];
324     priority = std::max(priority, getSymbolPriority(entry, *sym.isec->file));
325   };
326 
327   // TODO: Make sure this handles weak symbols correctly.
328   for (InputFile *file : inputFiles)
329     if (isa<ObjFile>(file) || isa<ArchiveFile>(file))
330       for (lld::macho::Symbol *sym : file->symbols)
331         if (auto *d = dyn_cast<Defined>(sym))
332           addSym(*d);
333 
334   return sectionPriorities;
335 }
336 
337 static int segmentOrder(OutputSegment *seg) {
338   return StringSwitch<int>(seg->name)
339       .Case(segment_names::pageZero, -2)
340       .Case(segment_names::text, -1)
341       // Make sure __LINKEDIT is the last segment (i.e. all its hidden
342       // sections must be ordered after other sections).
343       .Case(segment_names::linkEdit, std::numeric_limits<int>::max())
344       .Default(0);
345 }
346 
347 static int sectionOrder(OutputSection *osec) {
348   StringRef segname = osec->parent->name;
349   // Sections are uniquely identified by their segment + section name.
350   if (segname == segment_names::text) {
351     if (osec->name == section_names::header)
352       return -1;
353   } else if (segname == segment_names::linkEdit) {
354     return StringSwitch<int>(osec->name)
355         .Case(section_names::binding, -4)
356         .Case(section_names::export_, -3)
357         .Case(section_names::symbolTable, -2)
358         .Case(section_names::stringTable, -1)
359         .Default(0);
360   }
361   return 0;
362 }
363 
364 template <typename T, typename F>
365 static std::function<bool(T, T)> compareByOrder(F ord) {
366   return [=](T a, T b) { return ord(a) < ord(b); };
367 }
368 
369 // Sorting only can happen once all outputs have been collected. Here we sort
370 // segments, output sections within each segment, and input sections within each
371 // output segment.
372 static void sortSegmentsAndSections() {
373   llvm::stable_sort(outputSegments,
374                     compareByOrder<OutputSegment *>(segmentOrder));
375 
376   DenseMap<const InputSection *, size_t> isecPriorities =
377       buildInputSectionPriorities();
378 
379   uint32_t sectionIndex = 0;
380   for (OutputSegment *seg : outputSegments) {
381     seg->sortOutputSections(compareByOrder<OutputSection *>(sectionOrder));
382     for (auto *osec : seg->getSections()) {
383       // Now that the output sections are sorted, assign the final
384       // output section indices.
385       if (!osec->isHidden())
386         osec->index = ++sectionIndex;
387 
388       if (!isecPriorities.empty()) {
389         if (auto *merged = dyn_cast<MergedOutputSection>(osec)) {
390           llvm::stable_sort(merged->inputs,
391                             [&](InputSection *a, InputSection *b) {
392                               return isecPriorities[a] > isecPriorities[b];
393                             });
394         }
395       }
396     }
397   }
398 }
399 
400 void Writer::createOutputSections() {
401   // First, create hidden sections
402   headerSection = make<MachHeaderSection>();
403   bindingSection = make<BindingSection>();
404   lazyBindingSection = make<LazyBindingSection>();
405   stringTableSection = make<StringTableSection>();
406   symtabSection = make<SymtabSection>(*stringTableSection);
407   exportSection = make<ExportSection>();
408 
409   switch (config->outputType) {
410   case MH_EXECUTE:
411     make<PageZeroSection>();
412     break;
413   case MH_DYLIB:
414     break;
415   default:
416     llvm_unreachable("unhandled output file type");
417   }
418 
419   // Then merge input sections into output sections.
420   MapVector<std::pair<StringRef, StringRef>, MergedOutputSection *>
421       mergedOutputSections;
422   for (InputSection *isec : inputSections) {
423     MergedOutputSection *&osec =
424         mergedOutputSections[{isec->segname, isec->name}];
425     if (osec == nullptr)
426       osec = make<MergedOutputSection>(isec->name);
427     osec->mergeInput(isec);
428   }
429 
430   for (const auto &it : mergedOutputSections) {
431     StringRef segname = it.first.first;
432     MergedOutputSection *osec = it.second;
433     getOrCreateOutputSegment(segname)->addOutputSection(osec);
434   }
435 
436   for (SyntheticSection *ssec : syntheticSections) {
437     auto it = mergedOutputSections.find({ssec->segname, ssec->name});
438     if (it == mergedOutputSections.end()) {
439       if (ssec->isNeeded())
440         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
441     } else {
442       error("section from " + it->second->firstSection()->file->getName() +
443             " conflicts with synthetic section " + ssec->segname + "," +
444             ssec->name);
445     }
446   }
447 }
448 
449 void Writer::assignAddresses(OutputSegment *seg) {
450   addr = alignTo(addr, PageSize);
451   fileOff = alignTo(fileOff, PageSize);
452   seg->fileOff = fileOff;
453 
454   for (auto *osec : seg->getSections()) {
455     addr = alignTo(addr, osec->align);
456     fileOff = alignTo(fileOff, osec->align);
457     osec->addr = addr;
458     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
459     osec->finalize();
460 
461     addr += osec->getSize();
462     fileOff += osec->getFileSize();
463   }
464 }
465 
466 void Writer::openFile() {
467   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
468       FileOutputBuffer::create(config->outputFile, fileOff,
469                                FileOutputBuffer::F_executable);
470 
471   if (!bufferOrErr)
472     error("failed to open " + config->outputFile + ": " +
473           llvm::toString(bufferOrErr.takeError()));
474   else
475     buffer = std::move(*bufferOrErr);
476 }
477 
478 void Writer::writeSections() {
479   uint8_t *buf = buffer->getBufferStart();
480   for (OutputSegment *seg : outputSegments)
481     for (OutputSection *osec : seg->getSections())
482       osec->writeTo(buf + osec->fileOff);
483 }
484 
485 void Writer::run() {
486   // dyld requires __LINKEDIT segment to always exist (even if empty).
487   OutputSegment *linkEditSegment =
488       getOrCreateOutputSegment(segment_names::linkEdit);
489 
490   scanRelocations();
491   if (in.stubHelper->isNeeded())
492     in.stubHelper->setup();
493 
494   // Sort and assign sections to their respective segments. No more sections nor
495   // segments may be created after these methods run.
496   createOutputSections();
497   sortSegmentsAndSections();
498 
499   createLoadCommands();
500 
501   // Ensure that segments (and the sections they contain) are allocated
502   // addresses in ascending order, which dyld requires.
503   //
504   // Note that at this point, __LINKEDIT sections are empty, but we need to
505   // determine addresses of other segments/sections before generating its
506   // contents.
507   for (OutputSegment *seg : outputSegments)
508     if (seg != linkEditSegment)
509       assignAddresses(seg);
510 
511   // Fill __LINKEDIT contents.
512   bindingSection->finalizeContents();
513   lazyBindingSection->finalizeContents();
514   exportSection->finalizeContents();
515   symtabSection->finalizeContents();
516 
517   // Now that __LINKEDIT is filled out, do a proper calculation of its
518   // addresses and offsets.
519   assignAddresses(linkEditSegment);
520 
521   openFile();
522   if (errorCount())
523     return;
524 
525   writeSections();
526 
527   if (auto e = buffer->commit())
528     error("failed to write to the output file: " + toString(std::move(e)));
529 }
530 
531 void macho::writeResult() { Writer().run(); }
532 
533 void macho::createSyntheticSections() {
534   in.got = make<GotSection>();
535   in.lazyPointers = make<LazyPointerSection>();
536   in.stubs = make<StubsSection>();
537   in.stubHelper = make<StubHelperSection>();
538   in.imageLoaderCache = make<ImageLoaderCacheSection>();
539 }
540