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