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