| 1 | //===- lib/MC/MachObjectWriter.cpp - Mach-O File Writer -------------------===// |
| 2 | // |
| 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "llvm/ADT/DenseMap.h" |
| 10 | #include "llvm/ADT/Twine.h" |
| 11 | #include "llvm/BinaryFormat/MachO.h" |
| 12 | #include "llvm/MC/MCAsmBackend.h" |
| 13 | #include "llvm/MC/MCAsmInfoDarwin.h" |
| 14 | #include "llvm/MC/MCAssembler.h" |
| 15 | #include "llvm/MC/MCContext.h" |
| 16 | #include "llvm/MC/MCDirectives.h" |
| 17 | #include "llvm/MC/MCExpr.h" |
| 18 | #include "llvm/MC/MCMachObjectWriter.h" |
| 19 | #include "llvm/MC/MCObjectFileInfo.h" |
| 20 | #include "llvm/MC/MCObjectWriter.h" |
| 21 | #include "llvm/MC/MCSection.h" |
| 22 | #include "llvm/MC/MCSectionMachO.h" |
| 23 | #include "llvm/MC/MCSymbol.h" |
| 24 | #include "llvm/MC/MCSymbolMachO.h" |
| 25 | #include "llvm/MC/MCValue.h" |
| 26 | #include "llvm/Support/Alignment.h" |
| 27 | #include "llvm/Support/Casting.h" |
| 28 | #include "llvm/Support/Debug.h" |
| 29 | #include "llvm/Support/ErrorHandling.h" |
| 30 | #include "llvm/Support/MathExtras.h" |
| 31 | #include "llvm/Support/SMLoc.h" |
| 32 | #include "llvm/Support/raw_ostream.h" |
| 33 | #include <algorithm> |
| 34 | #include <cassert> |
| 35 | #include <cstdint> |
| 36 | #include <string> |
| 37 | #include <vector> |
| 38 | |
| 39 | using namespace llvm; |
| 40 | |
| 41 | #define DEBUG_TYPE "mc" |
| 42 | |
| 43 | void MachObjectWriter::reset() { |
| 44 | Relocations.clear(); |
| 45 | IndirectSymBase.clear(); |
| 46 | IndirectSymbols.clear(); |
| 47 | DataRegions.clear(); |
| 48 | SectionDataOffset.clear(); |
| 49 | SectionOrder.clear(); |
| 50 | StringTable.clear(); |
| 51 | LocalSymbolData.clear(); |
| 52 | ExternalSymbolData.clear(); |
| 53 | UndefinedSymbolData.clear(); |
| 54 | LOHContainer.reset(); |
| 55 | VersionInfo.Major = 0; |
| 56 | VersionInfo.SDKVersion = VersionTuple(); |
| 57 | TargetVariantVersionInfo.Major = 0; |
| 58 | TargetVariantVersionInfo.SDKVersion = VersionTuple(); |
| 59 | LinkerOptions.clear(); |
| 60 | MCObjectWriter::reset(); |
| 61 | } |
| 62 | |
| 63 | void MachObjectWriter::setAssembler(MCAssembler *Asm) { |
| 64 | MCObjectWriter::setAssembler(Asm); |
| 65 | TargetObjectWriter->setAssembler(Asm); |
| 66 | } |
| 67 | |
| 68 | bool MachObjectWriter::doesSymbolRequireExternRelocation(const MCSymbol &S) { |
| 69 | // Undefined symbols are always extern. |
| 70 | if (S.isUndefined()) |
| 71 | return true; |
| 72 | |
| 73 | // References to weak definitions require external relocation entries; the |
| 74 | // definition may not always be the one in the same object file. |
| 75 | if (static_cast<const MCSymbolMachO &>(S).isWeakDefinition()) |
| 76 | return true; |
| 77 | |
| 78 | // Otherwise, we can use an internal relocation. |
| 79 | return false; |
| 80 | } |
| 81 | |
| 82 | bool MachObjectWriter:: |
| 83 | MachSymbolData::operator<(const MachSymbolData &RHS) const { |
| 84 | return Symbol->getName() < RHS.Symbol->getName(); |
| 85 | } |
| 86 | |
| 87 | uint64_t |
| 88 | MachObjectWriter::getFragmentAddress(const MCAssembler &Asm, |
| 89 | const MCFragment *Fragment) const { |
| 90 | return getSectionAddress(Sec: Fragment->getParent()) + |
| 91 | Asm.getFragmentOffset(F: *Fragment); |
| 92 | } |
| 93 | |
| 94 | uint64_t MachObjectWriter::getSymbolAddress(const MCSymbol &S) const { |
| 95 | // If this is a variable, then recursively evaluate now. |
| 96 | if (S.isVariable()) { |
| 97 | if (const MCConstantExpr *C = |
| 98 | dyn_cast<const MCConstantExpr>(Val: S.getVariableValue())) |
| 99 | return C->getValue(); |
| 100 | |
| 101 | MCValue Target; |
| 102 | if (!S.getVariableValue()->evaluateAsRelocatable(Res&: Target, Asm)) |
| 103 | report_fatal_error(reason: "unable to evaluate offset for variable '" + |
| 104 | S.getName() + "'" ); |
| 105 | |
| 106 | // Verify that any used symbols are defined. |
| 107 | if (Target.getAddSym() && Target.getAddSym()->isUndefined()) |
| 108 | report_fatal_error(reason: "unable to evaluate offset to undefined symbol '" + |
| 109 | Target.getAddSym()->getName() + "'" ); |
| 110 | if (Target.getSubSym() && Target.getSubSym()->isUndefined()) |
| 111 | report_fatal_error(reason: "unable to evaluate offset to undefined symbol '" + |
| 112 | Target.getSubSym()->getName() + "'" ); |
| 113 | |
| 114 | uint64_t Address = Target.getConstant(); |
| 115 | if (Target.getAddSym()) |
| 116 | Address += getSymbolAddress(S: *Target.getAddSym()); |
| 117 | if (Target.getSubSym()) |
| 118 | Address -= getSymbolAddress(S: *Target.getSubSym()); |
| 119 | return Address; |
| 120 | } |
| 121 | |
| 122 | return getSectionAddress(Sec: S.getFragment()->getParent()) + |
| 123 | Asm->getSymbolOffset(S); |
| 124 | } |
| 125 | |
| 126 | uint64_t MachObjectWriter::getSectionAddress(const MCSection *Sec) const { |
| 127 | // A relocated reference into a DWARF section has to hold an offset into |
| 128 | // that section, so every __DWARF section starts at address 0. |
| 129 | if (getContext().getAsmInfo().doesDwarfUseRelocationsAcrossSections() && |
| 130 | static_cast<const MCSectionMachO *>(Sec)->getSegmentName() == "__DWARF" ) |
| 131 | return 0; |
| 132 | return SectionDataOffset.lookup(Val: Sec); |
| 133 | } |
| 134 | |
| 135 | uint64_t MachObjectWriter::getPaddingSize(const MCAssembler &Asm, |
| 136 | const MCSection *Sec) const { |
| 137 | uint64_t EndOffset = |
| 138 | SectionDataOffset.lookup(Val: Sec) + Asm.getSectionAddressSize(Sec: *Sec); |
| 139 | unsigned Next = |
| 140 | static_cast<const MCSectionMachO *>(Sec)->getLayoutOrder() + 1; |
| 141 | if (Next >= SectionOrder.size()) |
| 142 | return 0; |
| 143 | |
| 144 | const MCSection &NextSec = *SectionOrder[Next]; |
| 145 | if (NextSec.isBssSection()) |
| 146 | return 0; |
| 147 | return offsetToAlignment(Value: EndOffset, Alignment: NextSec.getAlign()); |
| 148 | } |
| 149 | |
| 150 | static bool isSymbolLinkerVisible(const MCSymbol &Symbol) { |
| 151 | // Non-temporary labels should always be visible to the linker. |
| 152 | if (!Symbol.isTemporary()) |
| 153 | return true; |
| 154 | |
| 155 | if (Symbol.isUsedInReloc()) |
| 156 | return true; |
| 157 | |
| 158 | return false; |
| 159 | } |
| 160 | |
| 161 | const MCSymbol *MachObjectWriter::getAtom(const MCSymbol &S) const { |
| 162 | // Linker visible symbols define atoms. |
| 163 | if (isSymbolLinkerVisible(Symbol: S)) |
| 164 | return &S; |
| 165 | |
| 166 | // Absolute and undefined symbols have no defining atom. |
| 167 | if (!S.isInSection()) |
| 168 | return nullptr; |
| 169 | |
| 170 | // Non-linker visible symbols in sections which can't be atomized have no |
| 171 | // defining atom. |
| 172 | if (!MCAsmInfoDarwin::isSectionAtomizableBySymbols( |
| 173 | Section: *S.getFragment()->getParent())) |
| 174 | return nullptr; |
| 175 | |
| 176 | // Otherwise, return the atom for the containing fragment. |
| 177 | return S.getFragment()->getAtom(); |
| 178 | } |
| 179 | |
| 180 | void MachObjectWriter::(MachO::HeaderFileType Type, |
| 181 | unsigned NumLoadCommands, |
| 182 | unsigned LoadCommandsSize, |
| 183 | bool SubsectionsViaSymbols) { |
| 184 | uint32_t Flags = 0; |
| 185 | |
| 186 | if (SubsectionsViaSymbols) |
| 187 | Flags |= MachO::MH_SUBSECTIONS_VIA_SYMBOLS; |
| 188 | |
| 189 | // struct mach_header (28 bytes) or |
| 190 | // struct mach_header_64 (32 bytes) |
| 191 | |
| 192 | uint64_t Start = W.OS.tell(); |
| 193 | (void) Start; |
| 194 | |
| 195 | W.write<uint32_t>(Val: is64Bit() ? MachO::MH_MAGIC_64 : MachO::MH_MAGIC); |
| 196 | |
| 197 | W.write<uint32_t>(Val: TargetObjectWriter->getCPUType()); |
| 198 | |
| 199 | uint32_t Cpusubtype = TargetObjectWriter->getCPUSubtype(); |
| 200 | |
| 201 | // Promote arm64e subtypes to always be ptrauth-ABI-versioned, at version 0. |
| 202 | // We never need to emit unversioned binaries. |
| 203 | // And we don't support arbitrary ABI versions (or the kernel flag) yet. |
| 204 | if (TargetObjectWriter->getCPUType() == MachO::CPU_TYPE_ARM64 && |
| 205 | Cpusubtype == MachO::CPU_SUBTYPE_ARM64E) |
| 206 | Cpusubtype = MachO::CPU_SUBTYPE_ARM64E_WITH_PTRAUTH_VERSION( |
| 207 | /*PtrAuthABIVersion=*/0, /*PtrAuthKernelABIVersion=*/false); |
| 208 | |
| 209 | W.write<uint32_t>(Val: Cpusubtype); |
| 210 | |
| 211 | W.write<uint32_t>(Val: Type); |
| 212 | W.write<uint32_t>(Val: NumLoadCommands); |
| 213 | W.write<uint32_t>(Val: LoadCommandsSize); |
| 214 | W.write<uint32_t>(Val: Flags); |
| 215 | if (is64Bit()) |
| 216 | W.write<uint32_t>(Val: 0); // reserved |
| 217 | |
| 218 | assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64) |
| 219 | : sizeof(MachO::mach_header))); |
| 220 | } |
| 221 | |
| 222 | void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) { |
| 223 | assert(Size >= Str.size()); |
| 224 | W.OS << Str; |
| 225 | W.OS.write_zeros(NumZeros: Size - Str.size()); |
| 226 | } |
| 227 | |
| 228 | /// writeSegmentLoadCommand - Write a segment load command. |
| 229 | /// |
| 230 | /// \param NumSections The number of sections in this segment. |
| 231 | /// \param SectionDataSize The total size of the sections. |
| 232 | void MachObjectWriter::writeSegmentLoadCommand( |
| 233 | StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize, |
| 234 | uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt, |
| 235 | uint32_t InitProt) { |
| 236 | // struct segment_command (56 bytes) or |
| 237 | // struct segment_command_64 (72 bytes) |
| 238 | |
| 239 | uint64_t Start = W.OS.tell(); |
| 240 | (void) Start; |
| 241 | |
| 242 | unsigned SegmentLoadCommandSize = |
| 243 | is64Bit() ? sizeof(MachO::segment_command_64): |
| 244 | sizeof(MachO::segment_command); |
| 245 | W.write<uint32_t>(Val: is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT); |
| 246 | W.write<uint32_t>(Val: SegmentLoadCommandSize + |
| 247 | NumSections * (is64Bit() ? sizeof(MachO::section_64) : |
| 248 | sizeof(MachO::section))); |
| 249 | |
| 250 | writeWithPadding(Str: Name, Size: 16); |
| 251 | if (is64Bit()) { |
| 252 | W.write<uint64_t>(Val: VMAddr); // vmaddr |
| 253 | W.write<uint64_t>(Val: VMSize); // vmsize |
| 254 | W.write<uint64_t>(Val: SectionDataStartOffset); // file offset |
| 255 | W.write<uint64_t>(Val: SectionDataSize); // file size |
| 256 | } else { |
| 257 | W.write<uint32_t>(Val: VMAddr); // vmaddr |
| 258 | W.write<uint32_t>(Val: VMSize); // vmsize |
| 259 | W.write<uint32_t>(Val: SectionDataStartOffset); // file offset |
| 260 | W.write<uint32_t>(Val: SectionDataSize); // file size |
| 261 | } |
| 262 | // maxprot |
| 263 | W.write<uint32_t>(Val: MaxProt); |
| 264 | // initprot |
| 265 | W.write<uint32_t>(Val: InitProt); |
| 266 | W.write<uint32_t>(Val: NumSections); |
| 267 | W.write<uint32_t>(Val: 0); // flags |
| 268 | |
| 269 | assert(W.OS.tell() - Start == SegmentLoadCommandSize); |
| 270 | } |
| 271 | |
| 272 | void MachObjectWriter::writeSection(const MCAssembler &Asm, |
| 273 | const MCSectionMachO &Sec, uint64_t VMAddr, |
| 274 | uint64_t FileOffset, unsigned Flags, |
| 275 | uint64_t RelocationsStart, |
| 276 | unsigned NumRelocations) { |
| 277 | // The offset is unused for virtual sections. |
| 278 | if (Sec.isBssSection()) { |
| 279 | assert(Asm.getSectionFileSize(Sec) == 0 && "Invalid file size!" ); |
| 280 | FileOffset = 0; |
| 281 | } |
| 282 | |
| 283 | // struct section (68 bytes) or |
| 284 | // struct section_64 (80 bytes) |
| 285 | |
| 286 | uint64_t SectionSize = Asm.getSectionAddressSize(Sec); |
| 287 | uint64_t Start = W.OS.tell(); |
| 288 | (void) Start; |
| 289 | writeWithPadding(Str: Sec.getName(), Size: 16); |
| 290 | writeWithPadding(Str: Sec.getSegmentName(), Size: 16); |
| 291 | if (is64Bit()) { |
| 292 | W.write<uint64_t>(Val: VMAddr); // address |
| 293 | W.write<uint64_t>(Val: SectionSize); // size |
| 294 | } else { |
| 295 | W.write<uint32_t>(Val: VMAddr); // address |
| 296 | W.write<uint32_t>(Val: SectionSize); // size |
| 297 | } |
| 298 | assert(isUInt<32>(FileOffset) && "Cannot encode offset of section" ); |
| 299 | W.write<uint32_t>(Val: FileOffset); |
| 300 | |
| 301 | W.write<uint32_t>(Val: Log2(A: Sec.getAlign())); |
| 302 | assert((!NumRelocations || isUInt<32>(RelocationsStart)) && |
| 303 | "Cannot encode offset of relocations" ); |
| 304 | W.write<uint32_t>(Val: NumRelocations ? RelocationsStart : 0); |
| 305 | W.write<uint32_t>(Val: NumRelocations); |
| 306 | W.write<uint32_t>(Val: Flags); |
| 307 | W.write<uint32_t>(Val: IndirectSymBase.lookup(Val: &Sec)); // reserved1 |
| 308 | W.write<uint32_t>(Val: Sec.getStubSize()); // reserved2 |
| 309 | if (is64Bit()) |
| 310 | W.write<uint32_t>(Val: 0); // reserved3 |
| 311 | |
| 312 | assert(W.OS.tell() - Start == |
| 313 | (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section))); |
| 314 | } |
| 315 | |
| 316 | void MachObjectWriter::writeSymtabLoadCommand(uint32_t SymbolOffset, |
| 317 | uint32_t NumSymbols, |
| 318 | uint32_t StringTableOffset, |
| 319 | uint32_t StringTableSize) { |
| 320 | // struct symtab_command (24 bytes) |
| 321 | |
| 322 | uint64_t Start = W.OS.tell(); |
| 323 | (void) Start; |
| 324 | |
| 325 | W.write<uint32_t>(Val: MachO::LC_SYMTAB); |
| 326 | W.write<uint32_t>(Val: sizeof(MachO::symtab_command)); |
| 327 | W.write<uint32_t>(Val: SymbolOffset); |
| 328 | W.write<uint32_t>(Val: NumSymbols); |
| 329 | W.write<uint32_t>(Val: StringTableOffset); |
| 330 | W.write<uint32_t>(Val: StringTableSize); |
| 331 | |
| 332 | assert(W.OS.tell() - Start == sizeof(MachO::symtab_command)); |
| 333 | } |
| 334 | |
| 335 | void MachObjectWriter::writeDysymtabLoadCommand(uint32_t FirstLocalSymbol, |
| 336 | uint32_t NumLocalSymbols, |
| 337 | uint32_t FirstExternalSymbol, |
| 338 | uint32_t NumExternalSymbols, |
| 339 | uint32_t FirstUndefinedSymbol, |
| 340 | uint32_t NumUndefinedSymbols, |
| 341 | uint32_t IndirectSymbolOffset, |
| 342 | uint32_t NumIndirectSymbols) { |
| 343 | // struct dysymtab_command (80 bytes) |
| 344 | |
| 345 | uint64_t Start = W.OS.tell(); |
| 346 | (void) Start; |
| 347 | |
| 348 | W.write<uint32_t>(Val: MachO::LC_DYSYMTAB); |
| 349 | W.write<uint32_t>(Val: sizeof(MachO::dysymtab_command)); |
| 350 | W.write<uint32_t>(Val: FirstLocalSymbol); |
| 351 | W.write<uint32_t>(Val: NumLocalSymbols); |
| 352 | W.write<uint32_t>(Val: FirstExternalSymbol); |
| 353 | W.write<uint32_t>(Val: NumExternalSymbols); |
| 354 | W.write<uint32_t>(Val: FirstUndefinedSymbol); |
| 355 | W.write<uint32_t>(Val: NumUndefinedSymbols); |
| 356 | W.write<uint32_t>(Val: 0); // tocoff |
| 357 | W.write<uint32_t>(Val: 0); // ntoc |
| 358 | W.write<uint32_t>(Val: 0); // modtaboff |
| 359 | W.write<uint32_t>(Val: 0); // nmodtab |
| 360 | W.write<uint32_t>(Val: 0); // extrefsymoff |
| 361 | W.write<uint32_t>(Val: 0); // nextrefsyms |
| 362 | W.write<uint32_t>(Val: IndirectSymbolOffset); |
| 363 | W.write<uint32_t>(Val: NumIndirectSymbols); |
| 364 | W.write<uint32_t>(Val: 0); // extreloff |
| 365 | W.write<uint32_t>(Val: 0); // nextrel |
| 366 | W.write<uint32_t>(Val: 0); // locreloff |
| 367 | W.write<uint32_t>(Val: 0); // nlocrel |
| 368 | |
| 369 | assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command)); |
| 370 | } |
| 371 | |
| 372 | MachObjectWriter::MachSymbolData * |
| 373 | MachObjectWriter::findSymbolData(const MCSymbol &Sym) { |
| 374 | for (auto *SymbolData : |
| 375 | {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) |
| 376 | for (MachSymbolData &Entry : *SymbolData) |
| 377 | if (Entry.Symbol == &Sym) |
| 378 | return &Entry; |
| 379 | |
| 380 | return nullptr; |
| 381 | } |
| 382 | |
| 383 | const MCSymbol &MachObjectWriter::findAliasedSymbol(const MCSymbol &Sym) const { |
| 384 | const MCSymbol *S = &Sym; |
| 385 | while (S->isVariable()) { |
| 386 | const MCExpr *Value = S->getVariableValue(); |
| 387 | const auto *Ref = dyn_cast<MCSymbolRefExpr>(Val: Value); |
| 388 | if (!Ref) |
| 389 | return *S; |
| 390 | S = &Ref->getSymbol(); |
| 391 | } |
| 392 | return *S; |
| 393 | } |
| 394 | |
| 395 | void MachObjectWriter::writeNlist(MachSymbolData &MSD, const MCAssembler &Asm) { |
| 396 | auto *Symbol = MSD.Symbol; |
| 397 | const auto &Data = static_cast<const MCSymbolMachO &>(*Symbol); |
| 398 | auto *AliasedSymbol = |
| 399 | static_cast<const MCSymbolMachO *>(&findAliasedSymbol(Sym: *Symbol)); |
| 400 | uint8_t SectionIndex = MSD.SectionIndex; |
| 401 | uint8_t Type = 0; |
| 402 | uint64_t Address = 0; |
| 403 | bool IsAlias = Symbol != AliasedSymbol; |
| 404 | |
| 405 | const MCSymbolMachO &OrigSymbol = *Symbol; |
| 406 | MachSymbolData *AliaseeInfo; |
| 407 | if (IsAlias) { |
| 408 | AliaseeInfo = findSymbolData(Sym: *AliasedSymbol); |
| 409 | if (AliaseeInfo) |
| 410 | SectionIndex = AliaseeInfo->SectionIndex; |
| 411 | Symbol = AliasedSymbol; |
| 412 | // FIXME: Should this update Data as well? |
| 413 | } |
| 414 | |
| 415 | // Set the N_TYPE bits. See <mach-o/nlist.h>. |
| 416 | // |
| 417 | // FIXME: Are the prebound or indirect fields possible here? |
| 418 | if (IsAlias && Symbol->isUndefined()) |
| 419 | Type = MachO::N_INDR; |
| 420 | else if (Symbol->isUndefined()) |
| 421 | Type = MachO::N_UNDF; |
| 422 | else if (Symbol->isAbsolute()) |
| 423 | Type = MachO::N_ABS; |
| 424 | else |
| 425 | Type = MachO::N_SECT; |
| 426 | |
| 427 | // FIXME: Set STAB bits. |
| 428 | |
| 429 | if (Data.isPrivateExtern()) |
| 430 | Type |= MachO::N_PEXT; |
| 431 | |
| 432 | // Set external bit. |
| 433 | if (Data.isExternal() || (!IsAlias && Symbol->isUndefined())) |
| 434 | Type |= MachO::N_EXT; |
| 435 | |
| 436 | // Compute the symbol address. |
| 437 | if (IsAlias && Symbol->isUndefined()) |
| 438 | Address = AliaseeInfo->StringIndex; |
| 439 | else if (Symbol->isDefined()) |
| 440 | Address = getSymbolAddress(S: OrigSymbol); |
| 441 | else if (Symbol->isCommon()) { |
| 442 | // Common symbols are encoded with the size in the address |
| 443 | // field, and their alignment in the flags. |
| 444 | Address = Symbol->getCommonSize(); |
| 445 | } |
| 446 | |
| 447 | // struct nlist (12 bytes) |
| 448 | |
| 449 | W.write<uint32_t>(Val: MSD.StringIndex); |
| 450 | W.OS << char(Type); |
| 451 | W.OS << char(SectionIndex); |
| 452 | |
| 453 | // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc' |
| 454 | // value. |
| 455 | bool EncodeAsAltEntry = IsAlias && OrigSymbol.isAltEntry(); |
| 456 | W.write<uint16_t>(Val: Symbol->getEncodedFlags(EncodeAsAltEntry)); |
| 457 | if (is64Bit()) |
| 458 | W.write<uint64_t>(Val: Address); |
| 459 | else |
| 460 | W.write<uint32_t>(Val: Address); |
| 461 | } |
| 462 | |
| 463 | void MachObjectWriter::writeLinkeditLoadCommand(uint32_t Type, |
| 464 | uint32_t DataOffset, |
| 465 | uint32_t DataSize) { |
| 466 | uint64_t Start = W.OS.tell(); |
| 467 | (void) Start; |
| 468 | |
| 469 | W.write<uint32_t>(Val: Type); |
| 470 | W.write<uint32_t>(Val: sizeof(MachO::linkedit_data_command)); |
| 471 | W.write<uint32_t>(Val: DataOffset); |
| 472 | W.write<uint32_t>(Val: DataSize); |
| 473 | |
| 474 | assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command)); |
| 475 | } |
| 476 | |
| 477 | static unsigned ComputeLinkerOptionsLoadCommandSize( |
| 478 | const std::vector<std::string> &Options, bool is64Bit) |
| 479 | { |
| 480 | unsigned Size = sizeof(MachO::linker_option_command); |
| 481 | for (const std::string &Option : Options) |
| 482 | Size += Option.size() + 1; |
| 483 | return alignTo(Value: Size, Align: is64Bit ? 8 : 4); |
| 484 | } |
| 485 | |
| 486 | void MachObjectWriter::writeLinkerOptionsLoadCommand( |
| 487 | const std::vector<std::string> &Options) |
| 488 | { |
| 489 | unsigned Size = ComputeLinkerOptionsLoadCommandSize(Options, is64Bit: is64Bit()); |
| 490 | uint64_t Start = W.OS.tell(); |
| 491 | (void) Start; |
| 492 | |
| 493 | W.write<uint32_t>(Val: MachO::LC_LINKER_OPTION); |
| 494 | W.write<uint32_t>(Val: Size); |
| 495 | W.write<uint32_t>(Val: Options.size()); |
| 496 | uint64_t BytesWritten = sizeof(MachO::linker_option_command); |
| 497 | for (const std::string &Option : Options) { |
| 498 | // Write each string, including the null byte. |
| 499 | W.OS << Option << '\0'; |
| 500 | BytesWritten += Option.size() + 1; |
| 501 | } |
| 502 | |
| 503 | // Pad to a multiple of the pointer size. |
| 504 | W.OS.write_zeros( |
| 505 | NumZeros: offsetToAlignment(Value: BytesWritten, Alignment: is64Bit() ? Align(8) : Align(4))); |
| 506 | |
| 507 | assert(W.OS.tell() - Start == Size); |
| 508 | } |
| 509 | |
| 510 | static bool isFixupTargetValid(const MCValue &Target) { |
| 511 | // Target is (LHS - RHS + cst). |
| 512 | // We don't support the form where LHS is null: -RHS + cst |
| 513 | if (!Target.getAddSym() && Target.getSubSym()) |
| 514 | return false; |
| 515 | return true; |
| 516 | } |
| 517 | |
| 518 | void MachObjectWriter::recordRelocation(const MCFragment &F, |
| 519 | const MCFixup &Fixup, MCValue Target, |
| 520 | uint64_t &FixedValue) { |
| 521 | if (!isFixupTargetValid(Target)) { |
| 522 | getContext().reportError(L: Fixup.getLoc(), |
| 523 | Msg: "unsupported relocation expression" ); |
| 524 | return; |
| 525 | } |
| 526 | |
| 527 | TargetObjectWriter->recordRelocation(Writer: this, Asm&: *Asm, Fragment: &F, Fixup, Target, |
| 528 | FixedValue); |
| 529 | } |
| 530 | |
| 531 | void MachObjectWriter::bindIndirectSymbols(MCAssembler &Asm) { |
| 532 | // This is the point where 'as' creates actual symbols for indirect symbols |
| 533 | // (in the following two passes). It would be easier for us to do this sooner |
| 534 | // when we see the attribute, but that makes getting the order in the symbol |
| 535 | // table much more complicated than it is worth. |
| 536 | // |
| 537 | // FIXME: Revisit this when the dust settles. |
| 538 | |
| 539 | // Report errors for use of .indirect_symbol not in a symbol pointer section |
| 540 | // or stub section. |
| 541 | for (IndirectSymbolData &ISD : IndirectSymbols) { |
| 542 | const MCSectionMachO &Section = static_cast<MCSectionMachO &>(*ISD.Section); |
| 543 | |
| 544 | if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS && |
| 545 | Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS && |
| 546 | Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS && |
| 547 | Section.getType() != MachO::S_SYMBOL_STUBS) { |
| 548 | MCSymbol &Symbol = *ISD.Symbol; |
| 549 | report_fatal_error(reason: "indirect symbol '" + Symbol.getName() + |
| 550 | "' not in a symbol pointer or stub section" ); |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | // Bind non-lazy symbol pointers first. |
| 555 | for (auto [IndirectIndex, ISD] : enumerate(First&: IndirectSymbols)) { |
| 556 | const auto &Section = static_cast<MCSectionMachO &>(*ISD.Section); |
| 557 | |
| 558 | if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS && |
| 559 | Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) |
| 560 | continue; |
| 561 | |
| 562 | // Initialize the section indirect symbol base, if necessary. |
| 563 | IndirectSymBase.insert(KV: std::make_pair(x&: ISD.Section, y&: IndirectIndex)); |
| 564 | |
| 565 | Asm.registerSymbol(Symbol: *ISD.Symbol); |
| 566 | } |
| 567 | |
| 568 | // Then lazy symbol pointers and symbol stubs. |
| 569 | for (auto [IndirectIndex, ISD] : enumerate(First&: IndirectSymbols)) { |
| 570 | const auto &Section = static_cast<MCSectionMachO &>(*ISD.Section); |
| 571 | |
| 572 | if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS && |
| 573 | Section.getType() != MachO::S_SYMBOL_STUBS) |
| 574 | continue; |
| 575 | |
| 576 | // Initialize the section indirect symbol base, if necessary. |
| 577 | IndirectSymBase.insert(KV: std::make_pair(x&: ISD.Section, y&: IndirectIndex)); |
| 578 | |
| 579 | // Set the symbol type to undefined lazy, but only on construction. |
| 580 | // |
| 581 | // FIXME: Do not hardcode. |
| 582 | if (Asm.registerSymbol(Symbol: *ISD.Symbol)) |
| 583 | ISD.Symbol->setReferenceTypeUndefinedLazy(true); |
| 584 | } |
| 585 | } |
| 586 | |
| 587 | /// computeSymbolTable - Compute the symbol table data |
| 588 | void MachObjectWriter::computeSymbolTable( |
| 589 | MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData, |
| 590 | std::vector<MachSymbolData> &ExternalSymbolData, |
| 591 | std::vector<MachSymbolData> &UndefinedSymbolData) { |
| 592 | // Build section lookup table. |
| 593 | DenseMap<const MCSection*, uint8_t> SectionIndexMap; |
| 594 | unsigned Index = 1; |
| 595 | for (MCSection &Sec : Asm) |
| 596 | SectionIndexMap[&Sec] = Index++; |
| 597 | |
| 598 | // Section indices begin from 1 in MachO. Only sections 1-255 can be indexed |
| 599 | // into section symbols. Referencing a section with index larger than 255 will |
| 600 | // not set n_sect for these symbols. |
| 601 | if (Index > 255) |
| 602 | getContext().reportError(L: SMLoc(), Msg: "Too many sections!" ); |
| 603 | |
| 604 | // Build the string table. |
| 605 | for (const MCSymbol &Symbol : Asm.symbols()) { |
| 606 | if (!static_cast<const MCSymbolMachO &>(Symbol).isSymbolLinkerVisible()) |
| 607 | continue; |
| 608 | |
| 609 | StringTable.add(S: Symbol.getName()); |
| 610 | } |
| 611 | StringTable.finalize(); |
| 612 | |
| 613 | // Build the symbol arrays but only for non-local symbols. |
| 614 | // |
| 615 | // The particular order that we collect and then sort the symbols is chosen to |
| 616 | // match 'as'. Even though it doesn't matter for correctness, this is |
| 617 | // important for letting us diff .o files. |
| 618 | for (const MCSymbol &Symbol : Asm.symbols()) { |
| 619 | auto &Sym = static_cast<const MCSymbolMachO &>(Symbol); |
| 620 | // Ignore non-linker visible symbols. |
| 621 | if (!Sym.isSymbolLinkerVisible()) |
| 622 | continue; |
| 623 | |
| 624 | if (!Sym.isExternal() && !Sym.isUndefined()) |
| 625 | continue; |
| 626 | |
| 627 | MachSymbolData MSD; |
| 628 | MSD.Symbol = &Sym; |
| 629 | MSD.StringIndex = StringTable.getOffset(S: Symbol.getName()); |
| 630 | |
| 631 | if (Symbol.isUndefined()) { |
| 632 | MSD.SectionIndex = 0; |
| 633 | UndefinedSymbolData.push_back(x: MSD); |
| 634 | } else if (Symbol.isAbsolute()) { |
| 635 | MSD.SectionIndex = 0; |
| 636 | ExternalSymbolData.push_back(x: MSD); |
| 637 | } else { |
| 638 | MSD.SectionIndex = SectionIndexMap.lookup(Val: &Symbol.getSection()); |
| 639 | if (!MSD.SectionIndex) |
| 640 | getContext().reportError(L: SMLoc(), Msg: "Invalid section index!" ); |
| 641 | ExternalSymbolData.push_back(x: MSD); |
| 642 | } |
| 643 | } |
| 644 | |
| 645 | // Now add the data for local symbols. |
| 646 | for (const MCSymbol &Symbol : Asm.symbols()) { |
| 647 | auto &Sym = static_cast<const MCSymbolMachO &>(Symbol); |
| 648 | // Ignore non-linker visible symbols. |
| 649 | if (!Sym.isSymbolLinkerVisible()) |
| 650 | continue; |
| 651 | |
| 652 | if (Sym.isExternal() || Sym.isUndefined()) |
| 653 | continue; |
| 654 | |
| 655 | MachSymbolData MSD; |
| 656 | MSD.Symbol = &Sym; |
| 657 | MSD.StringIndex = StringTable.getOffset(S: Symbol.getName()); |
| 658 | |
| 659 | if (Symbol.isAbsolute()) { |
| 660 | MSD.SectionIndex = 0; |
| 661 | LocalSymbolData.push_back(x: MSD); |
| 662 | } else { |
| 663 | MSD.SectionIndex = SectionIndexMap.lookup(Val: &Symbol.getSection()); |
| 664 | if (!MSD.SectionIndex) |
| 665 | getContext().reportError(L: SMLoc(), Msg: "Invalid section index!" ); |
| 666 | LocalSymbolData.push_back(x: MSD); |
| 667 | } |
| 668 | } |
| 669 | |
| 670 | // External and undefined symbols are required to be in lexicographic order. |
| 671 | llvm::sort(C&: ExternalSymbolData); |
| 672 | llvm::sort(C&: UndefinedSymbolData); |
| 673 | |
| 674 | // Set the symbol indices. |
| 675 | Index = 0; |
| 676 | for (auto *SymbolData : |
| 677 | {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) |
| 678 | for (MachSymbolData &Entry : *SymbolData) |
| 679 | Entry.Symbol->setIndex(Index++); |
| 680 | |
| 681 | for (const MCSection &Section : Asm) { |
| 682 | for (RelAndSymbol &Rel : Relocations[&Section]) { |
| 683 | if (!Rel.Sym) |
| 684 | continue; |
| 685 | |
| 686 | // Set the Index and the IsExtern bit. |
| 687 | unsigned Index = Rel.Sym->getIndex(); |
| 688 | assert(isInt<24>(Index)); |
| 689 | if (W.Endian == llvm::endianness::little) |
| 690 | Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27); |
| 691 | else |
| 692 | Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4); |
| 693 | } |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | void MachObjectWriter::computeSectionAddresses(const MCAssembler &Asm) { |
| 698 | // Assign layout order indices to sections. |
| 699 | unsigned i = 0; |
| 700 | // Compute the section layout order. Virtual sections must go last. |
| 701 | for (MCSection &Sec : Asm) { |
| 702 | if (!Sec.isBssSection()) { |
| 703 | SectionOrder.push_back(Elt: &Sec); |
| 704 | static_cast<MCSectionMachO &>(Sec).setLayoutOrder(i++); |
| 705 | } |
| 706 | } |
| 707 | for (MCSection &Sec : Asm) { |
| 708 | if (Sec.isBssSection()) { |
| 709 | SectionOrder.push_back(Elt: &Sec); |
| 710 | static_cast<MCSectionMachO &>(Sec).setLayoutOrder(i++); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | uint64_t StartOffset = 0; |
| 715 | for (const MCSection *Sec : SectionOrder) { |
| 716 | StartOffset = alignTo(Size: StartOffset, A: Sec->getAlign()); |
| 717 | SectionDataOffset[Sec] = StartOffset; |
| 718 | StartOffset += Asm.getSectionAddressSize(Sec: *Sec); |
| 719 | |
| 720 | // Explicitly pad the section to match the alignment requirements of the |
| 721 | // following one. This is for 'gas' compatibility, it shouldn't |
| 722 | /// strictly be necessary. |
| 723 | StartOffset += getPaddingSize(Asm, Sec); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | void MachObjectWriter::executePostLayoutBinding() { |
| 728 | computeSectionAddresses(Asm: *Asm); |
| 729 | |
| 730 | // Create symbol data for any indirect symbols. |
| 731 | bindIndirectSymbols(Asm&: *Asm); |
| 732 | } |
| 733 | |
| 734 | bool MachObjectWriter::isSymbolRefDifferenceFullyResolvedImpl( |
| 735 | const MCSymbol &SymA, const MCFragment &FB, bool InSet, |
| 736 | bool IsPCRel) const { |
| 737 | if (InSet) |
| 738 | return true; |
| 739 | |
| 740 | // The effective address is |
| 741 | // addr(atom(A)) + offset(A) |
| 742 | // - addr(atom(B)) - offset(B) |
| 743 | // and the offsets are not relocatable, so the fixup is fully resolved when |
| 744 | // addr(atom(A)) - addr(atom(B)) == 0. |
| 745 | const MCSymbol &SA = findAliasedSymbol(Sym: SymA); |
| 746 | const MCSection &SecA = SA.getSection(); |
| 747 | const MCSection &SecB = *FB.getParent(); |
| 748 | |
| 749 | if (IsPCRel) { |
| 750 | // The simple (Darwin, except on x86_64) way of dealing with this was to |
| 751 | // assume that any reference to a temporary symbol *must* be a temporary |
| 752 | // symbol in the same atom, unless the sections differ. Therefore, any PCrel |
| 753 | // relocation to a temporary symbol (in the same section) is fully |
| 754 | // resolved. This also works in conjunction with absolutized .set, which |
| 755 | // requires the compiler to use .set to absolutize the differences between |
| 756 | // symbols which the compiler knows to be assembly time constants, so we |
| 757 | // don't need to worry about considering symbol differences fully resolved. |
| 758 | // |
| 759 | // If the file isn't using sub-sections-via-symbols, we can make the |
| 760 | // same assumptions about any symbol that we normally make about |
| 761 | // assembler locals. |
| 762 | |
| 763 | bool hasReliableSymbolDifference = isX86_64(); |
| 764 | if (!hasReliableSymbolDifference) { |
| 765 | if (!SA.isInSection() || &SecA != &SecB || |
| 766 | (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() && |
| 767 | SubsectionsViaSymbols)) |
| 768 | return false; |
| 769 | return true; |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | // If they are not in the same section, we can't compute the diff. |
| 774 | if (&SecA != &SecB) |
| 775 | return false; |
| 776 | |
| 777 | // If the atoms are the same, they are guaranteed to have the same address. |
| 778 | return SA.getFragment()->getAtom() == FB.getAtom(); |
| 779 | } |
| 780 | |
| 781 | static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type) { |
| 782 | switch (Type) { |
| 783 | case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX; |
| 784 | case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS; |
| 785 | case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS; |
| 786 | case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS; |
| 787 | } |
| 788 | llvm_unreachable("Invalid mc version min type" ); |
| 789 | } |
| 790 | |
| 791 | void MachObjectWriter::populateAddrSigSection(MCAssembler &Asm) { |
| 792 | MCSection *AddrSigSection = |
| 793 | getContext().getObjectFileInfo()->getAddrSigSection(); |
| 794 | unsigned Log2Size = is64Bit() ? 3 : 2; |
| 795 | for (const MCSymbol *S : getAddrsigSyms()) { |
| 796 | if (!S->isRegistered()) |
| 797 | continue; |
| 798 | MachO::any_relocation_info MRE; |
| 799 | MRE.r_word0 = 0; |
| 800 | MRE.r_word1 = (Log2Size << 25) | (MachO::GENERIC_RELOC_VANILLA << 28); |
| 801 | addRelocation(RelSymbol: S, Sec: AddrSigSection, MRE); |
| 802 | } |
| 803 | } |
| 804 | |
| 805 | uint64_t MachObjectWriter::writeObject() { |
| 806 | auto &Asm = *this->Asm; |
| 807 | uint64_t StartOffset = W.OS.tell(); |
| 808 | auto NumBytesWritten = [&] { return W.OS.tell() - StartOffset; }; |
| 809 | |
| 810 | populateAddrSigSection(Asm); |
| 811 | |
| 812 | // Compute symbol table information and bind symbol indices. |
| 813 | computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData, |
| 814 | UndefinedSymbolData); |
| 815 | |
| 816 | if (!CGProfile.empty()) { |
| 817 | SmallString<0> Content; |
| 818 | raw_svector_ostream OS(Content); |
| 819 | for (const MCObjectWriter::CGProfileEntry &CGPE : CGProfile) { |
| 820 | uint32_t FromIndex = CGPE.From->getSymbol().getIndex(); |
| 821 | uint32_t ToIndex = CGPE.To->getSymbol().getIndex(); |
| 822 | support::endian::write(os&: OS, value: FromIndex, endian: W.Endian); |
| 823 | support::endian::write(os&: OS, value: ToIndex, endian: W.Endian); |
| 824 | support::endian::write(os&: OS, value: CGPE.Count, endian: W.Endian); |
| 825 | } |
| 826 | MCSection *Sec = getContext().getMachOSection(Segment: "__LLVM" , Section: "__cg_profile" , TypeAndAttributes: 0, |
| 827 | K: SectionKind::getMetadata()); |
| 828 | llvm::copy(Range: OS.str(), Out: Sec->curFragList()->Head->getVarContents().data()); |
| 829 | } |
| 830 | |
| 831 | unsigned NumSections = Asm.end() - Asm.begin(); |
| 832 | |
| 833 | // The section data starts after the header, the segment load command (and |
| 834 | // section headers) and the symbol table. |
| 835 | unsigned NumLoadCommands = 1; |
| 836 | uint64_t LoadCommandsSize = is64Bit() ? |
| 837 | sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64): |
| 838 | sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section); |
| 839 | |
| 840 | // Add the deployment target version info load command size, if used. |
| 841 | if (VersionInfo.Major != 0) { |
| 842 | ++NumLoadCommands; |
| 843 | if (VersionInfo.EmitBuildVersion) |
| 844 | LoadCommandsSize += sizeof(MachO::build_version_command); |
| 845 | else |
| 846 | LoadCommandsSize += sizeof(MachO::version_min_command); |
| 847 | } |
| 848 | |
| 849 | // Add the target variant version info load command size, if used. |
| 850 | if (TargetVariantVersionInfo.Major != 0) { |
| 851 | ++NumLoadCommands; |
| 852 | assert(TargetVariantVersionInfo.EmitBuildVersion && |
| 853 | "target variant should use build version" ); |
| 854 | LoadCommandsSize += sizeof(MachO::build_version_command); |
| 855 | } |
| 856 | |
| 857 | // Add the target triple load command size, if used. |
| 858 | uint32_t TargetTripleCommandSize = 0; |
| 859 | if (TargetTriple) { |
| 860 | ++NumLoadCommands; |
| 861 | // The full command is the command struct plus the NUL terminated triple |
| 862 | // string, all padded to align. |
| 863 | TargetTripleCommandSize = |
| 864 | alignTo(Value: sizeof(MachO::target_triple_command) + TargetTriple->size() + 1, |
| 865 | Align: is64Bit() ? 8 : 4); |
| 866 | LoadCommandsSize += TargetTripleCommandSize; |
| 867 | } |
| 868 | |
| 869 | // Add the data-in-code load command size, if used. |
| 870 | unsigned NumDataRegions = DataRegions.size(); |
| 871 | if (NumDataRegions) { |
| 872 | ++NumLoadCommands; |
| 873 | LoadCommandsSize += sizeof(MachO::linkedit_data_command); |
| 874 | } |
| 875 | |
| 876 | // Add the loh load command size, if used. |
| 877 | uint64_t LOHRawSize = LOHContainer.getEmitSize(Asm, ObjWriter: *this); |
| 878 | uint64_t LOHSize = alignTo(Value: LOHRawSize, Align: is64Bit() ? 8 : 4); |
| 879 | if (LOHSize) { |
| 880 | ++NumLoadCommands; |
| 881 | LoadCommandsSize += sizeof(MachO::linkedit_data_command); |
| 882 | } |
| 883 | |
| 884 | // Add the symbol table load command sizes, if used. |
| 885 | unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() + |
| 886 | UndefinedSymbolData.size(); |
| 887 | if (NumSymbols) { |
| 888 | NumLoadCommands += 2; |
| 889 | LoadCommandsSize += (sizeof(MachO::symtab_command) + |
| 890 | sizeof(MachO::dysymtab_command)); |
| 891 | } |
| 892 | |
| 893 | // Add the linker option load commands sizes. |
| 894 | for (const auto &Option : LinkerOptions) { |
| 895 | ++NumLoadCommands; |
| 896 | LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Options: Option, is64Bit: is64Bit()); |
| 897 | } |
| 898 | |
| 899 | // Compute the total size of the section data, as well as its file size and vm |
| 900 | // size. |
| 901 | uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) : |
| 902 | sizeof(MachO::mach_header)) + LoadCommandsSize; |
| 903 | uint64_t SectionDataSize = 0; |
| 904 | uint64_t SectionDataFileSize = 0; |
| 905 | uint64_t VMSize = 0; |
| 906 | for (const MCSection &Sec : Asm) { |
| 907 | uint64_t Address = getSectionAddress(Sec: &Sec); |
| 908 | uint64_t Offset = SectionDataOffset.lookup(Val: &Sec); |
| 909 | uint64_t Size = Asm.getSectionAddressSize(Sec); |
| 910 | uint64_t FileSize = Asm.getSectionFileSize(Sec); |
| 911 | FileSize += getPaddingSize(Asm, Sec: &Sec); |
| 912 | |
| 913 | VMSize = std::max(a: VMSize, b: Address + Size); |
| 914 | |
| 915 | if (Sec.isBssSection()) |
| 916 | continue; |
| 917 | |
| 918 | SectionDataSize = std::max(a: SectionDataSize, b: Offset + Size); |
| 919 | SectionDataFileSize = std::max(a: SectionDataFileSize, b: Offset + FileSize); |
| 920 | } |
| 921 | // A segment's file size can't exceed its VM size, even when sections at |
| 922 | // overlapping addresses take more space in the file than in memory. |
| 923 | VMSize = std::max(a: VMSize, b: SectionDataSize); |
| 924 | |
| 925 | // The section data is padded to pointer size bytes. |
| 926 | // |
| 927 | // FIXME: Is this machine dependent? |
| 928 | unsigned SectionDataPadding = |
| 929 | offsetToAlignment(Value: SectionDataFileSize, Alignment: is64Bit() ? Align(8) : Align(4)); |
| 930 | SectionDataFileSize += SectionDataPadding; |
| 931 | |
| 932 | // Write the prolog, starting with the header and load command... |
| 933 | writeHeader(Type: MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize, |
| 934 | SubsectionsViaSymbols); |
| 935 | uint32_t Prot = |
| 936 | MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | MachO::VM_PROT_EXECUTE; |
| 937 | writeSegmentLoadCommand(Name: "" , NumSections, VMAddr: 0, VMSize, SectionDataStartOffset: SectionDataStart, |
| 938 | SectionDataSize, MaxProt: Prot, InitProt: Prot); |
| 939 | |
| 940 | // ... and then the section headers. |
| 941 | uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize; |
| 942 | for (const MCSection &Section : Asm) { |
| 943 | const auto &Sec = static_cast<const MCSectionMachO &>(Section); |
| 944 | std::vector<RelAndSymbol> &Relocs = Relocations[&Sec]; |
| 945 | unsigned NumRelocs = Relocs.size(); |
| 946 | uint64_t SectionStart = SectionDataStart + SectionDataOffset.lookup(Val: &Sec); |
| 947 | unsigned Flags = Sec.getTypeAndAttributes(); |
| 948 | if (Sec.hasInstructions()) |
| 949 | Flags |= MachO::S_ATTR_SOME_INSTRUCTIONS; |
| 950 | if (!cast<MCSectionMachO>(Val: Sec).isBssSection() && |
| 951 | !isUInt<32>(x: SectionStart)) { |
| 952 | getContext().reportError( |
| 953 | L: SMLoc(), Msg: "cannot encode offset of section; object file too large" ); |
| 954 | return NumBytesWritten(); |
| 955 | } |
| 956 | if (NumRelocs && !isUInt<32>(x: RelocTableEnd)) { |
| 957 | getContext().reportError( |
| 958 | L: SMLoc(), |
| 959 | Msg: "cannot encode offset of relocations; object file too large" ); |
| 960 | return NumBytesWritten(); |
| 961 | } |
| 962 | writeSection(Asm, Sec, VMAddr: getSectionAddress(Sec: &Sec), FileOffset: SectionStart, Flags, |
| 963 | RelocationsStart: RelocTableEnd, NumRelocations: NumRelocs); |
| 964 | RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info); |
| 965 | } |
| 966 | |
| 967 | // Write out the deployment target information, if it's available. |
| 968 | auto EmitDeploymentTargetVersion = |
| 969 | [&](const VersionInfoType &VersionInfo) { |
| 970 | auto EncodeVersion = [](VersionTuple V) -> uint32_t { |
| 971 | assert(!V.empty() && "empty version" ); |
| 972 | unsigned Update = V.getSubminor().value_or(u: 0); |
| 973 | unsigned Minor = V.getMinor().value_or(u: 0); |
| 974 | assert(Update < 256 && "unencodable update target version" ); |
| 975 | assert(Minor < 256 && "unencodable minor target version" ); |
| 976 | assert(V.getMajor() < 65536 && "unencodable major target version" ); |
| 977 | return Update | (Minor << 8) | (V.getMajor() << 16); |
| 978 | }; |
| 979 | uint32_t EncodedVersion = EncodeVersion(VersionTuple( |
| 980 | VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update)); |
| 981 | uint32_t SDKVersion = !VersionInfo.SDKVersion.empty() |
| 982 | ? EncodeVersion(VersionInfo.SDKVersion) |
| 983 | : 0; |
| 984 | if (VersionInfo.EmitBuildVersion) { |
| 985 | // FIXME: Currently empty tools. Add clang version in the future. |
| 986 | W.write<uint32_t>(Val: MachO::LC_BUILD_VERSION); |
| 987 | W.write<uint32_t>(Val: sizeof(MachO::build_version_command)); |
| 988 | W.write<uint32_t>(Val: VersionInfo.TypeOrPlatform.Platform); |
| 989 | W.write<uint32_t>(Val: EncodedVersion); |
| 990 | W.write<uint32_t>(Val: SDKVersion); |
| 991 | W.write<uint32_t>(Val: 0); // Empty tools list. |
| 992 | } else { |
| 993 | MachO::LoadCommandType LCType = |
| 994 | getLCFromMCVM(Type: VersionInfo.TypeOrPlatform.Type); |
| 995 | W.write<uint32_t>(Val: LCType); |
| 996 | W.write<uint32_t>(Val: sizeof(MachO::version_min_command)); |
| 997 | W.write<uint32_t>(Val: EncodedVersion); |
| 998 | W.write<uint32_t>(Val: SDKVersion); |
| 999 | } |
| 1000 | }; |
| 1001 | if (VersionInfo.Major != 0) |
| 1002 | EmitDeploymentTargetVersion(VersionInfo); |
| 1003 | if (TargetVariantVersionInfo.Major != 0) |
| 1004 | EmitDeploymentTargetVersion(TargetVariantVersionInfo); |
| 1005 | |
| 1006 | // Write the target triple load command, if used. |
| 1007 | if (TargetTriple) { |
| 1008 | assert((TargetTripleCommandSize > sizeof(MachO::target_triple_command)) && |
| 1009 | "target triple load command size is too small" ); |
| 1010 | |
| 1011 | // Write the command struct |
| 1012 | W.write<uint32_t>(Val: MachO::LC_TARGET_TRIPLE); |
| 1013 | W.write<uint32_t>(Val: TargetTripleCommandSize); |
| 1014 | W.write<uint32_t>(Val: sizeof( |
| 1015 | MachO::target_triple_command)); // Offset to the triple string - right |
| 1016 | // after the command struct. |
| 1017 | |
| 1018 | // Write the triple string, NUL byte, and command padding. |
| 1019 | uint64_t RemainingSize = |
| 1020 | TargetTripleCommandSize - sizeof(MachO::target_triple_command); |
| 1021 | writeWithPadding(Str: *TargetTriple, Size: RemainingSize); |
| 1022 | } |
| 1023 | |
| 1024 | // Write the data-in-code load command, if used. |
| 1025 | uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8; |
| 1026 | if (NumDataRegions) { |
| 1027 | uint64_t DataRegionsOffset = RelocTableEnd; |
| 1028 | uint64_t DataRegionsSize = NumDataRegions * 8; |
| 1029 | writeLinkeditLoadCommand(Type: MachO::LC_DATA_IN_CODE, DataOffset: DataRegionsOffset, |
| 1030 | DataSize: DataRegionsSize); |
| 1031 | } |
| 1032 | |
| 1033 | // Write the loh load command, if used. |
| 1034 | uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize; |
| 1035 | if (LOHSize) |
| 1036 | writeLinkeditLoadCommand(Type: MachO::LC_LINKER_OPTIMIZATION_HINT, |
| 1037 | DataOffset: DataInCodeTableEnd, DataSize: LOHSize); |
| 1038 | |
| 1039 | // Write the symbol table load command, if used. |
| 1040 | if (NumSymbols) { |
| 1041 | unsigned FirstLocalSymbol = 0; |
| 1042 | unsigned NumLocalSymbols = LocalSymbolData.size(); |
| 1043 | unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols; |
| 1044 | unsigned NumExternalSymbols = ExternalSymbolData.size(); |
| 1045 | unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols; |
| 1046 | unsigned NumUndefinedSymbols = UndefinedSymbolData.size(); |
| 1047 | unsigned NumIndirectSymbols = IndirectSymbols.size(); |
| 1048 | unsigned NumSymTabSymbols = |
| 1049 | NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols; |
| 1050 | uint64_t IndirectSymbolSize = NumIndirectSymbols * 4; |
| 1051 | uint64_t IndirectSymbolOffset = 0; |
| 1052 | |
| 1053 | // If used, the indirect symbols are written after the section data. |
| 1054 | if (NumIndirectSymbols) |
| 1055 | IndirectSymbolOffset = LOHTableEnd; |
| 1056 | |
| 1057 | // The symbol table is written after the indirect symbol data. |
| 1058 | uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize; |
| 1059 | |
| 1060 | // The string table is written after symbol table. |
| 1061 | uint64_t StringTableOffset = |
| 1062 | SymbolTableOffset + NumSymTabSymbols * (is64Bit() ? |
| 1063 | sizeof(MachO::nlist_64) : |
| 1064 | sizeof(MachO::nlist)); |
| 1065 | writeSymtabLoadCommand(SymbolOffset: SymbolTableOffset, NumSymbols: NumSymTabSymbols, |
| 1066 | StringTableOffset, StringTableSize: StringTable.getSize()); |
| 1067 | |
| 1068 | writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols, |
| 1069 | FirstExternalSymbol, NumExternalSymbols, |
| 1070 | FirstUndefinedSymbol, NumUndefinedSymbols, |
| 1071 | IndirectSymbolOffset, NumIndirectSymbols); |
| 1072 | } |
| 1073 | |
| 1074 | // Write the linker options load commands. |
| 1075 | for (const auto &Option : LinkerOptions) |
| 1076 | writeLinkerOptionsLoadCommand(Options: Option); |
| 1077 | |
| 1078 | // Write the actual section data. |
| 1079 | for (const MCSection &Sec : Asm) { |
| 1080 | Asm.writeSectionData(OS&: W.OS, Section: &Sec); |
| 1081 | |
| 1082 | uint64_t Pad = getPaddingSize(Asm, Sec: &Sec); |
| 1083 | W.OS.write_zeros(NumZeros: Pad); |
| 1084 | } |
| 1085 | |
| 1086 | // Write the extra padding. |
| 1087 | W.OS.write_zeros(NumZeros: SectionDataPadding); |
| 1088 | |
| 1089 | // Write the relocation entries. |
| 1090 | for (const MCSection &Sec : Asm) { |
| 1091 | // Write the section relocation entries, in reverse order to match 'as' |
| 1092 | // (approximately, the exact algorithm is more complicated than this). |
| 1093 | std::vector<RelAndSymbol> &Relocs = Relocations[&Sec]; |
| 1094 | for (const RelAndSymbol &Rel : llvm::reverse(C&: Relocs)) { |
| 1095 | W.write<uint32_t>(Val: Rel.MRE.r_word0); |
| 1096 | W.write<uint32_t>(Val: Rel.MRE.r_word1); |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | // Write out the data-in-code region payload, if there is one. |
| 1101 | for (DataRegionData Data : DataRegions) { |
| 1102 | uint64_t Start = getSymbolAddress(S: *Data.Start); |
| 1103 | uint64_t End; |
| 1104 | if (Data.End) |
| 1105 | End = getSymbolAddress(S: *Data.End); |
| 1106 | else |
| 1107 | report_fatal_error(reason: "data region not terminated" ); |
| 1108 | |
| 1109 | LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data.Kind |
| 1110 | << " start: " << Start << "(" << Data.Start->getName() |
| 1111 | << ")" << " end: " << End << "(" << Data.End->getName() |
| 1112 | << ")" << " size: " << End - Start << "\n" ); |
| 1113 | W.write<uint32_t>(Val: Start); |
| 1114 | W.write<uint16_t>(Val: End - Start); |
| 1115 | W.write<uint16_t>(Val: Data.Kind); |
| 1116 | } |
| 1117 | |
| 1118 | // Write out the loh commands, if there is one. |
| 1119 | if (LOHSize) { |
| 1120 | #ifndef NDEBUG |
| 1121 | unsigned Start = W.OS.tell(); |
| 1122 | #endif |
| 1123 | LOHContainer.emit(Asm, ObjWriter&: *this); |
| 1124 | // Pad to a multiple of the pointer size. |
| 1125 | W.OS.write_zeros( |
| 1126 | NumZeros: offsetToAlignment(Value: LOHRawSize, Alignment: is64Bit() ? Align(8) : Align(4))); |
| 1127 | assert(W.OS.tell() - Start == LOHSize); |
| 1128 | } |
| 1129 | |
| 1130 | // Write the symbol table data, if used. |
| 1131 | if (NumSymbols) { |
| 1132 | // Write the indirect symbol entries. |
| 1133 | for (auto &ISD : IndirectSymbols) { |
| 1134 | // Indirect symbols in the non-lazy symbol pointer section have some |
| 1135 | // special handling. |
| 1136 | const MCSectionMachO &Section = |
| 1137 | static_cast<const MCSectionMachO &>(*ISD.Section); |
| 1138 | if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) { |
| 1139 | // If this symbol is defined and internal, mark it as such. |
| 1140 | if (ISD.Symbol->isDefined() && !ISD.Symbol->isExternal()) { |
| 1141 | uint32_t Flags = MachO::INDIRECT_SYMBOL_LOCAL; |
| 1142 | if (ISD.Symbol->isAbsolute()) |
| 1143 | Flags |= MachO::INDIRECT_SYMBOL_ABS; |
| 1144 | W.write<uint32_t>(Val: Flags); |
| 1145 | continue; |
| 1146 | } |
| 1147 | } |
| 1148 | |
| 1149 | W.write<uint32_t>(Val: ISD.Symbol->getIndex()); |
| 1150 | } |
| 1151 | |
| 1152 | // FIXME: Check that offsets match computed ones. |
| 1153 | |
| 1154 | // Write the symbol table entries. |
| 1155 | for (auto *SymbolData : |
| 1156 | {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData}) |
| 1157 | for (MachSymbolData &Entry : *SymbolData) |
| 1158 | writeNlist(MSD&: Entry, Asm); |
| 1159 | |
| 1160 | // Write the string table. |
| 1161 | StringTable.write(OS&: W.OS); |
| 1162 | } |
| 1163 | |
| 1164 | return NumBytesWritten(); |
| 1165 | } |
| 1166 | |