xref: /freebsd/contrib/llvm-project/lld/MachO/Writer.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
15ffd83dbSDimitry Andric //===- Writer.cpp ---------------------------------------------------------===//
25ffd83dbSDimitry Andric //
35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
65ffd83dbSDimitry Andric //
75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===//
85ffd83dbSDimitry Andric 
95ffd83dbSDimitry Andric #include "Writer.h"
10fe6060f1SDimitry Andric #include "ConcatOutputSection.h"
115ffd83dbSDimitry Andric #include "Config.h"
125ffd83dbSDimitry Andric #include "InputFiles.h"
135ffd83dbSDimitry Andric #include "InputSection.h"
14fe6060f1SDimitry Andric #include "MapFile.h"
155ffd83dbSDimitry Andric #include "OutputSection.h"
165ffd83dbSDimitry Andric #include "OutputSegment.h"
1704eeddc0SDimitry Andric #include "SectionPriorities.h"
185ffd83dbSDimitry Andric #include "SymbolTable.h"
195ffd83dbSDimitry Andric #include "Symbols.h"
205ffd83dbSDimitry Andric #include "SyntheticSections.h"
215ffd83dbSDimitry Andric #include "Target.h"
22e8d8bef9SDimitry Andric #include "UnwindInfoSection.h"
235ffd83dbSDimitry Andric 
24fe6060f1SDimitry Andric #include "lld/Common/Arrays.h"
2504eeddc0SDimitry Andric #include "lld/Common/CommonLinkerContext.h"
265ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h"
27e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h"
285ffd83dbSDimitry Andric #include "llvm/Support/LEB128.h"
29fe6060f1SDimitry Andric #include "llvm/Support/Parallel.h"
305ffd83dbSDimitry Andric #include "llvm/Support/Path.h"
31fe6060f1SDimitry Andric #include "llvm/Support/TimeProfiler.h"
32*0fca6ea1SDimitry Andric #include "llvm/Support/thread.h"
33e8d8bef9SDimitry Andric #include "llvm/Support/xxhash.h"
34e8d8bef9SDimitry Andric 
35e8d8bef9SDimitry Andric #include <algorithm>
365ffd83dbSDimitry Andric 
375ffd83dbSDimitry Andric using namespace llvm;
385ffd83dbSDimitry Andric using namespace llvm::MachO;
39e8d8bef9SDimitry Andric using namespace llvm::sys;
405ffd83dbSDimitry Andric using namespace lld;
415ffd83dbSDimitry Andric using namespace lld::macho;
425ffd83dbSDimitry Andric 
435ffd83dbSDimitry Andric namespace {
44e8d8bef9SDimitry Andric class LCUuid;
455ffd83dbSDimitry Andric 
465ffd83dbSDimitry Andric class Writer {
475ffd83dbSDimitry Andric public:
Writer()485ffd83dbSDimitry Andric   Writer() : buffer(errorHandler().outputBuffer) {}
495ffd83dbSDimitry Andric 
50fe6060f1SDimitry Andric   void treatSpecialUndefineds();
515ffd83dbSDimitry Andric   void scanRelocations();
52e8d8bef9SDimitry Andric   void scanSymbols();
53fe6060f1SDimitry Andric   template <class LP> void createOutputSections();
54fe6060f1SDimitry Andric   template <class LP> void createLoadCommands();
55fe6060f1SDimitry Andric   void finalizeAddresses();
56fe6060f1SDimitry Andric   void finalizeLinkEditSegment();
575ffd83dbSDimitry Andric   void assignAddresses(OutputSegment *);
585ffd83dbSDimitry Andric 
595ffd83dbSDimitry Andric   void openFile();
605ffd83dbSDimitry Andric   void writeSections();
61bdd1243dSDimitry Andric   void applyOptimizationHints();
62bdd1243dSDimitry Andric   void buildFixupChains();
63e8d8bef9SDimitry Andric   void writeUuid();
64fe6060f1SDimitry Andric   void writeCodeSignature();
65fe6060f1SDimitry Andric   void writeOutputFile();
665ffd83dbSDimitry Andric 
67fe6060f1SDimitry Andric   template <class LP> void run();
685ffd83dbSDimitry Andric 
695ffd83dbSDimitry Andric   std::unique_ptr<FileOutputBuffer> &buffer;
705ffd83dbSDimitry Andric   uint64_t addr = 0;
715ffd83dbSDimitry Andric   uint64_t fileOff = 0;
72e8d8bef9SDimitry Andric   MachHeaderSection *header = nullptr;
735ffd83dbSDimitry Andric   StringTableSection *stringTableSection = nullptr;
745ffd83dbSDimitry Andric   SymtabSection *symtabSection = nullptr;
75e8d8bef9SDimitry Andric   IndirectSymtabSection *indirectSymtabSection = nullptr;
76fe6060f1SDimitry Andric   CodeSignatureSection *codeSignatureSection = nullptr;
77fe6060f1SDimitry Andric   DataInCodeSection *dataInCodeSection = nullptr;
78fe6060f1SDimitry Andric   FunctionStartsSection *functionStartsSection = nullptr;
79fe6060f1SDimitry Andric 
80e8d8bef9SDimitry Andric   LCUuid *uuidCommand = nullptr;
81fe6060f1SDimitry Andric   OutputSegment *linkEditSegment = nullptr;
825ffd83dbSDimitry Andric };
835ffd83dbSDimitry Andric 
845ffd83dbSDimitry Andric // LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.
85fe6060f1SDimitry Andric class LCDyldInfo final : public LoadCommand {
865ffd83dbSDimitry Andric public:
LCDyldInfo(RebaseSection * rebaseSection,BindingSection * bindingSection,WeakBindingSection * weakBindingSection,LazyBindingSection * lazyBindingSection,ExportSection * exportSection)87e8d8bef9SDimitry Andric   LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,
88e8d8bef9SDimitry Andric              WeakBindingSection *weakBindingSection,
895ffd83dbSDimitry Andric              LazyBindingSection *lazyBindingSection,
905ffd83dbSDimitry Andric              ExportSection *exportSection)
91e8d8bef9SDimitry Andric       : rebaseSection(rebaseSection), bindingSection(bindingSection),
92e8d8bef9SDimitry Andric         weakBindingSection(weakBindingSection),
93e8d8bef9SDimitry Andric         lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}
945ffd83dbSDimitry Andric 
getSize() const955ffd83dbSDimitry Andric   uint32_t getSize() const override { return sizeof(dyld_info_command); }
965ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const975ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
985ffd83dbSDimitry Andric     auto *c = reinterpret_cast<dyld_info_command *>(buf);
995ffd83dbSDimitry Andric     c->cmd = LC_DYLD_INFO_ONLY;
1005ffd83dbSDimitry Andric     c->cmdsize = getSize();
101e8d8bef9SDimitry Andric     if (rebaseSection->isNeeded()) {
102e8d8bef9SDimitry Andric       c->rebase_off = rebaseSection->fileOff;
103e8d8bef9SDimitry Andric       c->rebase_size = rebaseSection->getFileSize();
104e8d8bef9SDimitry Andric     }
1055ffd83dbSDimitry Andric     if (bindingSection->isNeeded()) {
1065ffd83dbSDimitry Andric       c->bind_off = bindingSection->fileOff;
1075ffd83dbSDimitry Andric       c->bind_size = bindingSection->getFileSize();
1085ffd83dbSDimitry Andric     }
109e8d8bef9SDimitry Andric     if (weakBindingSection->isNeeded()) {
110e8d8bef9SDimitry Andric       c->weak_bind_off = weakBindingSection->fileOff;
111e8d8bef9SDimitry Andric       c->weak_bind_size = weakBindingSection->getFileSize();
112e8d8bef9SDimitry Andric     }
1135ffd83dbSDimitry Andric     if (lazyBindingSection->isNeeded()) {
1145ffd83dbSDimitry Andric       c->lazy_bind_off = lazyBindingSection->fileOff;
1155ffd83dbSDimitry Andric       c->lazy_bind_size = lazyBindingSection->getFileSize();
1165ffd83dbSDimitry Andric     }
1175ffd83dbSDimitry Andric     if (exportSection->isNeeded()) {
1185ffd83dbSDimitry Andric       c->export_off = exportSection->fileOff;
1195ffd83dbSDimitry Andric       c->export_size = exportSection->getFileSize();
1205ffd83dbSDimitry Andric     }
1215ffd83dbSDimitry Andric   }
1225ffd83dbSDimitry Andric 
123e8d8bef9SDimitry Andric   RebaseSection *rebaseSection;
1245ffd83dbSDimitry Andric   BindingSection *bindingSection;
125e8d8bef9SDimitry Andric   WeakBindingSection *weakBindingSection;
1265ffd83dbSDimitry Andric   LazyBindingSection *lazyBindingSection;
1275ffd83dbSDimitry Andric   ExportSection *exportSection;
1285ffd83dbSDimitry Andric };
1295ffd83dbSDimitry Andric 
130fe6060f1SDimitry Andric class LCSubFramework final : public LoadCommand {
131fe6060f1SDimitry Andric public:
LCSubFramework(StringRef umbrella)132fe6060f1SDimitry Andric   LCSubFramework(StringRef umbrella) : umbrella(umbrella) {}
133fe6060f1SDimitry Andric 
getSize() const134fe6060f1SDimitry Andric   uint32_t getSize() const override {
135bdd1243dSDimitry Andric     return alignToPowerOf2(sizeof(sub_framework_command) + umbrella.size() + 1,
136fe6060f1SDimitry Andric                            target->wordSize);
137fe6060f1SDimitry Andric   }
138fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const139fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
140fe6060f1SDimitry Andric     auto *c = reinterpret_cast<sub_framework_command *>(buf);
141fe6060f1SDimitry Andric     buf += sizeof(sub_framework_command);
142fe6060f1SDimitry Andric 
143fe6060f1SDimitry Andric     c->cmd = LC_SUB_FRAMEWORK;
144fe6060f1SDimitry Andric     c->cmdsize = getSize();
145fe6060f1SDimitry Andric     c->umbrella = sizeof(sub_framework_command);
146fe6060f1SDimitry Andric 
147fe6060f1SDimitry Andric     memcpy(buf, umbrella.data(), umbrella.size());
148fe6060f1SDimitry Andric     buf[umbrella.size()] = '\0';
149fe6060f1SDimitry Andric   }
150fe6060f1SDimitry Andric 
151fe6060f1SDimitry Andric private:
152fe6060f1SDimitry Andric   const StringRef umbrella;
153fe6060f1SDimitry Andric };
154fe6060f1SDimitry Andric 
155fe6060f1SDimitry Andric class LCFunctionStarts final : public LoadCommand {
156fe6060f1SDimitry Andric public:
LCFunctionStarts(FunctionStartsSection * functionStartsSection)157fe6060f1SDimitry Andric   explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)
158fe6060f1SDimitry Andric       : functionStartsSection(functionStartsSection) {}
159fe6060f1SDimitry Andric 
getSize() const160fe6060f1SDimitry Andric   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
161fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const162fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
163fe6060f1SDimitry Andric     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
164fe6060f1SDimitry Andric     c->cmd = LC_FUNCTION_STARTS;
165fe6060f1SDimitry Andric     c->cmdsize = getSize();
166fe6060f1SDimitry Andric     c->dataoff = functionStartsSection->fileOff;
167fe6060f1SDimitry Andric     c->datasize = functionStartsSection->getFileSize();
168fe6060f1SDimitry Andric   }
169fe6060f1SDimitry Andric 
170fe6060f1SDimitry Andric private:
171fe6060f1SDimitry Andric   FunctionStartsSection *functionStartsSection;
172fe6060f1SDimitry Andric };
173fe6060f1SDimitry Andric 
174fe6060f1SDimitry Andric class LCDataInCode final : public LoadCommand {
175fe6060f1SDimitry Andric public:
LCDataInCode(DataInCodeSection * dataInCodeSection)176fe6060f1SDimitry Andric   explicit LCDataInCode(DataInCodeSection *dataInCodeSection)
177fe6060f1SDimitry Andric       : dataInCodeSection(dataInCodeSection) {}
178fe6060f1SDimitry Andric 
getSize() const179fe6060f1SDimitry Andric   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
180fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const181fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
182fe6060f1SDimitry Andric     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
183fe6060f1SDimitry Andric     c->cmd = LC_DATA_IN_CODE;
184fe6060f1SDimitry Andric     c->cmdsize = getSize();
185fe6060f1SDimitry Andric     c->dataoff = dataInCodeSection->fileOff;
186fe6060f1SDimitry Andric     c->datasize = dataInCodeSection->getFileSize();
187fe6060f1SDimitry Andric   }
188fe6060f1SDimitry Andric 
189fe6060f1SDimitry Andric private:
190fe6060f1SDimitry Andric   DataInCodeSection *dataInCodeSection;
191fe6060f1SDimitry Andric };
192fe6060f1SDimitry Andric 
193fe6060f1SDimitry Andric class LCDysymtab final : public LoadCommand {
1945ffd83dbSDimitry Andric public:
LCDysymtab(SymtabSection * symtabSection,IndirectSymtabSection * indirectSymtabSection)195e8d8bef9SDimitry Andric   LCDysymtab(SymtabSection *symtabSection,
196e8d8bef9SDimitry Andric              IndirectSymtabSection *indirectSymtabSection)
197e8d8bef9SDimitry Andric       : symtabSection(symtabSection),
198e8d8bef9SDimitry Andric         indirectSymtabSection(indirectSymtabSection) {}
199e8d8bef9SDimitry Andric 
getSize() const2005ffd83dbSDimitry Andric   uint32_t getSize() const override { return sizeof(dysymtab_command); }
2015ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const2025ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
2035ffd83dbSDimitry Andric     auto *c = reinterpret_cast<dysymtab_command *>(buf);
2045ffd83dbSDimitry Andric     c->cmd = LC_DYSYMTAB;
2055ffd83dbSDimitry Andric     c->cmdsize = getSize();
206e8d8bef9SDimitry Andric 
207e8d8bef9SDimitry Andric     c->ilocalsym = 0;
208e8d8bef9SDimitry Andric     c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();
209e8d8bef9SDimitry Andric     c->nextdefsym = symtabSection->getNumExternalSymbols();
210e8d8bef9SDimitry Andric     c->iundefsym = c->iextdefsym + c->nextdefsym;
211e8d8bef9SDimitry Andric     c->nundefsym = symtabSection->getNumUndefinedSymbols();
212e8d8bef9SDimitry Andric 
213e8d8bef9SDimitry Andric     c->indirectsymoff = indirectSymtabSection->fileOff;
214e8d8bef9SDimitry Andric     c->nindirectsyms = indirectSymtabSection->getNumSymbols();
2155ffd83dbSDimitry Andric   }
216e8d8bef9SDimitry Andric 
217e8d8bef9SDimitry Andric   SymtabSection *symtabSection;
218e8d8bef9SDimitry Andric   IndirectSymtabSection *indirectSymtabSection;
2195ffd83dbSDimitry Andric };
2205ffd83dbSDimitry Andric 
221fe6060f1SDimitry Andric template <class LP> class LCSegment final : public LoadCommand {
2225ffd83dbSDimitry Andric public:
LCSegment(StringRef name,OutputSegment * seg)2235ffd83dbSDimitry Andric   LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}
2245ffd83dbSDimitry Andric 
getSize() const2255ffd83dbSDimitry Andric   uint32_t getSize() const override {
226fe6060f1SDimitry Andric     return sizeof(typename LP::segment_command) +
227fe6060f1SDimitry Andric            seg->numNonHiddenSections() * sizeof(typename LP::section);
2285ffd83dbSDimitry Andric   }
2295ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const2305ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
231fe6060f1SDimitry Andric     using SegmentCommand = typename LP::segment_command;
232349cc55cSDimitry Andric     using SectionHeader = typename LP::section;
2335ffd83dbSDimitry Andric 
234fe6060f1SDimitry Andric     auto *c = reinterpret_cast<SegmentCommand *>(buf);
235fe6060f1SDimitry Andric     buf += sizeof(SegmentCommand);
236fe6060f1SDimitry Andric 
237fe6060f1SDimitry Andric     c->cmd = LP::segmentLCType;
2385ffd83dbSDimitry Andric     c->cmdsize = getSize();
2395ffd83dbSDimitry Andric     memcpy(c->segname, name.data(), name.size());
2405ffd83dbSDimitry Andric     c->fileoff = seg->fileOff;
2415ffd83dbSDimitry Andric     c->maxprot = seg->maxProt;
2425ffd83dbSDimitry Andric     c->initprot = seg->initProt;
2435ffd83dbSDimitry Andric 
244fe6060f1SDimitry Andric     c->vmaddr = seg->addr;
245fe6060f1SDimitry Andric     c->vmsize = seg->vmSize;
246fe6060f1SDimitry Andric     c->filesize = seg->fileSize;
2475ffd83dbSDimitry Andric     c->nsects = seg->numNonHiddenSections();
248bdd1243dSDimitry Andric     c->flags = seg->flags;
2495ffd83dbSDimitry Andric 
250fe6060f1SDimitry Andric     for (const OutputSection *osec : seg->getSections()) {
2515ffd83dbSDimitry Andric       if (osec->isHidden())
2525ffd83dbSDimitry Andric         continue;
2535ffd83dbSDimitry Andric 
254349cc55cSDimitry Andric       auto *sectHdr = reinterpret_cast<SectionHeader *>(buf);
255349cc55cSDimitry Andric       buf += sizeof(SectionHeader);
2565ffd83dbSDimitry Andric 
2575ffd83dbSDimitry Andric       memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());
2585ffd83dbSDimitry Andric       memcpy(sectHdr->segname, name.data(), name.size());
2595ffd83dbSDimitry Andric 
2605ffd83dbSDimitry Andric       sectHdr->addr = osec->addr;
2615ffd83dbSDimitry Andric       sectHdr->offset = osec->fileOff;
2625ffd83dbSDimitry Andric       sectHdr->align = Log2_32(osec->align);
2635ffd83dbSDimitry Andric       sectHdr->flags = osec->flags;
2645ffd83dbSDimitry Andric       sectHdr->size = osec->getSize();
265e8d8bef9SDimitry Andric       sectHdr->reserved1 = osec->reserved1;
266e8d8bef9SDimitry Andric       sectHdr->reserved2 = osec->reserved2;
2675ffd83dbSDimitry Andric     }
2685ffd83dbSDimitry Andric   }
2695ffd83dbSDimitry Andric 
2705ffd83dbSDimitry Andric private:
2715ffd83dbSDimitry Andric   StringRef name;
2725ffd83dbSDimitry Andric   OutputSegment *seg;
2735ffd83dbSDimitry Andric };
2745ffd83dbSDimitry Andric 
275fe6060f1SDimitry Andric class LCMain final : public LoadCommand {
getSize() const276fe6060f1SDimitry Andric   uint32_t getSize() const override {
277fe6060f1SDimitry Andric     return sizeof(structs::entry_point_command);
278fe6060f1SDimitry Andric   }
2795ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const2805ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
281fe6060f1SDimitry Andric     auto *c = reinterpret_cast<structs::entry_point_command *>(buf);
2825ffd83dbSDimitry Andric     c->cmd = LC_MAIN;
2835ffd83dbSDimitry Andric     c->cmdsize = getSize();
284e8d8bef9SDimitry Andric 
285e8d8bef9SDimitry Andric     if (config->entry->isInStubs())
286e8d8bef9SDimitry Andric       c->entryoff =
287e8d8bef9SDimitry Andric           in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;
288e8d8bef9SDimitry Andric     else
289fe6060f1SDimitry Andric       c->entryoff = config->entry->getVA() - in.header->addr;
290e8d8bef9SDimitry Andric 
2915ffd83dbSDimitry Andric     c->stacksize = 0;
2925ffd83dbSDimitry Andric   }
2935ffd83dbSDimitry Andric };
2945ffd83dbSDimitry Andric 
295fe6060f1SDimitry Andric class LCSymtab final : public LoadCommand {
2965ffd83dbSDimitry Andric public:
LCSymtab(SymtabSection * symtabSection,StringTableSection * stringTableSection)2975ffd83dbSDimitry Andric   LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)
2985ffd83dbSDimitry Andric       : symtabSection(symtabSection), stringTableSection(stringTableSection) {}
2995ffd83dbSDimitry Andric 
getSize() const3005ffd83dbSDimitry Andric   uint32_t getSize() const override { return sizeof(symtab_command); }
3015ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const3025ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
3035ffd83dbSDimitry Andric     auto *c = reinterpret_cast<symtab_command *>(buf);
3045ffd83dbSDimitry Andric     c->cmd = LC_SYMTAB;
3055ffd83dbSDimitry Andric     c->cmdsize = getSize();
3065ffd83dbSDimitry Andric     c->symoff = symtabSection->fileOff;
3075ffd83dbSDimitry Andric     c->nsyms = symtabSection->getNumSymbols();
3085ffd83dbSDimitry Andric     c->stroff = stringTableSection->fileOff;
3095ffd83dbSDimitry Andric     c->strsize = stringTableSection->getFileSize();
3105ffd83dbSDimitry Andric   }
3115ffd83dbSDimitry Andric 
3125ffd83dbSDimitry Andric   SymtabSection *symtabSection = nullptr;
3135ffd83dbSDimitry Andric   StringTableSection *stringTableSection = nullptr;
3145ffd83dbSDimitry Andric };
3155ffd83dbSDimitry Andric 
3165ffd83dbSDimitry Andric // There are several dylib load commands that share the same structure:
3175ffd83dbSDimitry Andric //   * LC_LOAD_DYLIB
3185ffd83dbSDimitry Andric //   * LC_ID_DYLIB
3195ffd83dbSDimitry Andric //   * LC_REEXPORT_DYLIB
320fe6060f1SDimitry Andric class LCDylib final : public LoadCommand {
3215ffd83dbSDimitry Andric public:
LCDylib(LoadCommandType type,StringRef path,uint32_t compatibilityVersion=0,uint32_t currentVersion=0)322e8d8bef9SDimitry Andric   LCDylib(LoadCommandType type, StringRef path,
323e8d8bef9SDimitry Andric           uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)
324e8d8bef9SDimitry Andric       : type(type), path(path), compatibilityVersion(compatibilityVersion),
325e8d8bef9SDimitry Andric         currentVersion(currentVersion) {
326e8d8bef9SDimitry Andric     instanceCount++;
327e8d8bef9SDimitry Andric   }
3285ffd83dbSDimitry Andric 
getSize() const3295ffd83dbSDimitry Andric   uint32_t getSize() const override {
330bdd1243dSDimitry Andric     return alignToPowerOf2(sizeof(dylib_command) + path.size() + 1,
331bdd1243dSDimitry Andric                            target->wordSize);
3325ffd83dbSDimitry Andric   }
3335ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const3345ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
3355ffd83dbSDimitry Andric     auto *c = reinterpret_cast<dylib_command *>(buf);
3365ffd83dbSDimitry Andric     buf += sizeof(dylib_command);
3375ffd83dbSDimitry Andric 
3385ffd83dbSDimitry Andric     c->cmd = type;
3395ffd83dbSDimitry Andric     c->cmdsize = getSize();
3405ffd83dbSDimitry Andric     c->dylib.name = sizeof(dylib_command);
341e8d8bef9SDimitry Andric     c->dylib.timestamp = 0;
342e8d8bef9SDimitry Andric     c->dylib.compatibility_version = compatibilityVersion;
343e8d8bef9SDimitry Andric     c->dylib.current_version = currentVersion;
3445ffd83dbSDimitry Andric 
3455ffd83dbSDimitry Andric     memcpy(buf, path.data(), path.size());
3465ffd83dbSDimitry Andric     buf[path.size()] = '\0';
3475ffd83dbSDimitry Andric   }
3485ffd83dbSDimitry Andric 
getInstanceCount()349e8d8bef9SDimitry Andric   static uint32_t getInstanceCount() { return instanceCount; }
resetInstanceCount()350349cc55cSDimitry Andric   static void resetInstanceCount() { instanceCount = 0; }
351e8d8bef9SDimitry Andric 
3525ffd83dbSDimitry Andric private:
3535ffd83dbSDimitry Andric   LoadCommandType type;
3545ffd83dbSDimitry Andric   StringRef path;
355e8d8bef9SDimitry Andric   uint32_t compatibilityVersion;
356e8d8bef9SDimitry Andric   uint32_t currentVersion;
357e8d8bef9SDimitry Andric   static uint32_t instanceCount;
3585ffd83dbSDimitry Andric };
3595ffd83dbSDimitry Andric 
360e8d8bef9SDimitry Andric uint32_t LCDylib::instanceCount = 0;
361e8d8bef9SDimitry Andric 
362fe6060f1SDimitry Andric class LCLoadDylinker final : public LoadCommand {
3635ffd83dbSDimitry Andric public:
getSize() const3645ffd83dbSDimitry Andric   uint32_t getSize() const override {
365bdd1243dSDimitry Andric     return alignToPowerOf2(sizeof(dylinker_command) + path.size() + 1,
366bdd1243dSDimitry Andric                            target->wordSize);
3675ffd83dbSDimitry Andric   }
3685ffd83dbSDimitry Andric 
writeTo(uint8_t * buf) const3695ffd83dbSDimitry Andric   void writeTo(uint8_t *buf) const override {
3705ffd83dbSDimitry Andric     auto *c = reinterpret_cast<dylinker_command *>(buf);
3715ffd83dbSDimitry Andric     buf += sizeof(dylinker_command);
3725ffd83dbSDimitry Andric 
3735ffd83dbSDimitry Andric     c->cmd = LC_LOAD_DYLINKER;
3745ffd83dbSDimitry Andric     c->cmdsize = getSize();
3755ffd83dbSDimitry Andric     c->name = sizeof(dylinker_command);
3765ffd83dbSDimitry Andric 
3775ffd83dbSDimitry Andric     memcpy(buf, path.data(), path.size());
3785ffd83dbSDimitry Andric     buf[path.size()] = '\0';
3795ffd83dbSDimitry Andric   }
3805ffd83dbSDimitry Andric 
3815ffd83dbSDimitry Andric private:
3825ffd83dbSDimitry Andric   // Recent versions of Darwin won't run any binary that has dyld at a
3835ffd83dbSDimitry Andric   // different location.
3845ffd83dbSDimitry Andric   const StringRef path = "/usr/lib/dyld";
3855ffd83dbSDimitry Andric };
386e8d8bef9SDimitry Andric 
387fe6060f1SDimitry Andric class LCRPath final : public LoadCommand {
388e8d8bef9SDimitry Andric public:
LCRPath(StringRef path)389fe6060f1SDimitry Andric   explicit LCRPath(StringRef path) : path(path) {}
390e8d8bef9SDimitry Andric 
getSize() const391e8d8bef9SDimitry Andric   uint32_t getSize() const override {
392bdd1243dSDimitry Andric     return alignToPowerOf2(sizeof(rpath_command) + path.size() + 1,
393bdd1243dSDimitry Andric                            target->wordSize);
394e8d8bef9SDimitry Andric   }
395e8d8bef9SDimitry Andric 
writeTo(uint8_t * buf) const396e8d8bef9SDimitry Andric   void writeTo(uint8_t *buf) const override {
397e8d8bef9SDimitry Andric     auto *c = reinterpret_cast<rpath_command *>(buf);
398e8d8bef9SDimitry Andric     buf += sizeof(rpath_command);
399e8d8bef9SDimitry Andric 
400e8d8bef9SDimitry Andric     c->cmd = LC_RPATH;
401e8d8bef9SDimitry Andric     c->cmdsize = getSize();
402e8d8bef9SDimitry Andric     c->path = sizeof(rpath_command);
403e8d8bef9SDimitry Andric 
404e8d8bef9SDimitry Andric     memcpy(buf, path.data(), path.size());
405e8d8bef9SDimitry Andric     buf[path.size()] = '\0';
406e8d8bef9SDimitry Andric   }
407e8d8bef9SDimitry Andric 
408e8d8bef9SDimitry Andric private:
409e8d8bef9SDimitry Andric   StringRef path;
410e8d8bef9SDimitry Andric };
411e8d8bef9SDimitry Andric 
412bdd1243dSDimitry Andric class LCDyldEnv final : public LoadCommand {
413bdd1243dSDimitry Andric public:
LCDyldEnv(StringRef name)414bdd1243dSDimitry Andric   explicit LCDyldEnv(StringRef name) : name(name) {}
415bdd1243dSDimitry Andric 
getSize() const416bdd1243dSDimitry Andric   uint32_t getSize() const override {
417bdd1243dSDimitry Andric     return alignToPowerOf2(sizeof(dyld_env_command) + name.size() + 1,
418bdd1243dSDimitry Andric                            target->wordSize);
419bdd1243dSDimitry Andric   }
420bdd1243dSDimitry Andric 
writeTo(uint8_t * buf) const421bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) const override {
422bdd1243dSDimitry Andric     auto *c = reinterpret_cast<dyld_env_command *>(buf);
423bdd1243dSDimitry Andric     buf += sizeof(dyld_env_command);
424bdd1243dSDimitry Andric 
425bdd1243dSDimitry Andric     c->cmd = LC_DYLD_ENVIRONMENT;
426bdd1243dSDimitry Andric     c->cmdsize = getSize();
427bdd1243dSDimitry Andric     c->name = sizeof(dyld_env_command);
428bdd1243dSDimitry Andric 
429bdd1243dSDimitry Andric     memcpy(buf, name.data(), name.size());
430bdd1243dSDimitry Andric     buf[name.size()] = '\0';
431bdd1243dSDimitry Andric   }
432bdd1243dSDimitry Andric 
433bdd1243dSDimitry Andric private:
434bdd1243dSDimitry Andric   StringRef name;
435bdd1243dSDimitry Andric };
436bdd1243dSDimitry Andric 
437fe6060f1SDimitry Andric class LCMinVersion final : public LoadCommand {
438e8d8bef9SDimitry Andric public:
LCMinVersion(const PlatformInfo & platformInfo)439fe6060f1SDimitry Andric   explicit LCMinVersion(const PlatformInfo &platformInfo)
440fe6060f1SDimitry Andric       : platformInfo(platformInfo) {}
441fe6060f1SDimitry Andric 
getSize() const442fe6060f1SDimitry Andric   uint32_t getSize() const override { return sizeof(version_min_command); }
443fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const444fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
445fe6060f1SDimitry Andric     auto *c = reinterpret_cast<version_min_command *>(buf);
446fe6060f1SDimitry Andric     switch (platformInfo.target.Platform) {
44704eeddc0SDimitry Andric     case PLATFORM_MACOS:
448fe6060f1SDimitry Andric       c->cmd = LC_VERSION_MIN_MACOSX;
449fe6060f1SDimitry Andric       break;
45004eeddc0SDimitry Andric     case PLATFORM_IOS:
45104eeddc0SDimitry Andric     case PLATFORM_IOSSIMULATOR:
452fe6060f1SDimitry Andric       c->cmd = LC_VERSION_MIN_IPHONEOS;
453fe6060f1SDimitry Andric       break;
45404eeddc0SDimitry Andric     case PLATFORM_TVOS:
45504eeddc0SDimitry Andric     case PLATFORM_TVOSSIMULATOR:
456fe6060f1SDimitry Andric       c->cmd = LC_VERSION_MIN_TVOS;
457fe6060f1SDimitry Andric       break;
45804eeddc0SDimitry Andric     case PLATFORM_WATCHOS:
45904eeddc0SDimitry Andric     case PLATFORM_WATCHOSSIMULATOR:
460fe6060f1SDimitry Andric       c->cmd = LC_VERSION_MIN_WATCHOS;
461fe6060f1SDimitry Andric       break;
462fe6060f1SDimitry Andric     default:
463fe6060f1SDimitry Andric       llvm_unreachable("invalid platform");
464fe6060f1SDimitry Andric       break;
465fe6060f1SDimitry Andric     }
466fe6060f1SDimitry Andric     c->cmdsize = getSize();
46706c3fb27SDimitry Andric     c->version = encodeVersion(platformInfo.target.MinDeployment);
468fe6060f1SDimitry Andric     c->sdk = encodeVersion(platformInfo.sdk);
469fe6060f1SDimitry Andric   }
470fe6060f1SDimitry Andric 
471fe6060f1SDimitry Andric private:
472fe6060f1SDimitry Andric   const PlatformInfo &platformInfo;
473fe6060f1SDimitry Andric };
474fe6060f1SDimitry Andric 
475fe6060f1SDimitry Andric class LCBuildVersion final : public LoadCommand {
476fe6060f1SDimitry Andric public:
LCBuildVersion(const PlatformInfo & platformInfo)477fe6060f1SDimitry Andric   explicit LCBuildVersion(const PlatformInfo &platformInfo)
478fe6060f1SDimitry Andric       : platformInfo(platformInfo) {}
479e8d8bef9SDimitry Andric 
480e8d8bef9SDimitry Andric   const int ntools = 1;
481e8d8bef9SDimitry Andric 
getSize() const482e8d8bef9SDimitry Andric   uint32_t getSize() const override {
483e8d8bef9SDimitry Andric     return sizeof(build_version_command) + ntools * sizeof(build_tool_version);
484e8d8bef9SDimitry Andric   }
485e8d8bef9SDimitry Andric 
writeTo(uint8_t * buf) const486e8d8bef9SDimitry Andric   void writeTo(uint8_t *buf) const override {
487e8d8bef9SDimitry Andric     auto *c = reinterpret_cast<build_version_command *>(buf);
488e8d8bef9SDimitry Andric     c->cmd = LC_BUILD_VERSION;
489e8d8bef9SDimitry Andric     c->cmdsize = getSize();
49081ad6265SDimitry Andric 
491fe6060f1SDimitry Andric     c->platform = static_cast<uint32_t>(platformInfo.target.Platform);
49206c3fb27SDimitry Andric     c->minos = encodeVersion(platformInfo.target.MinDeployment);
493fe6060f1SDimitry Andric     c->sdk = encodeVersion(platformInfo.sdk);
49481ad6265SDimitry Andric 
495e8d8bef9SDimitry Andric     c->ntools = ntools;
496e8d8bef9SDimitry Andric     auto *t = reinterpret_cast<build_tool_version *>(&c[1]);
49706c3fb27SDimitry Andric     t->tool = TOOL_LLD;
498fe6060f1SDimitry Andric     t->version = encodeVersion(VersionTuple(
499fe6060f1SDimitry Andric         LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));
500e8d8bef9SDimitry Andric   }
501e8d8bef9SDimitry Andric 
502fe6060f1SDimitry Andric private:
503fe6060f1SDimitry Andric   const PlatformInfo &platformInfo;
504e8d8bef9SDimitry Andric };
505e8d8bef9SDimitry Andric 
506e8d8bef9SDimitry Andric // Stores a unique identifier for the output file based on an MD5 hash of its
507e8d8bef9SDimitry Andric // contents. In order to hash the contents, we must first write them, but
508e8d8bef9SDimitry Andric // LC_UUID itself must be part of the written contents in order for all the
509e8d8bef9SDimitry Andric // offsets to be calculated correctly. We resolve this circular paradox by
510e8d8bef9SDimitry Andric // first writing an LC_UUID with an all-zero UUID, then updating the UUID with
511e8d8bef9SDimitry Andric // its real value later.
512fe6060f1SDimitry Andric class LCUuid final : public LoadCommand {
513e8d8bef9SDimitry Andric public:
getSize() const514e8d8bef9SDimitry Andric   uint32_t getSize() const override { return sizeof(uuid_command); }
515e8d8bef9SDimitry Andric 
writeTo(uint8_t * buf) const516e8d8bef9SDimitry Andric   void writeTo(uint8_t *buf) const override {
517e8d8bef9SDimitry Andric     auto *c = reinterpret_cast<uuid_command *>(buf);
518e8d8bef9SDimitry Andric     c->cmd = LC_UUID;
519e8d8bef9SDimitry Andric     c->cmdsize = getSize();
520e8d8bef9SDimitry Andric     uuidBuf = c->uuid;
521e8d8bef9SDimitry Andric   }
522e8d8bef9SDimitry Andric 
writeUuid(uint64_t digest) const523e8d8bef9SDimitry Andric   void writeUuid(uint64_t digest) const {
524e8d8bef9SDimitry Andric     // xxhash only gives us 8 bytes, so put some fixed data in the other half.
525e8d8bef9SDimitry Andric     static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");
526e8d8bef9SDimitry Andric     memcpy(uuidBuf, "LLD\xa1UU1D", 8);
527e8d8bef9SDimitry Andric     memcpy(uuidBuf + 8, &digest, 8);
528e8d8bef9SDimitry Andric 
529e8d8bef9SDimitry Andric     // RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in
530e8d8bef9SDimitry Andric     // byte 8. Byte 6 is already fine due to the fixed data we put in. We don't
531e8d8bef9SDimitry Andric     // want to lose bits of the digest in byte 8, so swap that with a byte of
532e8d8bef9SDimitry Andric     // fixed data that happens to have the right bits set.
533e8d8bef9SDimitry Andric     std::swap(uuidBuf[3], uuidBuf[8]);
534e8d8bef9SDimitry Andric 
535e8d8bef9SDimitry Andric     // Claim that this is an MD5-based hash. It isn't, but this signals that
536e8d8bef9SDimitry Andric     // this is not a time-based and not a random hash. MD5 seems like the least
537e8d8bef9SDimitry Andric     // bad lie we can put here.
538e8d8bef9SDimitry Andric     assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");
539e8d8bef9SDimitry Andric     assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");
540e8d8bef9SDimitry Andric   }
541e8d8bef9SDimitry Andric 
542e8d8bef9SDimitry Andric   mutable uint8_t *uuidBuf;
543e8d8bef9SDimitry Andric };
544e8d8bef9SDimitry Andric 
545fe6060f1SDimitry Andric template <class LP> class LCEncryptionInfo final : public LoadCommand {
546fe6060f1SDimitry Andric public:
getSize() const547fe6060f1SDimitry Andric   uint32_t getSize() const override {
548fe6060f1SDimitry Andric     return sizeof(typename LP::encryption_info_command);
549fe6060f1SDimitry Andric   }
550fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const551fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
552fe6060f1SDimitry Andric     using EncryptionInfo = typename LP::encryption_info_command;
553fe6060f1SDimitry Andric     auto *c = reinterpret_cast<EncryptionInfo *>(buf);
554fe6060f1SDimitry Andric     buf += sizeof(EncryptionInfo);
555fe6060f1SDimitry Andric     c->cmd = LP::encryptionInfoLCType;
556fe6060f1SDimitry Andric     c->cmdsize = getSize();
557fe6060f1SDimitry Andric     c->cryptoff = in.header->getSize();
558fe6060f1SDimitry Andric     auto it = find_if(outputSegments, [](const OutputSegment *seg) {
559fe6060f1SDimitry Andric       return seg->name == segment_names::text;
560fe6060f1SDimitry Andric     });
561fe6060f1SDimitry Andric     assert(it != outputSegments.end());
562fe6060f1SDimitry Andric     c->cryptsize = (*it)->fileSize - c->cryptoff;
563fe6060f1SDimitry Andric   }
564fe6060f1SDimitry Andric };
565fe6060f1SDimitry Andric 
566fe6060f1SDimitry Andric class LCCodeSignature final : public LoadCommand {
567fe6060f1SDimitry Andric public:
LCCodeSignature(CodeSignatureSection * section)568fe6060f1SDimitry Andric   LCCodeSignature(CodeSignatureSection *section) : section(section) {}
569fe6060f1SDimitry Andric 
getSize() const570fe6060f1SDimitry Andric   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
571fe6060f1SDimitry Andric 
writeTo(uint8_t * buf) const572fe6060f1SDimitry Andric   void writeTo(uint8_t *buf) const override {
573fe6060f1SDimitry Andric     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
574fe6060f1SDimitry Andric     c->cmd = LC_CODE_SIGNATURE;
575fe6060f1SDimitry Andric     c->cmdsize = getSize();
576fe6060f1SDimitry Andric     c->dataoff = static_cast<uint32_t>(section->fileOff);
577fe6060f1SDimitry Andric     c->datasize = section->getSize();
578fe6060f1SDimitry Andric   }
579fe6060f1SDimitry Andric 
580fe6060f1SDimitry Andric   CodeSignatureSection *section;
581fe6060f1SDimitry Andric };
582fe6060f1SDimitry Andric 
583bdd1243dSDimitry Andric class LCExportsTrie final : public LoadCommand {
584bdd1243dSDimitry Andric public:
LCExportsTrie(ExportSection * section)585bdd1243dSDimitry Andric   LCExportsTrie(ExportSection *section) : section(section) {}
586bdd1243dSDimitry Andric 
getSize() const587bdd1243dSDimitry Andric   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
588bdd1243dSDimitry Andric 
writeTo(uint8_t * buf) const589bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) const override {
590bdd1243dSDimitry Andric     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
591bdd1243dSDimitry Andric     c->cmd = LC_DYLD_EXPORTS_TRIE;
592bdd1243dSDimitry Andric     c->cmdsize = getSize();
593bdd1243dSDimitry Andric     c->dataoff = section->fileOff;
594bdd1243dSDimitry Andric     c->datasize = section->getSize();
595bdd1243dSDimitry Andric   }
596bdd1243dSDimitry Andric 
597bdd1243dSDimitry Andric   ExportSection *section;
598bdd1243dSDimitry Andric };
599bdd1243dSDimitry Andric 
600bdd1243dSDimitry Andric class LCChainedFixups final : public LoadCommand {
601bdd1243dSDimitry Andric public:
LCChainedFixups(ChainedFixupsSection * section)602bdd1243dSDimitry Andric   LCChainedFixups(ChainedFixupsSection *section) : section(section) {}
603bdd1243dSDimitry Andric 
getSize() const604bdd1243dSDimitry Andric   uint32_t getSize() const override { return sizeof(linkedit_data_command); }
605bdd1243dSDimitry Andric 
writeTo(uint8_t * buf) const606bdd1243dSDimitry Andric   void writeTo(uint8_t *buf) const override {
607bdd1243dSDimitry Andric     auto *c = reinterpret_cast<linkedit_data_command *>(buf);
608bdd1243dSDimitry Andric     c->cmd = LC_DYLD_CHAINED_FIXUPS;
609bdd1243dSDimitry Andric     c->cmdsize = getSize();
610bdd1243dSDimitry Andric     c->dataoff = section->fileOff;
611bdd1243dSDimitry Andric     c->datasize = section->getSize();
612bdd1243dSDimitry Andric   }
613bdd1243dSDimitry Andric 
614bdd1243dSDimitry Andric   ChainedFixupsSection *section;
615bdd1243dSDimitry Andric };
616bdd1243dSDimitry Andric 
6175ffd83dbSDimitry Andric } // namespace
6185ffd83dbSDimitry Andric 
treatSpecialUndefineds()619fe6060f1SDimitry Andric void Writer::treatSpecialUndefineds() {
620fe6060f1SDimitry Andric   if (config->entry)
621fe6060f1SDimitry Andric     if (auto *undefined = dyn_cast<Undefined>(config->entry))
622fe6060f1SDimitry Andric       treatUndefinedSymbol(*undefined, "the entry point");
623fe6060f1SDimitry Andric 
624fe6060f1SDimitry Andric   // FIXME: This prints symbols that are undefined both in input files and
625fe6060f1SDimitry Andric   // via -u flag twice.
626fe6060f1SDimitry Andric   for (const Symbol *sym : config->explicitUndefineds) {
627fe6060f1SDimitry Andric     if (const auto *undefined = dyn_cast<Undefined>(sym))
628fe6060f1SDimitry Andric       treatUndefinedSymbol(*undefined, "-u");
629fe6060f1SDimitry Andric   }
630fe6060f1SDimitry Andric   // Literal exported-symbol names must be defined, but glob
631fe6060f1SDimitry Andric   // patterns need not match.
632fe6060f1SDimitry Andric   for (const CachedHashStringRef &cachedName :
633fe6060f1SDimitry Andric        config->exportedSymbols.literals) {
634fe6060f1SDimitry Andric     if (const Symbol *sym = symtab->find(cachedName))
635fe6060f1SDimitry Andric       if (const auto *undefined = dyn_cast<Undefined>(sym))
636fe6060f1SDimitry Andric         treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
637fe6060f1SDimitry Andric   }
638fe6060f1SDimitry Andric }
639fe6060f1SDimitry Andric 
prepareSymbolRelocation(Symbol * sym,const InputSection * isec,const lld::macho::Reloc & r)640fe6060f1SDimitry Andric static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,
64104eeddc0SDimitry Andric                                     const lld::macho::Reloc &r) {
642*0fca6ea1SDimitry Andric   if (!sym->isLive()) {
643*0fca6ea1SDimitry Andric     if (Defined *defined = dyn_cast<Defined>(sym)) {
644*0fca6ea1SDimitry Andric       if (config->emitInitOffsets &&
645*0fca6ea1SDimitry Andric           defined->isec()->getName() == section_names::moduleInitFunc)
646*0fca6ea1SDimitry Andric         fatal(isec->getLocation(r.offset) + ": cannot reference " +
647*0fca6ea1SDimitry Andric               sym->getName() +
648*0fca6ea1SDimitry Andric               " defined in __mod_init_func when -init_offsets is used");
649*0fca6ea1SDimitry Andric     }
650*0fca6ea1SDimitry Andric     assert(false && "referenced symbol must be live");
651*0fca6ea1SDimitry Andric   }
652*0fca6ea1SDimitry Andric 
653fe6060f1SDimitry Andric   const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);
654fe6060f1SDimitry Andric 
655fe6060f1SDimitry Andric   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {
656bdd1243dSDimitry Andric     if (needsBinding(sym))
657bdd1243dSDimitry Andric       in.stubs->addEntry(sym);
658fe6060f1SDimitry Andric   } else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {
659fe6060f1SDimitry Andric     if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))
660fe6060f1SDimitry Andric       in.got->addEntry(sym);
661fe6060f1SDimitry Andric   } else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {
662fe6060f1SDimitry Andric     if (needsBinding(sym))
663fe6060f1SDimitry Andric       in.tlvPointers->addEntry(sym);
664fe6060f1SDimitry Andric   } else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {
665fe6060f1SDimitry Andric     // References from thread-local variable sections are treated as offsets
666fe6060f1SDimitry Andric     // relative to the start of the referent section, and therefore have no
667fe6060f1SDimitry Andric     // need of rebase opcodes.
668fe6060f1SDimitry Andric     if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))
669fe6060f1SDimitry Andric       addNonLazyBindingEntries(sym, isec, r.offset, r.addend);
670fe6060f1SDimitry Andric   }
671fe6060f1SDimitry Andric }
672fe6060f1SDimitry Andric 
scanRelocations()6735ffd83dbSDimitry Andric void Writer::scanRelocations() {
674fe6060f1SDimitry Andric   TimeTraceScope timeScope("Scan relocations");
675fe6060f1SDimitry Andric 
676fe6060f1SDimitry Andric   // This can't use a for-each loop: It calls treatUndefinedSymbol(), which can
677fe6060f1SDimitry Andric   // add to inputSections, which invalidates inputSections's iterators.
678fe6060f1SDimitry Andric   for (size_t i = 0; i < inputSections.size(); ++i) {
679fe6060f1SDimitry Andric     ConcatInputSection *isec = inputSections[i];
680fe6060f1SDimitry Andric 
681fe6060f1SDimitry Andric     if (isec->shouldOmitFromOutput())
682e8d8bef9SDimitry Andric       continue;
683e8d8bef9SDimitry Andric 
684fe6060f1SDimitry Andric     for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {
68504eeddc0SDimitry Andric       lld::macho::Reloc &r = *it;
68606c3fb27SDimitry Andric 
68706c3fb27SDimitry Andric       // Canonicalize the referent so that later accesses in Writer won't
68806c3fb27SDimitry Andric       // have to worry about it.
68906c3fb27SDimitry Andric       if (auto *referentIsec = r.referent.dyn_cast<InputSection *>())
69006c3fb27SDimitry Andric         r.referent = referentIsec->canonical();
69106c3fb27SDimitry Andric 
692fe6060f1SDimitry Andric       if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
693fe6060f1SDimitry Andric         // Skip over the following UNSIGNED relocation -- it's just there as the
694fe6060f1SDimitry Andric         // minuend, and doesn't have the usual UNSIGNED semantics. We don't want
695fe6060f1SDimitry Andric         // to emit rebase opcodes for it.
69606c3fb27SDimitry Andric         ++it;
69706c3fb27SDimitry Andric         // Canonicalize the referent so that later accesses in Writer won't
69806c3fb27SDimitry Andric         // have to worry about it.
69906c3fb27SDimitry Andric         if (auto *referentIsec = it->referent.dyn_cast<InputSection *>())
70006c3fb27SDimitry Andric           it->referent = referentIsec->canonical();
701fe6060f1SDimitry Andric         continue;
702fe6060f1SDimitry Andric       }
703fe6060f1SDimitry Andric       if (auto *sym = r.referent.dyn_cast<Symbol *>()) {
704fe6060f1SDimitry Andric         if (auto *undefined = dyn_cast<Undefined>(sym))
70581ad6265SDimitry Andric           treatUndefinedSymbol(*undefined, isec, r.offset);
706fe6060f1SDimitry Andric         // treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.
707fe6060f1SDimitry Andric         if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))
708fe6060f1SDimitry Andric           prepareSymbolRelocation(sym, isec, r);
709e8d8bef9SDimitry Andric       } else {
710bdd1243dSDimitry Andric         if (!r.pcrel) {
711bdd1243dSDimitry Andric           if (config->emitChainedFixups)
712bdd1243dSDimitry Andric             in.chainedFixups->addRebase(isec, r.offset);
713bdd1243dSDimitry Andric           else
714e8d8bef9SDimitry Andric             in.rebase->addEntry(isec, r.offset);
7155ffd83dbSDimitry Andric         }
7165ffd83dbSDimitry Andric       }
7175ffd83dbSDimitry Andric     }
718bdd1243dSDimitry Andric   }
719fe6060f1SDimitry Andric 
720f3fd488fSDimitry Andric   in.unwindInfo->prepare();
7215ffd83dbSDimitry Andric }
7225ffd83dbSDimitry Andric 
addNonWeakDefinition(const Defined * defined)723bdd1243dSDimitry Andric static void addNonWeakDefinition(const Defined *defined) {
724bdd1243dSDimitry Andric   if (config->emitChainedFixups)
725bdd1243dSDimitry Andric     in.chainedFixups->setHasNonWeakDefinition();
726bdd1243dSDimitry Andric   else
727bdd1243dSDimitry Andric     in.weakBinding->addNonWeakDefinition(defined);
728bdd1243dSDimitry Andric }
729bdd1243dSDimitry Andric 
scanSymbols()730e8d8bef9SDimitry Andric void Writer::scanSymbols() {
731fe6060f1SDimitry Andric   TimeTraceScope timeScope("Scan symbols");
732*0fca6ea1SDimitry Andric   ObjCSelRefsHelper::initialize();
733349cc55cSDimitry Andric   for (Symbol *sym : symtab->getSymbols()) {
734349cc55cSDimitry Andric     if (auto *defined = dyn_cast<Defined>(sym)) {
735349cc55cSDimitry Andric       if (!defined->isLive())
736349cc55cSDimitry Andric         continue;
737349cc55cSDimitry Andric       if (defined->overridesWeakDef)
738bdd1243dSDimitry Andric         addNonWeakDefinition(defined);
739*0fca6ea1SDimitry Andric       if (!defined->isAbsolute() && isCodeSection(defined->isec()))
740349cc55cSDimitry Andric         in.unwindInfo->addSymbol(defined);
741e8d8bef9SDimitry Andric     } else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {
742fe6060f1SDimitry Andric       // This branch intentionally doesn't check isLive().
743fe6060f1SDimitry Andric       if (dysym->isDynamicLookup())
744fe6060f1SDimitry Andric         continue;
745fe6060f1SDimitry Andric       dysym->getFile()->refState =
746fe6060f1SDimitry Andric           std::max(dysym->getFile()->refState, dysym->getRefState());
747bdd1243dSDimitry Andric     } else if (isa<Undefined>(sym)) {
748*0fca6ea1SDimitry Andric       if (ObjCStubsSection::isObjCStubSymbol(sym)) {
749*0fca6ea1SDimitry Andric         // When -dead_strip is enabled, we don't want to emit any dead stubs.
750*0fca6ea1SDimitry Andric         // Although this stub symbol is yet undefined, addSym() was called
751*0fca6ea1SDimitry Andric         // during MarkLive.
752*0fca6ea1SDimitry Andric         if (config->deadStrip) {
753*0fca6ea1SDimitry Andric           if (!sym->isLive())
754*0fca6ea1SDimitry Andric             continue;
755*0fca6ea1SDimitry Andric         }
756bdd1243dSDimitry Andric         in.objcStubs->addEntry(sym);
757e8d8bef9SDimitry Andric       }
758e8d8bef9SDimitry Andric     }
759*0fca6ea1SDimitry Andric   }
760349cc55cSDimitry Andric 
761349cc55cSDimitry Andric   for (const InputFile *file : inputFiles) {
762349cc55cSDimitry Andric     if (auto *objFile = dyn_cast<ObjFile>(file))
763349cc55cSDimitry Andric       for (Symbol *sym : objFile->symbols) {
764349cc55cSDimitry Andric         if (auto *defined = dyn_cast_or_null<Defined>(sym)) {
765349cc55cSDimitry Andric           if (!defined->isLive())
766349cc55cSDimitry Andric             continue;
767349cc55cSDimitry Andric           if (!defined->isExternal() && !defined->isAbsolute() &&
768*0fca6ea1SDimitry Andric               isCodeSection(defined->isec()))
769349cc55cSDimitry Andric             in.unwindInfo->addSymbol(defined);
770349cc55cSDimitry Andric         }
771349cc55cSDimitry Andric       }
772349cc55cSDimitry Andric   }
773e8d8bef9SDimitry Andric }
774e8d8bef9SDimitry Andric 
775fe6060f1SDimitry Andric // TODO: ld64 enforces the old load commands in a few other cases.
useLCBuildVersion(const PlatformInfo & platformInfo)776fe6060f1SDimitry Andric static bool useLCBuildVersion(const PlatformInfo &platformInfo) {
777bdd1243dSDimitry Andric   static const std::array<std::pair<PlatformType, VersionTuple>, 7> minVersion =
778bdd1243dSDimitry Andric       {{{PLATFORM_MACOS, VersionTuple(10, 14)},
77904eeddc0SDimitry Andric         {PLATFORM_IOS, VersionTuple(12, 0)},
78004eeddc0SDimitry Andric         {PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)},
78104eeddc0SDimitry Andric         {PLATFORM_TVOS, VersionTuple(12, 0)},
78204eeddc0SDimitry Andric         {PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)},
78304eeddc0SDimitry Andric         {PLATFORM_WATCHOS, VersionTuple(5, 0)},
784bdd1243dSDimitry Andric         {PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}}};
785fe6060f1SDimitry Andric   auto it = llvm::find_if(minVersion, [&](const auto &p) {
786fe6060f1SDimitry Andric     return p.first == platformInfo.target.Platform;
787fe6060f1SDimitry Andric   });
78806c3fb27SDimitry Andric   return it == minVersion.end()
78906c3fb27SDimitry Andric              ? true
79006c3fb27SDimitry Andric              : platformInfo.target.MinDeployment >= it->second;
791fe6060f1SDimitry Andric }
792fe6060f1SDimitry Andric 
createLoadCommands()793fe6060f1SDimitry Andric template <class LP> void Writer::createLoadCommands() {
794fe6060f1SDimitry Andric   uint8_t segIndex = 0;
795fe6060f1SDimitry Andric   for (OutputSegment *seg : outputSegments) {
796fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));
797fe6060f1SDimitry Andric     seg->index = segIndex++;
798fe6060f1SDimitry Andric   }
799fe6060f1SDimitry Andric 
800bdd1243dSDimitry Andric   if (config->emitChainedFixups) {
801bdd1243dSDimitry Andric     in.header->addLoadCommand(make<LCChainedFixups>(in.chainedFixups));
802bdd1243dSDimitry Andric     in.header->addLoadCommand(make<LCExportsTrie>(in.exports));
803bdd1243dSDimitry Andric   } else {
804e8d8bef9SDimitry Andric     in.header->addLoadCommand(make<LCDyldInfo>(
805e8d8bef9SDimitry Andric         in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));
806bdd1243dSDimitry Andric   }
807e8d8bef9SDimitry Andric   in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));
808e8d8bef9SDimitry Andric   in.header->addLoadCommand(
809e8d8bef9SDimitry Andric       make<LCDysymtab>(symtabSection, indirectSymtabSection));
810fe6060f1SDimitry Andric   if (!config->umbrella.empty())
811fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));
812fe6060f1SDimitry Andric   if (config->emitEncryptionInfo)
813fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());
814e8d8bef9SDimitry Andric   for (StringRef path : config->runtimePaths)
815e8d8bef9SDimitry Andric     in.header->addLoadCommand(make<LCRPath>(path));
8165ffd83dbSDimitry Andric 
8175ffd83dbSDimitry Andric   switch (config->outputType) {
8185ffd83dbSDimitry Andric   case MH_EXECUTE:
819e8d8bef9SDimitry Andric     in.header->addLoadCommand(make<LCLoadDylinker>());
8205ffd83dbSDimitry Andric     break;
8215ffd83dbSDimitry Andric   case MH_DYLIB:
822e8d8bef9SDimitry Andric     in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,
823e8d8bef9SDimitry Andric                                             config->dylibCompatibilityVersion,
824e8d8bef9SDimitry Andric                                             config->dylibCurrentVersion));
825e8d8bef9SDimitry Andric     break;
826e8d8bef9SDimitry Andric   case MH_BUNDLE:
8275ffd83dbSDimitry Andric     break;
8285ffd83dbSDimitry Andric   default:
8295ffd83dbSDimitry Andric     llvm_unreachable("unhandled output file type");
8305ffd83dbSDimitry Andric   }
8315ffd83dbSDimitry Andric 
83206c3fb27SDimitry Andric   if (config->generateUuid) {
833e8d8bef9SDimitry Andric     uuidCommand = make<LCUuid>();
834e8d8bef9SDimitry Andric     in.header->addLoadCommand(uuidCommand);
83506c3fb27SDimitry Andric   }
836e8d8bef9SDimitry Andric 
837fe6060f1SDimitry Andric   if (useLCBuildVersion(config->platformInfo))
838fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));
839fe6060f1SDimitry Andric   else
840fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));
8415ffd83dbSDimitry Andric 
84281ad6265SDimitry Andric   if (config->secondaryPlatformInfo) {
84381ad6265SDimitry Andric     in.header->addLoadCommand(
84481ad6265SDimitry Andric         make<LCBuildVersion>(*config->secondaryPlatformInfo));
84581ad6265SDimitry Andric   }
84681ad6265SDimitry Andric 
847fe6060f1SDimitry Andric   // This is down here to match ld64's load command order.
848fe6060f1SDimitry Andric   if (config->outputType == MH_EXECUTE)
849fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCMain>());
850fe6060f1SDimitry Andric 
85161cfbce3SDimitry Andric   // See ld64's OutputFile::buildDylibOrdinalMapping for the corresponding
85261cfbce3SDimitry Andric   // library ordinal computation code in ld64.
853fe6060f1SDimitry Andric   int64_t dylibOrdinal = 1;
854fe6060f1SDimitry Andric   DenseMap<StringRef, int64_t> ordinalForInstallName;
85561cfbce3SDimitry Andric 
85661cfbce3SDimitry Andric   std::vector<DylibFile *> dylibFiles;
8575ffd83dbSDimitry Andric   for (InputFile *file : inputFiles) {
85861cfbce3SDimitry Andric     if (auto *dylibFile = dyn_cast<DylibFile>(file))
85961cfbce3SDimitry Andric       dylibFiles.push_back(dylibFile);
86061cfbce3SDimitry Andric   }
86161cfbce3SDimitry Andric   for (size_t i = 0; i < dylibFiles.size(); ++i)
86261cfbce3SDimitry Andric     dylibFiles.insert(dylibFiles.end(), dylibFiles[i]->extraDylibs.begin(),
86361cfbce3SDimitry Andric                       dylibFiles[i]->extraDylibs.end());
86461cfbce3SDimitry Andric 
86561cfbce3SDimitry Andric   for (DylibFile *dylibFile : dylibFiles) {
866fe6060f1SDimitry Andric     if (dylibFile->isBundleLoader) {
867fe6060f1SDimitry Andric       dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;
868fe6060f1SDimitry Andric       // Shortcut since bundle-loader does not re-export the symbols.
869fe6060f1SDimitry Andric 
870fe6060f1SDimitry Andric       dylibFile->reexport = false;
871fe6060f1SDimitry Andric       continue;
872fe6060f1SDimitry Andric     }
873fe6060f1SDimitry Andric 
874fe6060f1SDimitry Andric     // Don't emit load commands for a dylib that is not referenced if:
875fe6060f1SDimitry Andric     // - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --
876fe6060f1SDimitry Andric     //   if it's on the linker command line, it's explicit)
877fe6060f1SDimitry Andric     // - or it's marked MH_DEAD_STRIPPABLE_DYLIB
878fe6060f1SDimitry Andric     // - or the flag -dead_strip_dylibs is used
879fe6060f1SDimitry Andric     // FIXME: `isReferenced()` is currently computed before dead code
880fe6060f1SDimitry Andric     // stripping, so references from dead code keep a dylib alive. This
881fe6060f1SDimitry Andric     // matches ld64, but it's something we should do better.
882fe6060f1SDimitry Andric     if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&
88361cfbce3SDimitry Andric         (!dylibFile->isExplicitlyLinked() || dylibFile->deadStrippable ||
884fe6060f1SDimitry Andric          config->deadStripDylibs))
885fe6060f1SDimitry Andric       continue;
886fe6060f1SDimitry Andric 
887fe6060f1SDimitry Andric     // Several DylibFiles can have the same installName. Only emit a single
888fe6060f1SDimitry Andric     // load command for that installName and give all these DylibFiles the
889fe6060f1SDimitry Andric     // same ordinal.
890fe6060f1SDimitry Andric     // This can happen in several cases:
891fe6060f1SDimitry Andric     // - a new framework could change its installName to an older
892fe6060f1SDimitry Andric     //   framework name via an $ld$ symbol depending on platform_version
893fe6060f1SDimitry Andric     // - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;
894fe6060f1SDimitry Andric     //   Foo.framework/Foo.tbd is usually a symlink to
895fe6060f1SDimitry Andric     //   Foo.framework/Versions/Current/Foo.tbd, where
896fe6060f1SDimitry Andric     //   Foo.framework/Versions/Current is usually a symlink to
897fe6060f1SDimitry Andric     //   Foo.framework/Versions/A)
898fe6060f1SDimitry Andric     // - a framework can be linked both explicitly on the linker
899fe6060f1SDimitry Andric     //   command line and implicitly as a reexport from a different
900fe6060f1SDimitry Andric     //   framework. The re-export will usually point to the tbd file
901fe6060f1SDimitry Andric     //   in Foo.framework/Versions/A/Foo.tbd, while the explicit link will
902fe6060f1SDimitry Andric     //   usually find Foo.framework/Foo.tbd. These are usually symlinks,
903fe6060f1SDimitry Andric     //   but in a --reproduce archive they will be identical but distinct
904fe6060f1SDimitry Andric     //   files.
905fe6060f1SDimitry Andric     // In the first case, *semantically distinct* DylibFiles will have the
906fe6060f1SDimitry Andric     // same installName.
907fe6060f1SDimitry Andric     int64_t &ordinal = ordinalForInstallName[dylibFile->installName];
908fe6060f1SDimitry Andric     if (ordinal) {
909fe6060f1SDimitry Andric       dylibFile->ordinal = ordinal;
910fe6060f1SDimitry Andric       continue;
911fe6060f1SDimitry Andric     }
912fe6060f1SDimitry Andric 
913fe6060f1SDimitry Andric     ordinal = dylibFile->ordinal = dylibOrdinal++;
914e8d8bef9SDimitry Andric     LoadCommandType lcType =
915e8d8bef9SDimitry Andric         dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak
916e8d8bef9SDimitry Andric             ? LC_LOAD_WEAK_DYLIB
917e8d8bef9SDimitry Andric             : LC_LOAD_DYLIB;
918fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,
919e8d8bef9SDimitry Andric                                             dylibFile->compatibilityVersion,
920e8d8bef9SDimitry Andric                                             dylibFile->currentVersion));
9215ffd83dbSDimitry Andric 
9225ffd83dbSDimitry Andric     if (dylibFile->reexport)
923e8d8bef9SDimitry Andric       in.header->addLoadCommand(
924fe6060f1SDimitry Andric           make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));
9255ffd83dbSDimitry Andric   }
926e8d8bef9SDimitry Andric 
927bdd1243dSDimitry Andric   for (const auto &dyldEnv : config->dyldEnvs)
928bdd1243dSDimitry Andric     in.header->addLoadCommand(make<LCDyldEnv>(dyldEnv));
929bdd1243dSDimitry Andric 
930fe6060f1SDimitry Andric   if (functionStartsSection)
931fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));
932fe6060f1SDimitry Andric   if (dataInCodeSection)
933fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));
934fe6060f1SDimitry Andric   if (codeSignatureSection)
935fe6060f1SDimitry Andric     in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));
936fe6060f1SDimitry Andric 
937e8d8bef9SDimitry Andric   const uint32_t MACOS_MAXPATHLEN = 1024;
938e8d8bef9SDimitry Andric   config->headerPad = std::max(
939e8d8bef9SDimitry Andric       config->headerPad, (config->headerPadMaxInstallNames
940e8d8bef9SDimitry Andric                               ? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN
941e8d8bef9SDimitry Andric                               : 0));
9425ffd83dbSDimitry Andric }
9435ffd83dbSDimitry Andric 
9445ffd83dbSDimitry Andric // Sorting only can happen once all outputs have been collected. Here we sort
9455ffd83dbSDimitry Andric // segments, output sections within each segment, and input sections within each
9465ffd83dbSDimitry Andric // output segment.
sortSegmentsAndSections()9475ffd83dbSDimitry Andric static void sortSegmentsAndSections() {
948fe6060f1SDimitry Andric   TimeTraceScope timeScope("Sort segments and sections");
949fe6060f1SDimitry Andric   sortOutputSegments();
9505ffd83dbSDimitry Andric 
9515ffd83dbSDimitry Andric   DenseMap<const InputSection *, size_t> isecPriorities =
95281ad6265SDimitry Andric       priorityBuilder.buildInputSectionPriorities();
9535ffd83dbSDimitry Andric 
9545ffd83dbSDimitry Andric   uint32_t sectionIndex = 0;
9555ffd83dbSDimitry Andric   for (OutputSegment *seg : outputSegments) {
956fe6060f1SDimitry Andric     seg->sortOutputSections();
95704eeddc0SDimitry Andric     // References from thread-local variable sections are treated as offsets
95804eeddc0SDimitry Andric     // relative to the start of the thread-local data memory area, which
95904eeddc0SDimitry Andric     // is initialized via copying all the TLV data sections (which are all
96004eeddc0SDimitry Andric     // contiguous). If later data sections require a greater alignment than
96104eeddc0SDimitry Andric     // earlier ones, the offsets of data within those sections won't be
96204eeddc0SDimitry Andric     // guaranteed to aligned unless we normalize alignments. We therefore use
96304eeddc0SDimitry Andric     // the largest alignment for all TLV data sections.
96404eeddc0SDimitry Andric     uint32_t tlvAlign = 0;
96504eeddc0SDimitry Andric     for (const OutputSection *osec : seg->getSections())
96604eeddc0SDimitry Andric       if (isThreadLocalData(osec->flags) && osec->align > tlvAlign)
96704eeddc0SDimitry Andric         tlvAlign = osec->align;
96804eeddc0SDimitry Andric 
969fe6060f1SDimitry Andric     for (OutputSection *osec : seg->getSections()) {
9705ffd83dbSDimitry Andric       // Now that the output sections are sorted, assign the final
9715ffd83dbSDimitry Andric       // output section indices.
9725ffd83dbSDimitry Andric       if (!osec->isHidden())
9735ffd83dbSDimitry Andric         osec->index = ++sectionIndex;
97404eeddc0SDimitry Andric       if (isThreadLocalData(osec->flags)) {
97504eeddc0SDimitry Andric         if (!firstTLVDataSection)
976e8d8bef9SDimitry Andric           firstTLVDataSection = osec;
97704eeddc0SDimitry Andric         osec->align = tlvAlign;
97804eeddc0SDimitry Andric       }
979e8d8bef9SDimitry Andric 
9805ffd83dbSDimitry Andric       if (!isecPriorities.empty()) {
981fe6060f1SDimitry Andric         if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {
982bdd1243dSDimitry Andric           llvm::stable_sort(
983bdd1243dSDimitry Andric               merged->inputs, [&](InputSection *a, InputSection *b) {
984bdd1243dSDimitry Andric                 return isecPriorities.lookup(a) > isecPriorities.lookup(b);
9855ffd83dbSDimitry Andric               });
9865ffd83dbSDimitry Andric         }
9875ffd83dbSDimitry Andric       }
9885ffd83dbSDimitry Andric     }
9895ffd83dbSDimitry Andric   }
9905ffd83dbSDimitry Andric }
9915ffd83dbSDimitry Andric 
createOutputSections()992fe6060f1SDimitry Andric template <class LP> void Writer::createOutputSections() {
993fe6060f1SDimitry Andric   TimeTraceScope timeScope("Create output sections");
9945ffd83dbSDimitry Andric   // First, create hidden sections
9955ffd83dbSDimitry Andric   stringTableSection = make<StringTableSection>();
996fe6060f1SDimitry Andric   symtabSection = makeSymtabSection<LP>(*stringTableSection);
997e8d8bef9SDimitry Andric   indirectSymtabSection = make<IndirectSymtabSection>();
998fe6060f1SDimitry Andric   if (config->adhocCodesign)
999fe6060f1SDimitry Andric     codeSignatureSection = make<CodeSignatureSection>();
1000fe6060f1SDimitry Andric   if (config->emitDataInCodeInfo)
1001fe6060f1SDimitry Andric     dataInCodeSection = make<DataInCodeSection>();
1002fe6060f1SDimitry Andric   if (config->emitFunctionStarts)
1003fe6060f1SDimitry Andric     functionStartsSection = make<FunctionStartsSection>();
10045ffd83dbSDimitry Andric 
10055ffd83dbSDimitry Andric   switch (config->outputType) {
10065ffd83dbSDimitry Andric   case MH_EXECUTE:
10075ffd83dbSDimitry Andric     make<PageZeroSection>();
10085ffd83dbSDimitry Andric     break;
10095ffd83dbSDimitry Andric   case MH_DYLIB:
1010e8d8bef9SDimitry Andric   case MH_BUNDLE:
10115ffd83dbSDimitry Andric     break;
10125ffd83dbSDimitry Andric   default:
10135ffd83dbSDimitry Andric     llvm_unreachable("unhandled output file type");
10145ffd83dbSDimitry Andric   }
10155ffd83dbSDimitry Andric 
1016fe6060f1SDimitry Andric   // Then add input sections to output sections.
1017fe6060f1SDimitry Andric   for (ConcatInputSection *isec : inputSections) {
1018fe6060f1SDimitry Andric     if (isec->shouldOmitFromOutput())
1019fe6060f1SDimitry Andric       continue;
1020fe6060f1SDimitry Andric     ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);
1021fe6060f1SDimitry Andric     osec->addInput(isec);
1022fe6060f1SDimitry Andric     osec->inputOrder =
1023fe6060f1SDimitry Andric         std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));
10245ffd83dbSDimitry Andric   }
10255ffd83dbSDimitry Andric 
1026fe6060f1SDimitry Andric   // Once all the inputs are added, we can finalize the output section
1027fe6060f1SDimitry Andric   // properties and create the corresponding output segments.
1028fe6060f1SDimitry Andric   for (const auto &it : concatOutputSections) {
10295ffd83dbSDimitry Andric     StringRef segname = it.first.first;
1030fe6060f1SDimitry Andric     ConcatOutputSection *osec = it.second;
1031fe6060f1SDimitry Andric     assert(segname != segment_names::ld);
103281ad6265SDimitry Andric     if (osec->isNeeded()) {
103381ad6265SDimitry Andric       // See comment in ObjFile::splitEhFrames()
103481ad6265SDimitry Andric       if (osec->name == section_names::ehFrame &&
103581ad6265SDimitry Andric           segname == segment_names::text)
103681ad6265SDimitry Andric         osec->align = target->wordSize;
103781ad6265SDimitry Andric 
1038bdd1243dSDimitry Andric       // MC keeps the default 1-byte alignment for __thread_vars, even though it
1039bdd1243dSDimitry Andric       // contains pointers that are fixed up by dyld, which requires proper
1040bdd1243dSDimitry Andric       // alignment.
1041bdd1243dSDimitry Andric       if (isThreadLocalVariables(osec->flags))
1042bdd1243dSDimitry Andric         osec->align = std::max<uint32_t>(osec->align, target->wordSize);
1043bdd1243dSDimitry Andric 
10445ffd83dbSDimitry Andric       getOrCreateOutputSegment(segname)->addOutputSection(osec);
10455ffd83dbSDimitry Andric     }
104681ad6265SDimitry Andric   }
10475ffd83dbSDimitry Andric 
10485ffd83dbSDimitry Andric   for (SyntheticSection *ssec : syntheticSections) {
1049fe6060f1SDimitry Andric     auto it = concatOutputSections.find({ssec->segname, ssec->name});
1050349cc55cSDimitry Andric     // We add all LinkEdit sections here because we don't know if they are
1051349cc55cSDimitry Andric     // needed until their finalizeContents() methods get called later. While
1052349cc55cSDimitry Andric     // this means that we add some redundant sections to __LINKEDIT, there is
1053349cc55cSDimitry Andric     // is no redundancy in the output, as we do not emit section headers for
1054349cc55cSDimitry Andric     // any LinkEdit sections.
1055349cc55cSDimitry Andric     if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) {
1056fe6060f1SDimitry Andric       if (it == concatOutputSections.end()) {
10575ffd83dbSDimitry Andric         getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);
10585ffd83dbSDimitry Andric       } else {
1059fe6060f1SDimitry Andric         fatal("section from " +
1060fe6060f1SDimitry Andric               toString(it->second->firstSection()->getFile()) +
10615ffd83dbSDimitry Andric               " conflicts with synthetic section " + ssec->segname + "," +
10625ffd83dbSDimitry Andric               ssec->name);
10635ffd83dbSDimitry Andric       }
10645ffd83dbSDimitry Andric     }
10655ffd83dbSDimitry Andric   }
10665ffd83dbSDimitry Andric 
1067fe6060f1SDimitry Andric   // dyld requires __LINKEDIT segment to always exist (even if empty).
1068fe6060f1SDimitry Andric   linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);
1069fe6060f1SDimitry Andric }
1070fe6060f1SDimitry Andric 
finalizeAddresses()1071fe6060f1SDimitry Andric void Writer::finalizeAddresses() {
1072fe6060f1SDimitry Andric   TimeTraceScope timeScope("Finalize addresses");
1073fe6060f1SDimitry Andric   uint64_t pageSize = target->getPageSize();
107481ad6265SDimitry Andric 
107581ad6265SDimitry Andric   // We could parallelize this loop, but local benchmarking indicates it is
107681ad6265SDimitry Andric   // faster to do it all in the main thread.
107781ad6265SDimitry Andric   for (OutputSegment *seg : outputSegments) {
107881ad6265SDimitry Andric     if (seg == linkEditSegment)
107981ad6265SDimitry Andric       continue;
108081ad6265SDimitry Andric     for (OutputSection *osec : seg->getSections()) {
108181ad6265SDimitry Andric       if (!osec->isNeeded())
108281ad6265SDimitry Andric         continue;
108381ad6265SDimitry Andric       // Other kinds of OutputSections have already been finalized.
108406c3fb27SDimitry Andric       if (auto *concatOsec = dyn_cast<ConcatOutputSection>(osec))
108581ad6265SDimitry Andric         concatOsec->finalizeContents();
108681ad6265SDimitry Andric     }
108781ad6265SDimitry Andric   }
108881ad6265SDimitry Andric 
1089fe6060f1SDimitry Andric   // Ensure that segments (and the sections they contain) are allocated
1090fe6060f1SDimitry Andric   // addresses in ascending order, which dyld requires.
1091fe6060f1SDimitry Andric   //
1092fe6060f1SDimitry Andric   // Note that at this point, __LINKEDIT sections are empty, but we need to
1093fe6060f1SDimitry Andric   // determine addresses of other segments/sections before generating its
1094fe6060f1SDimitry Andric   // contents.
1095fe6060f1SDimitry Andric   for (OutputSegment *seg : outputSegments) {
1096fe6060f1SDimitry Andric     if (seg == linkEditSegment)
1097fe6060f1SDimitry Andric       continue;
1098fe6060f1SDimitry Andric     seg->addr = addr;
1099fe6060f1SDimitry Andric     assignAddresses(seg);
1100fe6060f1SDimitry Andric     // codesign / libstuff checks for segment ordering by verifying that
110106c3fb27SDimitry Andric     // `fileOff + fileSize == next segment fileOff`. So we call
110206c3fb27SDimitry Andric     // alignToPowerOf2() before (instead of after) computing fileSize to ensure
110306c3fb27SDimitry Andric     // that the segments are contiguous. We handle addr / vmSize similarly for
110406c3fb27SDimitry Andric     // the same reason.
1105bdd1243dSDimitry Andric     fileOff = alignToPowerOf2(fileOff, pageSize);
1106bdd1243dSDimitry Andric     addr = alignToPowerOf2(addr, pageSize);
1107fe6060f1SDimitry Andric     seg->vmSize = addr - seg->addr;
1108fe6060f1SDimitry Andric     seg->fileSize = fileOff - seg->fileOff;
1109fe6060f1SDimitry Andric     seg->assignAddressesToStartEndSymbols();
1110fe6060f1SDimitry Andric   }
1111fe6060f1SDimitry Andric }
1112fe6060f1SDimitry Andric 
finalizeLinkEditSegment()1113fe6060f1SDimitry Andric void Writer::finalizeLinkEditSegment() {
1114fe6060f1SDimitry Andric   TimeTraceScope timeScope("Finalize __LINKEDIT segment");
1115fe6060f1SDimitry Andric   // Fill __LINKEDIT contents.
1116bdd1243dSDimitry Andric   std::array<LinkEditSection *, 10> linkEditSections{
1117bdd1243dSDimitry Andric       in.rebase,         in.binding,
1118bdd1243dSDimitry Andric       in.weakBinding,    in.lazyBinding,
1119bdd1243dSDimitry Andric       in.exports,        in.chainedFixups,
1120bdd1243dSDimitry Andric       symtabSection,     indirectSymtabSection,
1121bdd1243dSDimitry Andric       dataInCodeSection, functionStartsSection,
1122fe6060f1SDimitry Andric   };
1123*0fca6ea1SDimitry Andric 
1124*0fca6ea1SDimitry Andric   parallelForEach(linkEditSections.begin(), linkEditSections.end(),
1125*0fca6ea1SDimitry Andric                   [](LinkEditSection *osec) {
1126fe6060f1SDimitry Andric                     if (osec)
1127*0fca6ea1SDimitry Andric                       osec->finalizeContents();
1128*0fca6ea1SDimitry Andric                   });
1129fe6060f1SDimitry Andric 
1130fe6060f1SDimitry Andric   // Now that __LINKEDIT is filled out, do a proper calculation of its
1131fe6060f1SDimitry Andric   // addresses and offsets.
1132fe6060f1SDimitry Andric   linkEditSegment->addr = addr;
1133fe6060f1SDimitry Andric   assignAddresses(linkEditSegment);
1134fe6060f1SDimitry Andric   // No need to page-align fileOff / addr here since this is the last segment.
1135fe6060f1SDimitry Andric   linkEditSegment->vmSize = addr - linkEditSegment->addr;
1136fe6060f1SDimitry Andric   linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;
1137fe6060f1SDimitry Andric }
1138fe6060f1SDimitry Andric 
assignAddresses(OutputSegment * seg)11395ffd83dbSDimitry Andric void Writer::assignAddresses(OutputSegment *seg) {
11405ffd83dbSDimitry Andric   seg->fileOff = fileOff;
11415ffd83dbSDimitry Andric 
1142fe6060f1SDimitry Andric   for (OutputSection *osec : seg->getSections()) {
1143e8d8bef9SDimitry Andric     if (!osec->isNeeded())
1144e8d8bef9SDimitry Andric       continue;
114506c3fb27SDimitry Andric     addr = alignToPowerOf2(addr, osec->align);
114606c3fb27SDimitry Andric     fileOff = alignToPowerOf2(fileOff, osec->align);
11475ffd83dbSDimitry Andric     osec->addr = addr;
11485ffd83dbSDimitry Andric     osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;
11495ffd83dbSDimitry Andric     osec->finalize();
1150fe6060f1SDimitry Andric     osec->assignAddressesToStartEndSymbols();
11515ffd83dbSDimitry Andric 
11525ffd83dbSDimitry Andric     addr += osec->getSize();
11535ffd83dbSDimitry Andric     fileOff += osec->getFileSize();
11545ffd83dbSDimitry Andric   }
11555ffd83dbSDimitry Andric }
11565ffd83dbSDimitry Andric 
openFile()11575ffd83dbSDimitry Andric void Writer::openFile() {
11585ffd83dbSDimitry Andric   Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
11595ffd83dbSDimitry Andric       FileOutputBuffer::create(config->outputFile, fileOff,
11605ffd83dbSDimitry Andric                                FileOutputBuffer::F_executable);
11615ffd83dbSDimitry Andric 
11625ffd83dbSDimitry Andric   if (!bufferOrErr)
116381ad6265SDimitry Andric     fatal("failed to open " + config->outputFile + ": " +
11645ffd83dbSDimitry Andric           llvm::toString(bufferOrErr.takeError()));
11655ffd83dbSDimitry Andric   buffer = std::move(*bufferOrErr);
116681ad6265SDimitry Andric   in.bufferStart = buffer->getBufferStart();
11675ffd83dbSDimitry Andric }
11685ffd83dbSDimitry Andric 
writeSections()11695ffd83dbSDimitry Andric void Writer::writeSections() {
1170*0fca6ea1SDimitry Andric   TimeTraceScope timeScope("Write output sections");
1171*0fca6ea1SDimitry Andric 
11725ffd83dbSDimitry Andric   uint8_t *buf = buffer->getBufferStart();
117381ad6265SDimitry Andric   std::vector<const OutputSection *> osecs;
1174fe6060f1SDimitry Andric   for (const OutputSegment *seg : outputSegments)
117581ad6265SDimitry Andric     append_range(osecs, seg->getSections());
117681ad6265SDimitry Andric 
117781ad6265SDimitry Andric   parallelForEach(osecs.begin(), osecs.end(), [&](const OutputSection *osec) {
11785ffd83dbSDimitry Andric     osec->writeTo(buf + osec->fileOff);
117981ad6265SDimitry Andric   });
11805ffd83dbSDimitry Andric }
11815ffd83dbSDimitry Andric 
applyOptimizationHints()1182bdd1243dSDimitry Andric void Writer::applyOptimizationHints() {
1183bdd1243dSDimitry Andric   if (config->arch() != AK_arm64 || config->ignoreOptimizationHints)
1184bdd1243dSDimitry Andric     return;
1185bdd1243dSDimitry Andric 
1186bdd1243dSDimitry Andric   uint8_t *buf = buffer->getBufferStart();
1187bdd1243dSDimitry Andric   TimeTraceScope timeScope("Apply linker optimization hints");
1188bdd1243dSDimitry Andric   parallelForEach(inputFiles, [buf](const InputFile *file) {
1189bdd1243dSDimitry Andric     if (const auto *objFile = dyn_cast<ObjFile>(file))
1190bdd1243dSDimitry Andric       target->applyOptimizationHints(buf, *objFile);
1191bdd1243dSDimitry Andric   });
1192bdd1243dSDimitry Andric }
1193bdd1243dSDimitry Andric 
1194fe6060f1SDimitry Andric // In order to utilize multiple cores, we first split the buffer into chunks,
1195fe6060f1SDimitry Andric // compute a hash for each chunk, and then compute a hash value of the hash
1196fe6060f1SDimitry Andric // values.
writeUuid()1197e8d8bef9SDimitry Andric void Writer::writeUuid() {
1198fe6060f1SDimitry Andric   TimeTraceScope timeScope("Computing UUID");
11990eae32dcSDimitry Andric 
1200fe6060f1SDimitry Andric   ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};
120106c3fb27SDimitry Andric   std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);
1202*0fca6ea1SDimitry Andric 
120381ad6265SDimitry Andric   // Leave one slot for filename
120481ad6265SDimitry Andric   std::vector<uint64_t> hashes(chunks.size() + 1);
1205*0fca6ea1SDimitry Andric   parallelFor(0, chunks.size(),
1206*0fca6ea1SDimitry Andric               [&](size_t i) { hashes[i] = xxh3_64bits(chunks[i]); });
120781ad6265SDimitry Andric   // Append the output filename so that identical binaries with different names
120881ad6265SDimitry Andric   // don't get the same UUID.
120906c3fb27SDimitry Andric   hashes[chunks.size()] = xxh3_64bits(sys::path::filename(config->finalOutput));
1210*0fca6ea1SDimitry Andric 
121106c3fb27SDimitry Andric   uint64_t digest = xxh3_64bits({reinterpret_cast<uint8_t *>(hashes.data()),
1212fe6060f1SDimitry Andric                                  hashes.size() * sizeof(uint64_t)});
1213e8d8bef9SDimitry Andric   uuidCommand->writeUuid(digest);
1214e8d8bef9SDimitry Andric }
1215e8d8bef9SDimitry Andric 
1216bdd1243dSDimitry Andric // This is step 5 of the algorithm described in the class comment of
1217bdd1243dSDimitry Andric // ChainedFixupsSection.
buildFixupChains()1218bdd1243dSDimitry Andric void Writer::buildFixupChains() {
1219bdd1243dSDimitry Andric   if (!config->emitChainedFixups)
1220bdd1243dSDimitry Andric     return;
1221bdd1243dSDimitry Andric 
1222bdd1243dSDimitry Andric   const std::vector<Location> &loc = in.chainedFixups->getLocations();
1223bdd1243dSDimitry Andric   if (loc.empty())
1224bdd1243dSDimitry Andric     return;
1225bdd1243dSDimitry Andric 
1226bdd1243dSDimitry Andric   TimeTraceScope timeScope("Build fixup chains");
1227bdd1243dSDimitry Andric 
1228bdd1243dSDimitry Andric   const uint64_t pageSize = target->getPageSize();
1229bdd1243dSDimitry Andric   constexpr uint32_t stride = 4; // for DYLD_CHAINED_PTR_64
1230bdd1243dSDimitry Andric 
1231bdd1243dSDimitry Andric   for (size_t i = 0, count = loc.size(); i < count;) {
1232bdd1243dSDimitry Andric     const OutputSegment *oseg = loc[i].isec->parent->parent;
1233bdd1243dSDimitry Andric     uint8_t *buf = buffer->getBufferStart() + oseg->fileOff;
1234bdd1243dSDimitry Andric     uint64_t pageIdx = loc[i].offset / pageSize;
1235bdd1243dSDimitry Andric     ++i;
1236bdd1243dSDimitry Andric 
1237bdd1243dSDimitry Andric     while (i < count && loc[i].isec->parent->parent == oseg &&
1238bdd1243dSDimitry Andric            (loc[i].offset / pageSize) == pageIdx) {
1239bdd1243dSDimitry Andric       uint64_t offset = loc[i].offset - loc[i - 1].offset;
1240bdd1243dSDimitry Andric 
1241bdd1243dSDimitry Andric       auto fail = [&](Twine message) {
1242bdd1243dSDimitry Andric         error(loc[i].isec->getSegName() + "," + loc[i].isec->getName() +
1243bdd1243dSDimitry Andric               ", offset " +
1244bdd1243dSDimitry Andric               Twine(loc[i].offset - loc[i].isec->parent->getSegmentOffset()) +
1245bdd1243dSDimitry Andric               ": " + message);
1246bdd1243dSDimitry Andric       };
1247bdd1243dSDimitry Andric 
1248bdd1243dSDimitry Andric       if (offset < target->wordSize)
1249bdd1243dSDimitry Andric         return fail("fixups overlap");
1250bdd1243dSDimitry Andric       if (offset % stride != 0)
1251bdd1243dSDimitry Andric         return fail(
1252bdd1243dSDimitry Andric             "fixups are unaligned (offset " + Twine(offset) +
1253bdd1243dSDimitry Andric             " is not a multiple of the stride). Re-link with -no_fixup_chains");
1254bdd1243dSDimitry Andric 
1255bdd1243dSDimitry Andric       // The "next" field is in the same location for bind and rebase entries.
1256bdd1243dSDimitry Andric       reinterpret_cast<dyld_chained_ptr_64_bind *>(buf + loc[i - 1].offset)
1257bdd1243dSDimitry Andric           ->next = offset / stride;
1258bdd1243dSDimitry Andric       ++i;
1259bdd1243dSDimitry Andric     }
1260bdd1243dSDimitry Andric   }
1261bdd1243dSDimitry Andric }
1262bdd1243dSDimitry Andric 
writeCodeSignature()1263fe6060f1SDimitry Andric void Writer::writeCodeSignature() {
126481ad6265SDimitry Andric   if (codeSignatureSection) {
126581ad6265SDimitry Andric     TimeTraceScope timeScope("Write code signature");
1266fe6060f1SDimitry Andric     codeSignatureSection->writeHashes(buffer->getBufferStart());
1267fe6060f1SDimitry Andric   }
126881ad6265SDimitry Andric }
12695ffd83dbSDimitry Andric 
writeOutputFile()1270fe6060f1SDimitry Andric void Writer::writeOutputFile() {
1271fe6060f1SDimitry Andric   TimeTraceScope timeScope("Write output file");
12725ffd83dbSDimitry Andric   openFile();
127381ad6265SDimitry Andric   reportPendingUndefinedSymbols();
12745ffd83dbSDimitry Andric   if (errorCount())
12755ffd83dbSDimitry Andric     return;
12765ffd83dbSDimitry Andric   writeSections();
1277bdd1243dSDimitry Andric   applyOptimizationHints();
1278bdd1243dSDimitry Andric   buildFixupChains();
127906c3fb27SDimitry Andric   if (config->generateUuid)
1280e8d8bef9SDimitry Andric     writeUuid();
1281fe6060f1SDimitry Andric   writeCodeSignature();
12825ffd83dbSDimitry Andric 
12835ffd83dbSDimitry Andric   if (auto e = buffer->commit())
1284bdd1243dSDimitry Andric     fatal("failed to write output '" + buffer->getPath() +
1285bdd1243dSDimitry Andric           "': " + toString(std::move(e)));
12865ffd83dbSDimitry Andric }
12875ffd83dbSDimitry Andric 
run()1288fe6060f1SDimitry Andric template <class LP> void Writer::run() {
1289fe6060f1SDimitry Andric   treatSpecialUndefineds();
1290bdd1243dSDimitry Andric   if (config->entry && needsBinding(config->entry))
1291bdd1243dSDimitry Andric     in.stubs->addEntry(config->entry);
12921fd87a68SDimitry Andric 
1293349cc55cSDimitry Andric   // Canonicalization of all pointers to InputSections should be handled by
12941fd87a68SDimitry Andric   // these two scan* methods. I.e. from this point onward, for all live
12951fd87a68SDimitry Andric   // InputSections, we should have `isec->canonical() == isec`.
1296349cc55cSDimitry Andric   scanSymbols();
1297bdd1243dSDimitry Andric   if (in.objcStubs->isNeeded())
1298bdd1243dSDimitry Andric     in.objcStubs->setUp();
1299*0fca6ea1SDimitry Andric   if (in.objcMethList->isNeeded())
1300*0fca6ea1SDimitry Andric     in.objcMethList->setUp();
1301fe6060f1SDimitry Andric   scanRelocations();
1302bdd1243dSDimitry Andric   if (in.initOffsets->isNeeded())
1303bdd1243dSDimitry Andric     in.initOffsets->setUp();
1304349cc55cSDimitry Andric 
1305bdd1243dSDimitry Andric   // Do not proceed if there were undefined or duplicate symbols.
130681ad6265SDimitry Andric   reportPendingUndefinedSymbols();
1307bdd1243dSDimitry Andric   reportPendingDuplicateSymbols();
1308349cc55cSDimitry Andric   if (errorCount())
1309349cc55cSDimitry Andric     return;
1310349cc55cSDimitry Andric 
1311bdd1243dSDimitry Andric   if (in.stubHelper && in.stubHelper->isNeeded())
1312bdd1243dSDimitry Andric     in.stubHelper->setUp();
1313fcaf7f86SDimitry Andric 
1314fcaf7f86SDimitry Andric   if (in.objCImageInfo->isNeeded())
1315fcaf7f86SDimitry Andric     in.objCImageInfo->finalizeContents();
1316fcaf7f86SDimitry Andric 
13171fd87a68SDimitry Andric   // At this point, we should know exactly which output sections are needed,
13181fd87a68SDimitry Andric   // courtesy of scanSymbols() and scanRelocations().
1319fe6060f1SDimitry Andric   createOutputSections<LP>();
1320349cc55cSDimitry Andric 
1321fe6060f1SDimitry Andric   // After this point, we create no new segments; HOWEVER, we might
1322fe6060f1SDimitry Andric   // yet create branch-range extension thunks for architectures whose
1323fe6060f1SDimitry Andric   // hardware call instructions have limited range, e.g., ARM(64).
1324fe6060f1SDimitry Andric   // The thunks are created as InputSections interspersed among
1325fe6060f1SDimitry Andric   // the ordinary __TEXT,_text InputSections.
1326fe6060f1SDimitry Andric   sortSegmentsAndSections();
1327fe6060f1SDimitry Andric   createLoadCommands<LP>();
1328fe6060f1SDimitry Andric   finalizeAddresses();
1329*0fca6ea1SDimitry Andric 
1330*0fca6ea1SDimitry Andric   llvm::thread mapFileWriter([&] {
133104eeddc0SDimitry Andric     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
133204eeddc0SDimitry Andric       timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile");
133304eeddc0SDimitry Andric     writeMapFile();
133404eeddc0SDimitry Andric     if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)
133504eeddc0SDimitry Andric       timeTraceProfilerFinishThread();
133604eeddc0SDimitry Andric   });
1337*0fca6ea1SDimitry Andric 
1338fe6060f1SDimitry Andric   finalizeLinkEditSegment();
1339fe6060f1SDimitry Andric   writeOutputFile();
1340*0fca6ea1SDimitry Andric   mapFileWriter.join();
1341fe6060f1SDimitry Andric }
1342fe6060f1SDimitry Andric 
writeResult()1343fe6060f1SDimitry Andric template <class LP> void macho::writeResult() { Writer().run<LP>(); }
13445ffd83dbSDimitry Andric 
resetWriter()1345349cc55cSDimitry Andric void macho::resetWriter() { LCDylib::resetInstanceCount(); }
1346349cc55cSDimitry Andric 
createSyntheticSections()13475ffd83dbSDimitry Andric void macho::createSyntheticSections() {
1348e8d8bef9SDimitry Andric   in.header = make<MachHeaderSection>();
1349bdd1243dSDimitry Andric   if (config->dedupStrings)
1350bdd1243dSDimitry Andric     in.cStringSection =
1351bdd1243dSDimitry Andric         make<DeduplicatedCStringSection>(section_names::cString);
13521fd87a68SDimitry Andric   else
1353bdd1243dSDimitry Andric     in.cStringSection = make<CStringSection>(section_names::cString);
1354bdd1243dSDimitry Andric   in.objcMethnameSection =
1355bdd1243dSDimitry Andric       make<DeduplicatedCStringSection>(section_names::objcMethname);
1356bdd1243dSDimitry Andric   in.wordLiteralSection = make<WordLiteralSection>();
1357bdd1243dSDimitry Andric   if (config->emitChainedFixups) {
1358bdd1243dSDimitry Andric     in.chainedFixups = make<ChainedFixupsSection>();
1359bdd1243dSDimitry Andric   } else {
1360e8d8bef9SDimitry Andric     in.rebase = make<RebaseSection>();
13615ffd83dbSDimitry Andric     in.binding = make<BindingSection>();
1362e8d8bef9SDimitry Andric     in.weakBinding = make<WeakBindingSection>();
1363e8d8bef9SDimitry Andric     in.lazyBinding = make<LazyBindingSection>();
1364bdd1243dSDimitry Andric     in.lazyPointers = make<LazyPointerSection>();
1365bdd1243dSDimitry Andric     in.stubHelper = make<StubHelperSection>();
1366bdd1243dSDimitry Andric   }
1367e8d8bef9SDimitry Andric   in.exports = make<ExportSection>();
13685ffd83dbSDimitry Andric   in.got = make<GotSection>();
1369e8d8bef9SDimitry Andric   in.tlvPointers = make<TlvPointerSection>();
13705ffd83dbSDimitry Andric   in.stubs = make<StubsSection>();
1371bdd1243dSDimitry Andric   in.objcStubs = make<ObjCStubsSection>();
1372fe6060f1SDimitry Andric   in.unwindInfo = makeUnwindInfoSection();
1373fcaf7f86SDimitry Andric   in.objCImageInfo = make<ObjCImageInfoSection>();
1374bdd1243dSDimitry Andric   in.initOffsets = make<InitOffsetsSection>();
1375*0fca6ea1SDimitry Andric   in.objcMethList = make<ObjCMethListSection>();
1376fe6060f1SDimitry Andric 
1377fe6060f1SDimitry Andric   // This section contains space for just a single word, and will be used by
1378fe6060f1SDimitry Andric   // dyld to cache an address to the image loader it uses.
137904eeddc0SDimitry Andric   uint8_t *arr = bAlloc().Allocate<uint8_t>(target->wordSize);
1380fe6060f1SDimitry Andric   memset(arr, 0, target->wordSize);
138181ad6265SDimitry Andric   in.imageLoaderCache = makeSyntheticInputSection(
138281ad6265SDimitry Andric       segment_names::data, section_names::data, S_REGULAR,
1383fe6060f1SDimitry Andric       ArrayRef<uint8_t>{arr, target->wordSize},
138481ad6265SDimitry Andric       /*align=*/target->wordSize);
1385*0fca6ea1SDimitry Andric   assert(in.imageLoaderCache->live);
13865ffd83dbSDimitry Andric }
1387e8d8bef9SDimitry Andric 
1388e8d8bef9SDimitry Andric OutputSection *macho::firstTLVDataSection = nullptr;
1389fe6060f1SDimitry Andric 
1390fe6060f1SDimitry Andric template void macho::writeResult<LP64>();
1391fe6060f1SDimitry Andric template void macho::writeResult<ILP32>();
1392