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