Path: blob/main/contrib/llvm-project/lld/MachO/Writer.cpp
34878 views
//===- Writer.cpp ---------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "Writer.h"9#include "ConcatOutputSection.h"10#include "Config.h"11#include "InputFiles.h"12#include "InputSection.h"13#include "MapFile.h"14#include "OutputSection.h"15#include "OutputSegment.h"16#include "SectionPriorities.h"17#include "SymbolTable.h"18#include "Symbols.h"19#include "SyntheticSections.h"20#include "Target.h"21#include "UnwindInfoSection.h"2223#include "lld/Common/Arrays.h"24#include "lld/Common/CommonLinkerContext.h"25#include "llvm/BinaryFormat/MachO.h"26#include "llvm/Config/llvm-config.h"27#include "llvm/Support/LEB128.h"28#include "llvm/Support/Parallel.h"29#include "llvm/Support/Path.h"30#include "llvm/Support/TimeProfiler.h"31#include "llvm/Support/thread.h"32#include "llvm/Support/xxhash.h"3334#include <algorithm>3536using namespace llvm;37using namespace llvm::MachO;38using namespace llvm::sys;39using namespace lld;40using namespace lld::macho;4142namespace {43class LCUuid;4445class Writer {46public:47Writer() : buffer(errorHandler().outputBuffer) {}4849void treatSpecialUndefineds();50void scanRelocations();51void scanSymbols();52template <class LP> void createOutputSections();53template <class LP> void createLoadCommands();54void finalizeAddresses();55void finalizeLinkEditSegment();56void assignAddresses(OutputSegment *);5758void openFile();59void writeSections();60void applyOptimizationHints();61void buildFixupChains();62void writeUuid();63void writeCodeSignature();64void writeOutputFile();6566template <class LP> void run();6768std::unique_ptr<FileOutputBuffer> &buffer;69uint64_t addr = 0;70uint64_t fileOff = 0;71MachHeaderSection *header = nullptr;72StringTableSection *stringTableSection = nullptr;73SymtabSection *symtabSection = nullptr;74IndirectSymtabSection *indirectSymtabSection = nullptr;75CodeSignatureSection *codeSignatureSection = nullptr;76DataInCodeSection *dataInCodeSection = nullptr;77FunctionStartsSection *functionStartsSection = nullptr;7879LCUuid *uuidCommand = nullptr;80OutputSegment *linkEditSegment = nullptr;81};8283// LC_DYLD_INFO_ONLY stores the offsets of symbol import/export information.84class LCDyldInfo final : public LoadCommand {85public:86LCDyldInfo(RebaseSection *rebaseSection, BindingSection *bindingSection,87WeakBindingSection *weakBindingSection,88LazyBindingSection *lazyBindingSection,89ExportSection *exportSection)90: rebaseSection(rebaseSection), bindingSection(bindingSection),91weakBindingSection(weakBindingSection),92lazyBindingSection(lazyBindingSection), exportSection(exportSection) {}9394uint32_t getSize() const override { return sizeof(dyld_info_command); }9596void writeTo(uint8_t *buf) const override {97auto *c = reinterpret_cast<dyld_info_command *>(buf);98c->cmd = LC_DYLD_INFO_ONLY;99c->cmdsize = getSize();100if (rebaseSection->isNeeded()) {101c->rebase_off = rebaseSection->fileOff;102c->rebase_size = rebaseSection->getFileSize();103}104if (bindingSection->isNeeded()) {105c->bind_off = bindingSection->fileOff;106c->bind_size = bindingSection->getFileSize();107}108if (weakBindingSection->isNeeded()) {109c->weak_bind_off = weakBindingSection->fileOff;110c->weak_bind_size = weakBindingSection->getFileSize();111}112if (lazyBindingSection->isNeeded()) {113c->lazy_bind_off = lazyBindingSection->fileOff;114c->lazy_bind_size = lazyBindingSection->getFileSize();115}116if (exportSection->isNeeded()) {117c->export_off = exportSection->fileOff;118c->export_size = exportSection->getFileSize();119}120}121122RebaseSection *rebaseSection;123BindingSection *bindingSection;124WeakBindingSection *weakBindingSection;125LazyBindingSection *lazyBindingSection;126ExportSection *exportSection;127};128129class LCSubFramework final : public LoadCommand {130public:131LCSubFramework(StringRef umbrella) : umbrella(umbrella) {}132133uint32_t getSize() const override {134return alignToPowerOf2(sizeof(sub_framework_command) + umbrella.size() + 1,135target->wordSize);136}137138void writeTo(uint8_t *buf) const override {139auto *c = reinterpret_cast<sub_framework_command *>(buf);140buf += sizeof(sub_framework_command);141142c->cmd = LC_SUB_FRAMEWORK;143c->cmdsize = getSize();144c->umbrella = sizeof(sub_framework_command);145146memcpy(buf, umbrella.data(), umbrella.size());147buf[umbrella.size()] = '\0';148}149150private:151const StringRef umbrella;152};153154class LCFunctionStarts final : public LoadCommand {155public:156explicit LCFunctionStarts(FunctionStartsSection *functionStartsSection)157: functionStartsSection(functionStartsSection) {}158159uint32_t getSize() const override { return sizeof(linkedit_data_command); }160161void writeTo(uint8_t *buf) const override {162auto *c = reinterpret_cast<linkedit_data_command *>(buf);163c->cmd = LC_FUNCTION_STARTS;164c->cmdsize = getSize();165c->dataoff = functionStartsSection->fileOff;166c->datasize = functionStartsSection->getFileSize();167}168169private:170FunctionStartsSection *functionStartsSection;171};172173class LCDataInCode final : public LoadCommand {174public:175explicit LCDataInCode(DataInCodeSection *dataInCodeSection)176: dataInCodeSection(dataInCodeSection) {}177178uint32_t getSize() const override { return sizeof(linkedit_data_command); }179180void writeTo(uint8_t *buf) const override {181auto *c = reinterpret_cast<linkedit_data_command *>(buf);182c->cmd = LC_DATA_IN_CODE;183c->cmdsize = getSize();184c->dataoff = dataInCodeSection->fileOff;185c->datasize = dataInCodeSection->getFileSize();186}187188private:189DataInCodeSection *dataInCodeSection;190};191192class LCDysymtab final : public LoadCommand {193public:194LCDysymtab(SymtabSection *symtabSection,195IndirectSymtabSection *indirectSymtabSection)196: symtabSection(symtabSection),197indirectSymtabSection(indirectSymtabSection) {}198199uint32_t getSize() const override { return sizeof(dysymtab_command); }200201void writeTo(uint8_t *buf) const override {202auto *c = reinterpret_cast<dysymtab_command *>(buf);203c->cmd = LC_DYSYMTAB;204c->cmdsize = getSize();205206c->ilocalsym = 0;207c->iextdefsym = c->nlocalsym = symtabSection->getNumLocalSymbols();208c->nextdefsym = symtabSection->getNumExternalSymbols();209c->iundefsym = c->iextdefsym + c->nextdefsym;210c->nundefsym = symtabSection->getNumUndefinedSymbols();211212c->indirectsymoff = indirectSymtabSection->fileOff;213c->nindirectsyms = indirectSymtabSection->getNumSymbols();214}215216SymtabSection *symtabSection;217IndirectSymtabSection *indirectSymtabSection;218};219220template <class LP> class LCSegment final : public LoadCommand {221public:222LCSegment(StringRef name, OutputSegment *seg) : name(name), seg(seg) {}223224uint32_t getSize() const override {225return sizeof(typename LP::segment_command) +226seg->numNonHiddenSections() * sizeof(typename LP::section);227}228229void writeTo(uint8_t *buf) const override {230using SegmentCommand = typename LP::segment_command;231using SectionHeader = typename LP::section;232233auto *c = reinterpret_cast<SegmentCommand *>(buf);234buf += sizeof(SegmentCommand);235236c->cmd = LP::segmentLCType;237c->cmdsize = getSize();238memcpy(c->segname, name.data(), name.size());239c->fileoff = seg->fileOff;240c->maxprot = seg->maxProt;241c->initprot = seg->initProt;242243c->vmaddr = seg->addr;244c->vmsize = seg->vmSize;245c->filesize = seg->fileSize;246c->nsects = seg->numNonHiddenSections();247c->flags = seg->flags;248249for (const OutputSection *osec : seg->getSections()) {250if (osec->isHidden())251continue;252253auto *sectHdr = reinterpret_cast<SectionHeader *>(buf);254buf += sizeof(SectionHeader);255256memcpy(sectHdr->sectname, osec->name.data(), osec->name.size());257memcpy(sectHdr->segname, name.data(), name.size());258259sectHdr->addr = osec->addr;260sectHdr->offset = osec->fileOff;261sectHdr->align = Log2_32(osec->align);262sectHdr->flags = osec->flags;263sectHdr->size = osec->getSize();264sectHdr->reserved1 = osec->reserved1;265sectHdr->reserved2 = osec->reserved2;266}267}268269private:270StringRef name;271OutputSegment *seg;272};273274class LCMain final : public LoadCommand {275uint32_t getSize() const override {276return sizeof(structs::entry_point_command);277}278279void writeTo(uint8_t *buf) const override {280auto *c = reinterpret_cast<structs::entry_point_command *>(buf);281c->cmd = LC_MAIN;282c->cmdsize = getSize();283284if (config->entry->isInStubs())285c->entryoff =286in.stubs->fileOff + config->entry->stubsIndex * target->stubSize;287else288c->entryoff = config->entry->getVA() - in.header->addr;289290c->stacksize = 0;291}292};293294class LCSymtab final : public LoadCommand {295public:296LCSymtab(SymtabSection *symtabSection, StringTableSection *stringTableSection)297: symtabSection(symtabSection), stringTableSection(stringTableSection) {}298299uint32_t getSize() const override { return sizeof(symtab_command); }300301void writeTo(uint8_t *buf) const override {302auto *c = reinterpret_cast<symtab_command *>(buf);303c->cmd = LC_SYMTAB;304c->cmdsize = getSize();305c->symoff = symtabSection->fileOff;306c->nsyms = symtabSection->getNumSymbols();307c->stroff = stringTableSection->fileOff;308c->strsize = stringTableSection->getFileSize();309}310311SymtabSection *symtabSection = nullptr;312StringTableSection *stringTableSection = nullptr;313};314315// There are several dylib load commands that share the same structure:316// * LC_LOAD_DYLIB317// * LC_ID_DYLIB318// * LC_REEXPORT_DYLIB319class LCDylib final : public LoadCommand {320public:321LCDylib(LoadCommandType type, StringRef path,322uint32_t compatibilityVersion = 0, uint32_t currentVersion = 0)323: type(type), path(path), compatibilityVersion(compatibilityVersion),324currentVersion(currentVersion) {325instanceCount++;326}327328uint32_t getSize() const override {329return alignToPowerOf2(sizeof(dylib_command) + path.size() + 1,330target->wordSize);331}332333void writeTo(uint8_t *buf) const override {334auto *c = reinterpret_cast<dylib_command *>(buf);335buf += sizeof(dylib_command);336337c->cmd = type;338c->cmdsize = getSize();339c->dylib.name = sizeof(dylib_command);340c->dylib.timestamp = 0;341c->dylib.compatibility_version = compatibilityVersion;342c->dylib.current_version = currentVersion;343344memcpy(buf, path.data(), path.size());345buf[path.size()] = '\0';346}347348static uint32_t getInstanceCount() { return instanceCount; }349static void resetInstanceCount() { instanceCount = 0; }350351private:352LoadCommandType type;353StringRef path;354uint32_t compatibilityVersion;355uint32_t currentVersion;356static uint32_t instanceCount;357};358359uint32_t LCDylib::instanceCount = 0;360361class LCLoadDylinker final : public LoadCommand {362public:363uint32_t getSize() const override {364return alignToPowerOf2(sizeof(dylinker_command) + path.size() + 1,365target->wordSize);366}367368void writeTo(uint8_t *buf) const override {369auto *c = reinterpret_cast<dylinker_command *>(buf);370buf += sizeof(dylinker_command);371372c->cmd = LC_LOAD_DYLINKER;373c->cmdsize = getSize();374c->name = sizeof(dylinker_command);375376memcpy(buf, path.data(), path.size());377buf[path.size()] = '\0';378}379380private:381// Recent versions of Darwin won't run any binary that has dyld at a382// different location.383const StringRef path = "/usr/lib/dyld";384};385386class LCRPath final : public LoadCommand {387public:388explicit LCRPath(StringRef path) : path(path) {}389390uint32_t getSize() const override {391return alignToPowerOf2(sizeof(rpath_command) + path.size() + 1,392target->wordSize);393}394395void writeTo(uint8_t *buf) const override {396auto *c = reinterpret_cast<rpath_command *>(buf);397buf += sizeof(rpath_command);398399c->cmd = LC_RPATH;400c->cmdsize = getSize();401c->path = sizeof(rpath_command);402403memcpy(buf, path.data(), path.size());404buf[path.size()] = '\0';405}406407private:408StringRef path;409};410411class LCDyldEnv final : public LoadCommand {412public:413explicit LCDyldEnv(StringRef name) : name(name) {}414415uint32_t getSize() const override {416return alignToPowerOf2(sizeof(dyld_env_command) + name.size() + 1,417target->wordSize);418}419420void writeTo(uint8_t *buf) const override {421auto *c = reinterpret_cast<dyld_env_command *>(buf);422buf += sizeof(dyld_env_command);423424c->cmd = LC_DYLD_ENVIRONMENT;425c->cmdsize = getSize();426c->name = sizeof(dyld_env_command);427428memcpy(buf, name.data(), name.size());429buf[name.size()] = '\0';430}431432private:433StringRef name;434};435436class LCMinVersion final : public LoadCommand {437public:438explicit LCMinVersion(const PlatformInfo &platformInfo)439: platformInfo(platformInfo) {}440441uint32_t getSize() const override { return sizeof(version_min_command); }442443void writeTo(uint8_t *buf) const override {444auto *c = reinterpret_cast<version_min_command *>(buf);445switch (platformInfo.target.Platform) {446case PLATFORM_MACOS:447c->cmd = LC_VERSION_MIN_MACOSX;448break;449case PLATFORM_IOS:450case PLATFORM_IOSSIMULATOR:451c->cmd = LC_VERSION_MIN_IPHONEOS;452break;453case PLATFORM_TVOS:454case PLATFORM_TVOSSIMULATOR:455c->cmd = LC_VERSION_MIN_TVOS;456break;457case PLATFORM_WATCHOS:458case PLATFORM_WATCHOSSIMULATOR:459c->cmd = LC_VERSION_MIN_WATCHOS;460break;461default:462llvm_unreachable("invalid platform");463break;464}465c->cmdsize = getSize();466c->version = encodeVersion(platformInfo.target.MinDeployment);467c->sdk = encodeVersion(platformInfo.sdk);468}469470private:471const PlatformInfo &platformInfo;472};473474class LCBuildVersion final : public LoadCommand {475public:476explicit LCBuildVersion(const PlatformInfo &platformInfo)477: platformInfo(platformInfo) {}478479const int ntools = 1;480481uint32_t getSize() const override {482return sizeof(build_version_command) + ntools * sizeof(build_tool_version);483}484485void writeTo(uint8_t *buf) const override {486auto *c = reinterpret_cast<build_version_command *>(buf);487c->cmd = LC_BUILD_VERSION;488c->cmdsize = getSize();489490c->platform = static_cast<uint32_t>(platformInfo.target.Platform);491c->minos = encodeVersion(platformInfo.target.MinDeployment);492c->sdk = encodeVersion(platformInfo.sdk);493494c->ntools = ntools;495auto *t = reinterpret_cast<build_tool_version *>(&c[1]);496t->tool = TOOL_LLD;497t->version = encodeVersion(VersionTuple(498LLVM_VERSION_MAJOR, LLVM_VERSION_MINOR, LLVM_VERSION_PATCH));499}500501private:502const PlatformInfo &platformInfo;503};504505// Stores a unique identifier for the output file based on an MD5 hash of its506// contents. In order to hash the contents, we must first write them, but507// LC_UUID itself must be part of the written contents in order for all the508// offsets to be calculated correctly. We resolve this circular paradox by509// first writing an LC_UUID with an all-zero UUID, then updating the UUID with510// its real value later.511class LCUuid final : public LoadCommand {512public:513uint32_t getSize() const override { return sizeof(uuid_command); }514515void writeTo(uint8_t *buf) const override {516auto *c = reinterpret_cast<uuid_command *>(buf);517c->cmd = LC_UUID;518c->cmdsize = getSize();519uuidBuf = c->uuid;520}521522void writeUuid(uint64_t digest) const {523// xxhash only gives us 8 bytes, so put some fixed data in the other half.524static_assert(sizeof(uuid_command::uuid) == 16, "unexpected uuid size");525memcpy(uuidBuf, "LLD\xa1UU1D", 8);526memcpy(uuidBuf + 8, &digest, 8);527528// RFC 4122 conformance. We need to fix 4 bits in byte 6 and 2 bits in529// byte 8. Byte 6 is already fine due to the fixed data we put in. We don't530// want to lose bits of the digest in byte 8, so swap that with a byte of531// fixed data that happens to have the right bits set.532std::swap(uuidBuf[3], uuidBuf[8]);533534// Claim that this is an MD5-based hash. It isn't, but this signals that535// this is not a time-based and not a random hash. MD5 seems like the least536// bad lie we can put here.537assert((uuidBuf[6] & 0xf0) == 0x30 && "See RFC 4122 Sections 4.2.2, 4.1.3");538assert((uuidBuf[8] & 0xc0) == 0x80 && "See RFC 4122 Section 4.2.2");539}540541mutable uint8_t *uuidBuf;542};543544template <class LP> class LCEncryptionInfo final : public LoadCommand {545public:546uint32_t getSize() const override {547return sizeof(typename LP::encryption_info_command);548}549550void writeTo(uint8_t *buf) const override {551using EncryptionInfo = typename LP::encryption_info_command;552auto *c = reinterpret_cast<EncryptionInfo *>(buf);553buf += sizeof(EncryptionInfo);554c->cmd = LP::encryptionInfoLCType;555c->cmdsize = getSize();556c->cryptoff = in.header->getSize();557auto it = find_if(outputSegments, [](const OutputSegment *seg) {558return seg->name == segment_names::text;559});560assert(it != outputSegments.end());561c->cryptsize = (*it)->fileSize - c->cryptoff;562}563};564565class LCCodeSignature final : public LoadCommand {566public:567LCCodeSignature(CodeSignatureSection *section) : section(section) {}568569uint32_t getSize() const override { return sizeof(linkedit_data_command); }570571void writeTo(uint8_t *buf) const override {572auto *c = reinterpret_cast<linkedit_data_command *>(buf);573c->cmd = LC_CODE_SIGNATURE;574c->cmdsize = getSize();575c->dataoff = static_cast<uint32_t>(section->fileOff);576c->datasize = section->getSize();577}578579CodeSignatureSection *section;580};581582class LCExportsTrie final : public LoadCommand {583public:584LCExportsTrie(ExportSection *section) : section(section) {}585586uint32_t getSize() const override { return sizeof(linkedit_data_command); }587588void writeTo(uint8_t *buf) const override {589auto *c = reinterpret_cast<linkedit_data_command *>(buf);590c->cmd = LC_DYLD_EXPORTS_TRIE;591c->cmdsize = getSize();592c->dataoff = section->fileOff;593c->datasize = section->getSize();594}595596ExportSection *section;597};598599class LCChainedFixups final : public LoadCommand {600public:601LCChainedFixups(ChainedFixupsSection *section) : section(section) {}602603uint32_t getSize() const override { return sizeof(linkedit_data_command); }604605void writeTo(uint8_t *buf) const override {606auto *c = reinterpret_cast<linkedit_data_command *>(buf);607c->cmd = LC_DYLD_CHAINED_FIXUPS;608c->cmdsize = getSize();609c->dataoff = section->fileOff;610c->datasize = section->getSize();611}612613ChainedFixupsSection *section;614};615616} // namespace617618void Writer::treatSpecialUndefineds() {619if (config->entry)620if (auto *undefined = dyn_cast<Undefined>(config->entry))621treatUndefinedSymbol(*undefined, "the entry point");622623// FIXME: This prints symbols that are undefined both in input files and624// via -u flag twice.625for (const Symbol *sym : config->explicitUndefineds) {626if (const auto *undefined = dyn_cast<Undefined>(sym))627treatUndefinedSymbol(*undefined, "-u");628}629// Literal exported-symbol names must be defined, but glob630// patterns need not match.631for (const CachedHashStringRef &cachedName :632config->exportedSymbols.literals) {633if (const Symbol *sym = symtab->find(cachedName))634if (const auto *undefined = dyn_cast<Undefined>(sym))635treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");636}637}638639static void prepareSymbolRelocation(Symbol *sym, const InputSection *isec,640const lld::macho::Reloc &r) {641if (!sym->isLive()) {642if (Defined *defined = dyn_cast<Defined>(sym)) {643if (config->emitInitOffsets &&644defined->isec()->getName() == section_names::moduleInitFunc)645fatal(isec->getLocation(r.offset) + ": cannot reference " +646sym->getName() +647" defined in __mod_init_func when -init_offsets is used");648}649assert(false && "referenced symbol must be live");650}651652const RelocAttrs &relocAttrs = target->getRelocAttrs(r.type);653654if (relocAttrs.hasAttr(RelocAttrBits::BRANCH)) {655if (needsBinding(sym))656in.stubs->addEntry(sym);657} else if (relocAttrs.hasAttr(RelocAttrBits::GOT)) {658if (relocAttrs.hasAttr(RelocAttrBits::POINTER) || needsBinding(sym))659in.got->addEntry(sym);660} else if (relocAttrs.hasAttr(RelocAttrBits::TLV)) {661if (needsBinding(sym))662in.tlvPointers->addEntry(sym);663} else if (relocAttrs.hasAttr(RelocAttrBits::UNSIGNED)) {664// References from thread-local variable sections are treated as offsets665// relative to the start of the referent section, and therefore have no666// need of rebase opcodes.667if (!(isThreadLocalVariables(isec->getFlags()) && isa<Defined>(sym)))668addNonLazyBindingEntries(sym, isec, r.offset, r.addend);669}670}671672void Writer::scanRelocations() {673TimeTraceScope timeScope("Scan relocations");674675// This can't use a for-each loop: It calls treatUndefinedSymbol(), which can676// add to inputSections, which invalidates inputSections's iterators.677for (size_t i = 0; i < inputSections.size(); ++i) {678ConcatInputSection *isec = inputSections[i];679680if (isec->shouldOmitFromOutput())681continue;682683for (auto it = isec->relocs.begin(); it != isec->relocs.end(); ++it) {684lld::macho::Reloc &r = *it;685686// Canonicalize the referent so that later accesses in Writer won't687// have to worry about it.688if (auto *referentIsec = r.referent.dyn_cast<InputSection *>())689r.referent = referentIsec->canonical();690691if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {692// Skip over the following UNSIGNED relocation -- it's just there as the693// minuend, and doesn't have the usual UNSIGNED semantics. We don't want694// to emit rebase opcodes for it.695++it;696// Canonicalize the referent so that later accesses in Writer won't697// have to worry about it.698if (auto *referentIsec = it->referent.dyn_cast<InputSection *>())699it->referent = referentIsec->canonical();700continue;701}702if (auto *sym = r.referent.dyn_cast<Symbol *>()) {703if (auto *undefined = dyn_cast<Undefined>(sym))704treatUndefinedSymbol(*undefined, isec, r.offset);705// treatUndefinedSymbol() can replace sym with a DylibSymbol; re-check.706if (!isa<Undefined>(sym) && validateSymbolRelocation(sym, isec, r))707prepareSymbolRelocation(sym, isec, r);708} else {709if (!r.pcrel) {710if (config->emitChainedFixups)711in.chainedFixups->addRebase(isec, r.offset);712else713in.rebase->addEntry(isec, r.offset);714}715}716}717}718719in.unwindInfo->prepare();720}721722static void addNonWeakDefinition(const Defined *defined) {723if (config->emitChainedFixups)724in.chainedFixups->setHasNonWeakDefinition();725else726in.weakBinding->addNonWeakDefinition(defined);727}728729void Writer::scanSymbols() {730TimeTraceScope timeScope("Scan symbols");731ObjCSelRefsHelper::initialize();732for (Symbol *sym : symtab->getSymbols()) {733if (auto *defined = dyn_cast<Defined>(sym)) {734if (!defined->isLive())735continue;736if (defined->overridesWeakDef)737addNonWeakDefinition(defined);738if (!defined->isAbsolute() && isCodeSection(defined->isec()))739in.unwindInfo->addSymbol(defined);740} else if (const auto *dysym = dyn_cast<DylibSymbol>(sym)) {741// This branch intentionally doesn't check isLive().742if (dysym->isDynamicLookup())743continue;744dysym->getFile()->refState =745std::max(dysym->getFile()->refState, dysym->getRefState());746} else if (isa<Undefined>(sym)) {747if (ObjCStubsSection::isObjCStubSymbol(sym)) {748// When -dead_strip is enabled, we don't want to emit any dead stubs.749// Although this stub symbol is yet undefined, addSym() was called750// during MarkLive.751if (config->deadStrip) {752if (!sym->isLive())753continue;754}755in.objcStubs->addEntry(sym);756}757}758}759760for (const InputFile *file : inputFiles) {761if (auto *objFile = dyn_cast<ObjFile>(file))762for (Symbol *sym : objFile->symbols) {763if (auto *defined = dyn_cast_or_null<Defined>(sym)) {764if (!defined->isLive())765continue;766if (!defined->isExternal() && !defined->isAbsolute() &&767isCodeSection(defined->isec()))768in.unwindInfo->addSymbol(defined);769}770}771}772}773774// TODO: ld64 enforces the old load commands in a few other cases.775static bool useLCBuildVersion(const PlatformInfo &platformInfo) {776static const std::array<std::pair<PlatformType, VersionTuple>, 7> minVersion =777{{{PLATFORM_MACOS, VersionTuple(10, 14)},778{PLATFORM_IOS, VersionTuple(12, 0)},779{PLATFORM_IOSSIMULATOR, VersionTuple(13, 0)},780{PLATFORM_TVOS, VersionTuple(12, 0)},781{PLATFORM_TVOSSIMULATOR, VersionTuple(13, 0)},782{PLATFORM_WATCHOS, VersionTuple(5, 0)},783{PLATFORM_WATCHOSSIMULATOR, VersionTuple(6, 0)}}};784auto it = llvm::find_if(minVersion, [&](const auto &p) {785return p.first == platformInfo.target.Platform;786});787return it == minVersion.end()788? true789: platformInfo.target.MinDeployment >= it->second;790}791792template <class LP> void Writer::createLoadCommands() {793uint8_t segIndex = 0;794for (OutputSegment *seg : outputSegments) {795in.header->addLoadCommand(make<LCSegment<LP>>(seg->name, seg));796seg->index = segIndex++;797}798799if (config->emitChainedFixups) {800in.header->addLoadCommand(make<LCChainedFixups>(in.chainedFixups));801in.header->addLoadCommand(make<LCExportsTrie>(in.exports));802} else {803in.header->addLoadCommand(make<LCDyldInfo>(804in.rebase, in.binding, in.weakBinding, in.lazyBinding, in.exports));805}806in.header->addLoadCommand(make<LCSymtab>(symtabSection, stringTableSection));807in.header->addLoadCommand(808make<LCDysymtab>(symtabSection, indirectSymtabSection));809if (!config->umbrella.empty())810in.header->addLoadCommand(make<LCSubFramework>(config->umbrella));811if (config->emitEncryptionInfo)812in.header->addLoadCommand(make<LCEncryptionInfo<LP>>());813for (StringRef path : config->runtimePaths)814in.header->addLoadCommand(make<LCRPath>(path));815816switch (config->outputType) {817case MH_EXECUTE:818in.header->addLoadCommand(make<LCLoadDylinker>());819break;820case MH_DYLIB:821in.header->addLoadCommand(make<LCDylib>(LC_ID_DYLIB, config->installName,822config->dylibCompatibilityVersion,823config->dylibCurrentVersion));824break;825case MH_BUNDLE:826break;827default:828llvm_unreachable("unhandled output file type");829}830831if (config->generateUuid) {832uuidCommand = make<LCUuid>();833in.header->addLoadCommand(uuidCommand);834}835836if (useLCBuildVersion(config->platformInfo))837in.header->addLoadCommand(make<LCBuildVersion>(config->platformInfo));838else839in.header->addLoadCommand(make<LCMinVersion>(config->platformInfo));840841if (config->secondaryPlatformInfo) {842in.header->addLoadCommand(843make<LCBuildVersion>(*config->secondaryPlatformInfo));844}845846// This is down here to match ld64's load command order.847if (config->outputType == MH_EXECUTE)848in.header->addLoadCommand(make<LCMain>());849850// See ld64's OutputFile::buildDylibOrdinalMapping for the corresponding851// library ordinal computation code in ld64.852int64_t dylibOrdinal = 1;853DenseMap<StringRef, int64_t> ordinalForInstallName;854855std::vector<DylibFile *> dylibFiles;856for (InputFile *file : inputFiles) {857if (auto *dylibFile = dyn_cast<DylibFile>(file))858dylibFiles.push_back(dylibFile);859}860for (size_t i = 0; i < dylibFiles.size(); ++i)861dylibFiles.insert(dylibFiles.end(), dylibFiles[i]->extraDylibs.begin(),862dylibFiles[i]->extraDylibs.end());863864for (DylibFile *dylibFile : dylibFiles) {865if (dylibFile->isBundleLoader) {866dylibFile->ordinal = BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE;867// Shortcut since bundle-loader does not re-export the symbols.868869dylibFile->reexport = false;870continue;871}872873// Don't emit load commands for a dylib that is not referenced if:874// - it was added implicitly (via a reexport, an LC_LOAD_DYLINKER --875// if it's on the linker command line, it's explicit)876// - or it's marked MH_DEAD_STRIPPABLE_DYLIB877// - or the flag -dead_strip_dylibs is used878// FIXME: `isReferenced()` is currently computed before dead code879// stripping, so references from dead code keep a dylib alive. This880// matches ld64, but it's something we should do better.881if (!dylibFile->isReferenced() && !dylibFile->forceNeeded &&882(!dylibFile->isExplicitlyLinked() || dylibFile->deadStrippable ||883config->deadStripDylibs))884continue;885886// Several DylibFiles can have the same installName. Only emit a single887// load command for that installName and give all these DylibFiles the888// same ordinal.889// This can happen in several cases:890// - a new framework could change its installName to an older891// framework name via an $ld$ symbol depending on platform_version892// - symlinks (for example, libpthread.tbd is a symlink to libSystem.tbd;893// Foo.framework/Foo.tbd is usually a symlink to894// Foo.framework/Versions/Current/Foo.tbd, where895// Foo.framework/Versions/Current is usually a symlink to896// Foo.framework/Versions/A)897// - a framework can be linked both explicitly on the linker898// command line and implicitly as a reexport from a different899// framework. The re-export will usually point to the tbd file900// in Foo.framework/Versions/A/Foo.tbd, while the explicit link will901// usually find Foo.framework/Foo.tbd. These are usually symlinks,902// but in a --reproduce archive they will be identical but distinct903// files.904// In the first case, *semantically distinct* DylibFiles will have the905// same installName.906int64_t &ordinal = ordinalForInstallName[dylibFile->installName];907if (ordinal) {908dylibFile->ordinal = ordinal;909continue;910}911912ordinal = dylibFile->ordinal = dylibOrdinal++;913LoadCommandType lcType =914dylibFile->forceWeakImport || dylibFile->refState == RefState::Weak915? LC_LOAD_WEAK_DYLIB916: LC_LOAD_DYLIB;917in.header->addLoadCommand(make<LCDylib>(lcType, dylibFile->installName,918dylibFile->compatibilityVersion,919dylibFile->currentVersion));920921if (dylibFile->reexport)922in.header->addLoadCommand(923make<LCDylib>(LC_REEXPORT_DYLIB, dylibFile->installName));924}925926for (const auto &dyldEnv : config->dyldEnvs)927in.header->addLoadCommand(make<LCDyldEnv>(dyldEnv));928929if (functionStartsSection)930in.header->addLoadCommand(make<LCFunctionStarts>(functionStartsSection));931if (dataInCodeSection)932in.header->addLoadCommand(make<LCDataInCode>(dataInCodeSection));933if (codeSignatureSection)934in.header->addLoadCommand(make<LCCodeSignature>(codeSignatureSection));935936const uint32_t MACOS_MAXPATHLEN = 1024;937config->headerPad = std::max(938config->headerPad, (config->headerPadMaxInstallNames939? LCDylib::getInstanceCount() * MACOS_MAXPATHLEN940: 0));941}942943// Sorting only can happen once all outputs have been collected. Here we sort944// segments, output sections within each segment, and input sections within each945// output segment.946static void sortSegmentsAndSections() {947TimeTraceScope timeScope("Sort segments and sections");948sortOutputSegments();949950DenseMap<const InputSection *, size_t> isecPriorities =951priorityBuilder.buildInputSectionPriorities();952953uint32_t sectionIndex = 0;954for (OutputSegment *seg : outputSegments) {955seg->sortOutputSections();956// References from thread-local variable sections are treated as offsets957// relative to the start of the thread-local data memory area, which958// is initialized via copying all the TLV data sections (which are all959// contiguous). If later data sections require a greater alignment than960// earlier ones, the offsets of data within those sections won't be961// guaranteed to aligned unless we normalize alignments. We therefore use962// the largest alignment for all TLV data sections.963uint32_t tlvAlign = 0;964for (const OutputSection *osec : seg->getSections())965if (isThreadLocalData(osec->flags) && osec->align > tlvAlign)966tlvAlign = osec->align;967968for (OutputSection *osec : seg->getSections()) {969// Now that the output sections are sorted, assign the final970// output section indices.971if (!osec->isHidden())972osec->index = ++sectionIndex;973if (isThreadLocalData(osec->flags)) {974if (!firstTLVDataSection)975firstTLVDataSection = osec;976osec->align = tlvAlign;977}978979if (!isecPriorities.empty()) {980if (auto *merged = dyn_cast<ConcatOutputSection>(osec)) {981llvm::stable_sort(982merged->inputs, [&](InputSection *a, InputSection *b) {983return isecPriorities.lookup(a) > isecPriorities.lookup(b);984});985}986}987}988}989}990991template <class LP> void Writer::createOutputSections() {992TimeTraceScope timeScope("Create output sections");993// First, create hidden sections994stringTableSection = make<StringTableSection>();995symtabSection = makeSymtabSection<LP>(*stringTableSection);996indirectSymtabSection = make<IndirectSymtabSection>();997if (config->adhocCodesign)998codeSignatureSection = make<CodeSignatureSection>();999if (config->emitDataInCodeInfo)1000dataInCodeSection = make<DataInCodeSection>();1001if (config->emitFunctionStarts)1002functionStartsSection = make<FunctionStartsSection>();10031004switch (config->outputType) {1005case MH_EXECUTE:1006make<PageZeroSection>();1007break;1008case MH_DYLIB:1009case MH_BUNDLE:1010break;1011default:1012llvm_unreachable("unhandled output file type");1013}10141015// Then add input sections to output sections.1016for (ConcatInputSection *isec : inputSections) {1017if (isec->shouldOmitFromOutput())1018continue;1019ConcatOutputSection *osec = cast<ConcatOutputSection>(isec->parent);1020osec->addInput(isec);1021osec->inputOrder =1022std::min(osec->inputOrder, static_cast<int>(isec->outSecOff));1023}10241025// Once all the inputs are added, we can finalize the output section1026// properties and create the corresponding output segments.1027for (const auto &it : concatOutputSections) {1028StringRef segname = it.first.first;1029ConcatOutputSection *osec = it.second;1030assert(segname != segment_names::ld);1031if (osec->isNeeded()) {1032// See comment in ObjFile::splitEhFrames()1033if (osec->name == section_names::ehFrame &&1034segname == segment_names::text)1035osec->align = target->wordSize;10361037// MC keeps the default 1-byte alignment for __thread_vars, even though it1038// contains pointers that are fixed up by dyld, which requires proper1039// alignment.1040if (isThreadLocalVariables(osec->flags))1041osec->align = std::max<uint32_t>(osec->align, target->wordSize);10421043getOrCreateOutputSegment(segname)->addOutputSection(osec);1044}1045}10461047for (SyntheticSection *ssec : syntheticSections) {1048auto it = concatOutputSections.find({ssec->segname, ssec->name});1049// We add all LinkEdit sections here because we don't know if they are1050// needed until their finalizeContents() methods get called later. While1051// this means that we add some redundant sections to __LINKEDIT, there is1052// is no redundancy in the output, as we do not emit section headers for1053// any LinkEdit sections.1054if (ssec->isNeeded() || ssec->segname == segment_names::linkEdit) {1055if (it == concatOutputSections.end()) {1056getOrCreateOutputSegment(ssec->segname)->addOutputSection(ssec);1057} else {1058fatal("section from " +1059toString(it->second->firstSection()->getFile()) +1060" conflicts with synthetic section " + ssec->segname + "," +1061ssec->name);1062}1063}1064}10651066// dyld requires __LINKEDIT segment to always exist (even if empty).1067linkEditSegment = getOrCreateOutputSegment(segment_names::linkEdit);1068}10691070void Writer::finalizeAddresses() {1071TimeTraceScope timeScope("Finalize addresses");1072uint64_t pageSize = target->getPageSize();10731074// We could parallelize this loop, but local benchmarking indicates it is1075// faster to do it all in the main thread.1076for (OutputSegment *seg : outputSegments) {1077if (seg == linkEditSegment)1078continue;1079for (OutputSection *osec : seg->getSections()) {1080if (!osec->isNeeded())1081continue;1082// Other kinds of OutputSections have already been finalized.1083if (auto *concatOsec = dyn_cast<ConcatOutputSection>(osec))1084concatOsec->finalizeContents();1085}1086}10871088// Ensure that segments (and the sections they contain) are allocated1089// addresses in ascending order, which dyld requires.1090//1091// Note that at this point, __LINKEDIT sections are empty, but we need to1092// determine addresses of other segments/sections before generating its1093// contents.1094for (OutputSegment *seg : outputSegments) {1095if (seg == linkEditSegment)1096continue;1097seg->addr = addr;1098assignAddresses(seg);1099// codesign / libstuff checks for segment ordering by verifying that1100// `fileOff + fileSize == next segment fileOff`. So we call1101// alignToPowerOf2() before (instead of after) computing fileSize to ensure1102// that the segments are contiguous. We handle addr / vmSize similarly for1103// the same reason.1104fileOff = alignToPowerOf2(fileOff, pageSize);1105addr = alignToPowerOf2(addr, pageSize);1106seg->vmSize = addr - seg->addr;1107seg->fileSize = fileOff - seg->fileOff;1108seg->assignAddressesToStartEndSymbols();1109}1110}11111112void Writer::finalizeLinkEditSegment() {1113TimeTraceScope timeScope("Finalize __LINKEDIT segment");1114// Fill __LINKEDIT contents.1115std::array<LinkEditSection *, 10> linkEditSections{1116in.rebase, in.binding,1117in.weakBinding, in.lazyBinding,1118in.exports, in.chainedFixups,1119symtabSection, indirectSymtabSection,1120dataInCodeSection, functionStartsSection,1121};11221123parallelForEach(linkEditSections.begin(), linkEditSections.end(),1124[](LinkEditSection *osec) {1125if (osec)1126osec->finalizeContents();1127});11281129// Now that __LINKEDIT is filled out, do a proper calculation of its1130// addresses and offsets.1131linkEditSegment->addr = addr;1132assignAddresses(linkEditSegment);1133// No need to page-align fileOff / addr here since this is the last segment.1134linkEditSegment->vmSize = addr - linkEditSegment->addr;1135linkEditSegment->fileSize = fileOff - linkEditSegment->fileOff;1136}11371138void Writer::assignAddresses(OutputSegment *seg) {1139seg->fileOff = fileOff;11401141for (OutputSection *osec : seg->getSections()) {1142if (!osec->isNeeded())1143continue;1144addr = alignToPowerOf2(addr, osec->align);1145fileOff = alignToPowerOf2(fileOff, osec->align);1146osec->addr = addr;1147osec->fileOff = isZeroFill(osec->flags) ? 0 : fileOff;1148osec->finalize();1149osec->assignAddressesToStartEndSymbols();11501151addr += osec->getSize();1152fileOff += osec->getFileSize();1153}1154}11551156void Writer::openFile() {1157Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =1158FileOutputBuffer::create(config->outputFile, fileOff,1159FileOutputBuffer::F_executable);11601161if (!bufferOrErr)1162fatal("failed to open " + config->outputFile + ": " +1163llvm::toString(bufferOrErr.takeError()));1164buffer = std::move(*bufferOrErr);1165in.bufferStart = buffer->getBufferStart();1166}11671168void Writer::writeSections() {1169TimeTraceScope timeScope("Write output sections");11701171uint8_t *buf = buffer->getBufferStart();1172std::vector<const OutputSection *> osecs;1173for (const OutputSegment *seg : outputSegments)1174append_range(osecs, seg->getSections());11751176parallelForEach(osecs.begin(), osecs.end(), [&](const OutputSection *osec) {1177osec->writeTo(buf + osec->fileOff);1178});1179}11801181void Writer::applyOptimizationHints() {1182if (config->arch() != AK_arm64 || config->ignoreOptimizationHints)1183return;11841185uint8_t *buf = buffer->getBufferStart();1186TimeTraceScope timeScope("Apply linker optimization hints");1187parallelForEach(inputFiles, [buf](const InputFile *file) {1188if (const auto *objFile = dyn_cast<ObjFile>(file))1189target->applyOptimizationHints(buf, *objFile);1190});1191}11921193// In order to utilize multiple cores, we first split the buffer into chunks,1194// compute a hash for each chunk, and then compute a hash value of the hash1195// values.1196void Writer::writeUuid() {1197TimeTraceScope timeScope("Computing UUID");11981199ArrayRef<uint8_t> data{buffer->getBufferStart(), buffer->getBufferEnd()};1200std::vector<ArrayRef<uint8_t>> chunks = split(data, 1024 * 1024);12011202// Leave one slot for filename1203std::vector<uint64_t> hashes(chunks.size() + 1);1204parallelFor(0, chunks.size(),1205[&](size_t i) { hashes[i] = xxh3_64bits(chunks[i]); });1206// Append the output filename so that identical binaries with different names1207// don't get the same UUID.1208hashes[chunks.size()] = xxh3_64bits(sys::path::filename(config->finalOutput));12091210uint64_t digest = xxh3_64bits({reinterpret_cast<uint8_t *>(hashes.data()),1211hashes.size() * sizeof(uint64_t)});1212uuidCommand->writeUuid(digest);1213}12141215// This is step 5 of the algorithm described in the class comment of1216// ChainedFixupsSection.1217void Writer::buildFixupChains() {1218if (!config->emitChainedFixups)1219return;12201221const std::vector<Location> &loc = in.chainedFixups->getLocations();1222if (loc.empty())1223return;12241225TimeTraceScope timeScope("Build fixup chains");12261227const uint64_t pageSize = target->getPageSize();1228constexpr uint32_t stride = 4; // for DYLD_CHAINED_PTR_6412291230for (size_t i = 0, count = loc.size(); i < count;) {1231const OutputSegment *oseg = loc[i].isec->parent->parent;1232uint8_t *buf = buffer->getBufferStart() + oseg->fileOff;1233uint64_t pageIdx = loc[i].offset / pageSize;1234++i;12351236while (i < count && loc[i].isec->parent->parent == oseg &&1237(loc[i].offset / pageSize) == pageIdx) {1238uint64_t offset = loc[i].offset - loc[i - 1].offset;12391240auto fail = [&](Twine message) {1241error(loc[i].isec->getSegName() + "," + loc[i].isec->getName() +1242", offset " +1243Twine(loc[i].offset - loc[i].isec->parent->getSegmentOffset()) +1244": " + message);1245};12461247if (offset < target->wordSize)1248return fail("fixups overlap");1249if (offset % stride != 0)1250return fail(1251"fixups are unaligned (offset " + Twine(offset) +1252" is not a multiple of the stride). Re-link with -no_fixup_chains");12531254// The "next" field is in the same location for bind and rebase entries.1255reinterpret_cast<dyld_chained_ptr_64_bind *>(buf + loc[i - 1].offset)1256->next = offset / stride;1257++i;1258}1259}1260}12611262void Writer::writeCodeSignature() {1263if (codeSignatureSection) {1264TimeTraceScope timeScope("Write code signature");1265codeSignatureSection->writeHashes(buffer->getBufferStart());1266}1267}12681269void Writer::writeOutputFile() {1270TimeTraceScope timeScope("Write output file");1271openFile();1272reportPendingUndefinedSymbols();1273if (errorCount())1274return;1275writeSections();1276applyOptimizationHints();1277buildFixupChains();1278if (config->generateUuid)1279writeUuid();1280writeCodeSignature();12811282if (auto e = buffer->commit())1283fatal("failed to write output '" + buffer->getPath() +1284"': " + toString(std::move(e)));1285}12861287template <class LP> void Writer::run() {1288treatSpecialUndefineds();1289if (config->entry && needsBinding(config->entry))1290in.stubs->addEntry(config->entry);12911292// Canonicalization of all pointers to InputSections should be handled by1293// these two scan* methods. I.e. from this point onward, for all live1294// InputSections, we should have `isec->canonical() == isec`.1295scanSymbols();1296if (in.objcStubs->isNeeded())1297in.objcStubs->setUp();1298if (in.objcMethList->isNeeded())1299in.objcMethList->setUp();1300scanRelocations();1301if (in.initOffsets->isNeeded())1302in.initOffsets->setUp();13031304// Do not proceed if there were undefined or duplicate symbols.1305reportPendingUndefinedSymbols();1306reportPendingDuplicateSymbols();1307if (errorCount())1308return;13091310if (in.stubHelper && in.stubHelper->isNeeded())1311in.stubHelper->setUp();13121313if (in.objCImageInfo->isNeeded())1314in.objCImageInfo->finalizeContents();13151316// At this point, we should know exactly which output sections are needed,1317// courtesy of scanSymbols() and scanRelocations().1318createOutputSections<LP>();13191320// After this point, we create no new segments; HOWEVER, we might1321// yet create branch-range extension thunks for architectures whose1322// hardware call instructions have limited range, e.g., ARM(64).1323// The thunks are created as InputSections interspersed among1324// the ordinary __TEXT,_text InputSections.1325sortSegmentsAndSections();1326createLoadCommands<LP>();1327finalizeAddresses();13281329llvm::thread mapFileWriter([&] {1330if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)1331timeTraceProfilerInitialize(config->timeTraceGranularity, "writeMapFile");1332writeMapFile();1333if (LLVM_ENABLE_THREADS && config->timeTraceEnabled)1334timeTraceProfilerFinishThread();1335});13361337finalizeLinkEditSegment();1338writeOutputFile();1339mapFileWriter.join();1340}13411342template <class LP> void macho::writeResult() { Writer().run<LP>(); }13431344void macho::resetWriter() { LCDylib::resetInstanceCount(); }13451346void macho::createSyntheticSections() {1347in.header = make<MachHeaderSection>();1348if (config->dedupStrings)1349in.cStringSection =1350make<DeduplicatedCStringSection>(section_names::cString);1351else1352in.cStringSection = make<CStringSection>(section_names::cString);1353in.objcMethnameSection =1354make<DeduplicatedCStringSection>(section_names::objcMethname);1355in.wordLiteralSection = make<WordLiteralSection>();1356if (config->emitChainedFixups) {1357in.chainedFixups = make<ChainedFixupsSection>();1358} else {1359in.rebase = make<RebaseSection>();1360in.binding = make<BindingSection>();1361in.weakBinding = make<WeakBindingSection>();1362in.lazyBinding = make<LazyBindingSection>();1363in.lazyPointers = make<LazyPointerSection>();1364in.stubHelper = make<StubHelperSection>();1365}1366in.exports = make<ExportSection>();1367in.got = make<GotSection>();1368in.tlvPointers = make<TlvPointerSection>();1369in.stubs = make<StubsSection>();1370in.objcStubs = make<ObjCStubsSection>();1371in.unwindInfo = makeUnwindInfoSection();1372in.objCImageInfo = make<ObjCImageInfoSection>();1373in.initOffsets = make<InitOffsetsSection>();1374in.objcMethList = make<ObjCMethListSection>();13751376// This section contains space for just a single word, and will be used by1377// dyld to cache an address to the image loader it uses.1378uint8_t *arr = bAlloc().Allocate<uint8_t>(target->wordSize);1379memset(arr, 0, target->wordSize);1380in.imageLoaderCache = makeSyntheticInputSection(1381segment_names::data, section_names::data, S_REGULAR,1382ArrayRef<uint8_t>{arr, target->wordSize},1383/*align=*/target->wordSize);1384assert(in.imageLoaderCache->live);1385}13861387OutputSection *macho::firstTLVDataSection = nullptr;13881389template void macho::writeResult<LP64>();1390template void macho::writeResult<ILP32>();139113921393