LLVM 19.0.0git
MachObjectWriter.cpp
Go to the documentation of this file.
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"
15#include "llvm/MC/MCAssembler.h"
16#include "llvm/MC/MCContext.h"
18#include "llvm/MC/MCExpr.h"
20#include "llvm/MC/MCFragment.h"
24#include "llvm/MC/MCSection.h"
26#include "llvm/MC/MCSymbol.h"
28#include "llvm/MC/MCValue.h"
31#include "llvm/Support/Debug.h"
33#include "llvm/Support/LEB128.h"
36#include <algorithm>
37#include <cassert>
38#include <cstdint>
39#include <string>
40#include <utility>
41#include <vector>
42
43using namespace llvm;
44
45#define DEBUG_TYPE "mc"
46
48 Relocations.clear();
49 IndirectSymBase.clear();
50 IndirectSymbols.clear();
51 DataRegions.clear();
52 SectionAddress.clear();
53 SectionOrder.clear();
54 StringTable.clear();
55 LocalSymbolData.clear();
56 ExternalSymbolData.clear();
57 UndefinedSymbolData.clear();
59}
60
62 // Undefined symbols are always extern.
63 if (S.isUndefined())
64 return true;
65
66 // References to weak definitions require external relocation entries; the
67 // definition may not always be the one in the same object file.
68 if (cast<MCSymbolMachO>(S).isWeakDefinition())
69 return true;
70
71 // Otherwise, we can use an internal relocation.
72 return false;
73}
74
75bool MachObjectWriter::
76MachSymbolData::operator<(const MachSymbolData &RHS) const {
77 return Symbol->getName() < RHS.Symbol->getName();
78}
79
80bool MachObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
81 const MCFixupKindInfo &FKI = Asm.getBackend().getFixupKindInfo(
82 (MCFixupKind) Kind);
83
85}
86
89 const MCFragment *Fragment) const {
90 return getSectionAddress(Fragment->getParent()) +
91 Asm.getFragmentOffset(*Fragment);
92}
93
95 const MCAssembler &Asm) const {
96 // If this is a variable, then recursively evaluate now.
97 if (S.isVariable()) {
98 if (const MCConstantExpr *C =
99 dyn_cast<const MCConstantExpr>(S.getVariableValue()))
100 return C->getValue();
101
103 if (!S.getVariableValue()->evaluateAsRelocatable(Target, &Asm, nullptr))
104 report_fatal_error("unable to evaluate offset for variable '" +
105 S.getName() + "'");
106
107 // Verify that any used symbols are defined.
108 if (Target.getSymA() && Target.getSymA()->getSymbol().isUndefined())
109 report_fatal_error("unable to evaluate offset to undefined symbol '" +
110 Target.getSymA()->getSymbol().getName() + "'");
111 if (Target.getSymB() && Target.getSymB()->getSymbol().isUndefined())
112 report_fatal_error("unable to evaluate offset to undefined symbol '" +
113 Target.getSymB()->getSymbol().getName() + "'");
114
115 uint64_t Address = Target.getConstant();
116 if (Target.getSymA())
117 Address += getSymbolAddress(Target.getSymA()->getSymbol(), Asm);
118 if (Target.getSymB())
119 Address += getSymbolAddress(Target.getSymB()->getSymbol(), Asm);
120 return Address;
121 }
122
124 Asm.getSymbolOffset(S);
125}
126
128 const MCSection *Sec) const {
129 uint64_t EndAddr = getSectionAddress(Sec) + Asm.getSectionAddressSize(*Sec);
130 unsigned Next = cast<MCSectionMachO>(Sec)->getLayoutOrder() + 1;
131 if (Next >= SectionOrder.size())
132 return 0;
133
134 const MCSection &NextSec = *SectionOrder[Next];
135 if (NextSec.isVirtualSection())
136 return 0;
137 return offsetToAlignment(EndAddr, NextSec.getAlign());
138}
139
140static bool isSymbolLinkerVisible(const MCSymbol &Symbol) {
141 // Non-temporary labels should always be visible to the linker.
142 if (!Symbol.isTemporary())
143 return true;
144
145 if (Symbol.isUsedInReloc())
146 return true;
147
148 return false;
149}
150
152 // Linker visible symbols define atoms.
154 return &S;
155
156 // Absolute and undefined symbols have no defining atom.
157 if (!S.isInSection())
158 return nullptr;
159
160 // Non-linker visible symbols in sections which can't be atomized have no
161 // defining atom.
163 *S.getFragment()->getParent()))
164 return nullptr;
165
166 // Otherwise, return the atom for the containing fragment.
167 return S.getFragment()->getAtom();
168}
169
171 unsigned NumLoadCommands,
172 unsigned LoadCommandsSize,
173 bool SubsectionsViaSymbols) {
174 uint32_t Flags = 0;
175
176 if (SubsectionsViaSymbols)
178
179 // struct mach_header (28 bytes) or
180 // struct mach_header_64 (32 bytes)
181
182 uint64_t Start = W.OS.tell();
183 (void) Start;
184
186
187 W.write<uint32_t>(TargetObjectWriter->getCPUType());
188 W.write<uint32_t>(TargetObjectWriter->getCPUSubtype());
189
191 W.write<uint32_t>(NumLoadCommands);
192 W.write<uint32_t>(LoadCommandsSize);
193 W.write<uint32_t>(Flags);
194 if (is64Bit())
195 W.write<uint32_t>(0); // reserved
196
197 assert(W.OS.tell() - Start == (is64Bit() ? sizeof(MachO::mach_header_64)
198 : sizeof(MachO::mach_header)));
199}
200
201void MachObjectWriter::writeWithPadding(StringRef Str, uint64_t Size) {
202 assert(Size >= Str.size());
203 W.OS << Str;
204 W.OS.write_zeros(Size - Str.size());
205}
206
207/// writeSegmentLoadCommand - Write a segment load command.
208///
209/// \param NumSections The number of sections in this segment.
210/// \param SectionDataSize The total size of the sections.
212 StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize,
213 uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt,
214 uint32_t InitProt) {
215 // struct segment_command (56 bytes) or
216 // struct segment_command_64 (72 bytes)
217
218 uint64_t Start = W.OS.tell();
219 (void) Start;
220
221 unsigned SegmentLoadCommandSize =
224 W.write<uint32_t>(is64Bit() ? MachO::LC_SEGMENT_64 : MachO::LC_SEGMENT);
225 W.write<uint32_t>(SegmentLoadCommandSize +
226 NumSections * (is64Bit() ? sizeof(MachO::section_64) :
227 sizeof(MachO::section)));
228
229 writeWithPadding(Name, 16);
230 if (is64Bit()) {
231 W.write<uint64_t>(VMAddr); // vmaddr
232 W.write<uint64_t>(VMSize); // vmsize
233 W.write<uint64_t>(SectionDataStartOffset); // file offset
234 W.write<uint64_t>(SectionDataSize); // file size
235 } else {
236 W.write<uint32_t>(VMAddr); // vmaddr
237 W.write<uint32_t>(VMSize); // vmsize
238 W.write<uint32_t>(SectionDataStartOffset); // file offset
239 W.write<uint32_t>(SectionDataSize); // file size
240 }
241 // maxprot
242 W.write<uint32_t>(MaxProt);
243 // initprot
244 W.write<uint32_t>(InitProt);
245 W.write<uint32_t>(NumSections);
246 W.write<uint32_t>(0); // flags
247
248 assert(W.OS.tell() - Start == SegmentLoadCommandSize);
249}
250
252 const MCSection &Sec, uint64_t VMAddr,
253 uint64_t FileOffset, unsigned Flags,
254 uint64_t RelocationsStart,
255 unsigned NumRelocations) {
256 uint64_t SectionSize = Asm.getSectionAddressSize(Sec);
257 const MCSectionMachO &Section = cast<MCSectionMachO>(Sec);
258
259 // The offset is unused for virtual sections.
260 if (Section.isVirtualSection()) {
261 assert(Asm.getSectionFileSize(Sec) == 0 && "Invalid file size!");
262 FileOffset = 0;
263 }
264
265 // struct section (68 bytes) or
266 // struct section_64 (80 bytes)
267
268 uint64_t Start = W.OS.tell();
269 (void) Start;
270
271 writeWithPadding(Section.getName(), 16);
272 writeWithPadding(Section.getSegmentName(), 16);
273 if (is64Bit()) {
274 W.write<uint64_t>(VMAddr); // address
275 W.write<uint64_t>(SectionSize); // size
276 } else {
277 W.write<uint32_t>(VMAddr); // address
278 W.write<uint32_t>(SectionSize); // size
279 }
280 assert(isUInt<32>(FileOffset) && "Cannot encode offset of section");
281 W.write<uint32_t>(FileOffset);
282
283 W.write<uint32_t>(Log2(Section.getAlign()));
284 assert((!NumRelocations || isUInt<32>(RelocationsStart)) &&
285 "Cannot encode offset of relocations");
286 W.write<uint32_t>(NumRelocations ? RelocationsStart : 0);
287 W.write<uint32_t>(NumRelocations);
288 W.write<uint32_t>(Flags);
289 W.write<uint32_t>(IndirectSymBase.lookup(&Sec)); // reserved1
290 W.write<uint32_t>(Section.getStubSize()); // reserved2
291 if (is64Bit())
292 W.write<uint32_t>(0); // reserved3
293
294 assert(W.OS.tell() - Start ==
295 (is64Bit() ? sizeof(MachO::section_64) : sizeof(MachO::section)));
296}
297
299 uint32_t NumSymbols,
300 uint32_t StringTableOffset,
301 uint32_t StringTableSize) {
302 // struct symtab_command (24 bytes)
303
304 uint64_t Start = W.OS.tell();
305 (void) Start;
306
307 W.write<uint32_t>(MachO::LC_SYMTAB);
309 W.write<uint32_t>(SymbolOffset);
310 W.write<uint32_t>(NumSymbols);
311 W.write<uint32_t>(StringTableOffset);
312 W.write<uint32_t>(StringTableSize);
313
314 assert(W.OS.tell() - Start == sizeof(MachO::symtab_command));
315}
316
318 uint32_t NumLocalSymbols,
319 uint32_t FirstExternalSymbol,
320 uint32_t NumExternalSymbols,
321 uint32_t FirstUndefinedSymbol,
322 uint32_t NumUndefinedSymbols,
323 uint32_t IndirectSymbolOffset,
324 uint32_t NumIndirectSymbols) {
325 // struct dysymtab_command (80 bytes)
326
327 uint64_t Start = W.OS.tell();
328 (void) Start;
329
330 W.write<uint32_t>(MachO::LC_DYSYMTAB);
332 W.write<uint32_t>(FirstLocalSymbol);
333 W.write<uint32_t>(NumLocalSymbols);
334 W.write<uint32_t>(FirstExternalSymbol);
335 W.write<uint32_t>(NumExternalSymbols);
336 W.write<uint32_t>(FirstUndefinedSymbol);
337 W.write<uint32_t>(NumUndefinedSymbols);
338 W.write<uint32_t>(0); // tocoff
339 W.write<uint32_t>(0); // ntoc
340 W.write<uint32_t>(0); // modtaboff
341 W.write<uint32_t>(0); // nmodtab
342 W.write<uint32_t>(0); // extrefsymoff
343 W.write<uint32_t>(0); // nextrefsyms
344 W.write<uint32_t>(IndirectSymbolOffset);
345 W.write<uint32_t>(NumIndirectSymbols);
346 W.write<uint32_t>(0); // extreloff
347 W.write<uint32_t>(0); // nextrel
348 W.write<uint32_t>(0); // locreloff
349 W.write<uint32_t>(0); // nlocrel
350
351 assert(W.OS.tell() - Start == sizeof(MachO::dysymtab_command));
352}
353
354MachObjectWriter::MachSymbolData *
355MachObjectWriter::findSymbolData(const MCSymbol &Sym) {
356 for (auto *SymbolData :
357 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
358 for (MachSymbolData &Entry : *SymbolData)
359 if (Entry.Symbol == &Sym)
360 return &Entry;
361
362 return nullptr;
363}
364
366 const MCSymbol *S = &Sym;
367 while (S->isVariable()) {
368 const MCExpr *Value = S->getVariableValue();
369 const auto *Ref = dyn_cast<MCSymbolRefExpr>(Value);
370 if (!Ref)
371 return *S;
372 S = &Ref->getSymbol();
373 }
374 return *S;
375}
376
377void MachObjectWriter::writeNlist(MachSymbolData &MSD, const MCAssembler &Asm) {
378 const MCSymbol *Symbol = MSD.Symbol;
379 const MCSymbol &Data = *Symbol;
380 const MCSymbol *AliasedSymbol = &findAliasedSymbol(*Symbol);
381 uint8_t SectionIndex = MSD.SectionIndex;
382 uint8_t Type = 0;
383 uint64_t Address = 0;
384 bool IsAlias = Symbol != AliasedSymbol;
385
386 const MCSymbol &OrigSymbol = *Symbol;
387 MachSymbolData *AliaseeInfo;
388 if (IsAlias) {
389 AliaseeInfo = findSymbolData(*AliasedSymbol);
390 if (AliaseeInfo)
391 SectionIndex = AliaseeInfo->SectionIndex;
392 Symbol = AliasedSymbol;
393 // FIXME: Should this update Data as well?
394 }
395
396 // Set the N_TYPE bits. See <mach-o/nlist.h>.
397 //
398 // FIXME: Are the prebound or indirect fields possible here?
399 if (IsAlias && Symbol->isUndefined())
401 else if (Symbol->isUndefined())
403 else if (Symbol->isAbsolute())
405 else
407
408 // FIXME: Set STAB bits.
409
410 if (Data.isPrivateExtern())
412
413 // Set external bit.
414 if (Data.isExternal() || (!IsAlias && Symbol->isUndefined()))
416
417 // Compute the symbol address.
418 if (IsAlias && Symbol->isUndefined())
419 Address = AliaseeInfo->StringIndex;
420 else if (Symbol->isDefined())
421 Address = getSymbolAddress(OrigSymbol, Asm);
422 else if (Symbol->isCommon()) {
423 // Common symbols are encoded with the size in the address
424 // field, and their alignment in the flags.
425 Address = Symbol->getCommonSize();
426 }
427
428 // struct nlist (12 bytes)
429
430 W.write<uint32_t>(MSD.StringIndex);
431 W.OS << char(Type);
432 W.OS << char(SectionIndex);
433
434 // The Mach-O streamer uses the lowest 16-bits of the flags for the 'desc'
435 // value.
436 bool EncodeAsAltEntry =
437 IsAlias && cast<MCSymbolMachO>(OrigSymbol).isAltEntry();
438 W.write<uint16_t>(cast<MCSymbolMachO>(Symbol)->getEncodedFlags(EncodeAsAltEntry));
439 if (is64Bit())
441 else
443}
444
446 uint32_t DataOffset,
447 uint32_t DataSize) {
448 uint64_t Start = W.OS.tell();
449 (void) Start;
450
453 W.write<uint32_t>(DataOffset);
454 W.write<uint32_t>(DataSize);
455
456 assert(W.OS.tell() - Start == sizeof(MachO::linkedit_data_command));
457}
458
460 const std::vector<std::string> &Options, bool is64Bit)
461{
462 unsigned Size = sizeof(MachO::linker_option_command);
463 for (const std::string &Option : Options)
464 Size += Option.size() + 1;
465 return alignTo(Size, is64Bit ? 8 : 4);
466}
467
469 const std::vector<std::string> &Options)
470{
472 uint64_t Start = W.OS.tell();
473 (void) Start;
474
475 W.write<uint32_t>(MachO::LC_LINKER_OPTION);
477 W.write<uint32_t>(Options.size());
478 uint64_t BytesWritten = sizeof(MachO::linker_option_command);
479 for (const std::string &Option : Options) {
480 // Write each string, including the null byte.
481 W.OS << Option << '\0';
482 BytesWritten += Option.size() + 1;
483 }
484
485 // Pad to a multiple of the pointer size.
487 offsetToAlignment(BytesWritten, is64Bit() ? Align(8) : Align(4)));
488
489 assert(W.OS.tell() - Start == Size);
490}
491
492static bool isFixupTargetValid(const MCValue &Target) {
493 // Target is (LHS - RHS + cst).
494 // We don't support the form where LHS is null: -RHS + cst
495 if (!Target.getSymA() && Target.getSymB())
496 return false;
497 return true;
498}
499
501 const MCFragment *Fragment,
502 const MCFixup &Fixup, MCValue Target,
503 uint64_t &FixedValue) {
505 Asm.getContext().reportError(Fixup.getLoc(),
506 "unsupported relocation expression");
507 return;
508 }
509
510 TargetObjectWriter->recordRelocation(this, Asm, Fragment, Fixup, Target,
511 FixedValue);
512}
513
515 // This is the point where 'as' creates actual symbols for indirect symbols
516 // (in the following two passes). It would be easier for us to do this sooner
517 // when we see the attribute, but that makes getting the order in the symbol
518 // table much more complicated than it is worth.
519 //
520 // FIXME: Revisit this when the dust settles.
521
522 // Report errors for use of .indirect_symbol not in a symbol pointer section
523 // or stub section.
524 for (IndirectSymbolData &ISD : IndirectSymbols) {
525 const MCSectionMachO &Section = cast<MCSectionMachO>(*ISD.Section);
526
527 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
528 Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
529 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS &&
530 Section.getType() != MachO::S_SYMBOL_STUBS) {
531 MCSymbol &Symbol = *ISD.Symbol;
532 report_fatal_error("indirect symbol '" + Symbol.getName() +
533 "' not in a symbol pointer or stub section");
534 }
535 }
536
537 // Bind non-lazy symbol pointers first.
538 for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) {
539 const auto &Section = cast<MCSectionMachO>(*ISD.Section);
540
541 if (Section.getType() != MachO::S_NON_LAZY_SYMBOL_POINTERS &&
542 Section.getType() != MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
543 continue;
544
545 // Initialize the section indirect symbol base, if necessary.
546 IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex));
547
548 Asm.registerSymbol(*ISD.Symbol);
549 }
550
551 // Then lazy symbol pointers and symbol stubs.
552 for (auto [IndirectIndex, ISD] : enumerate(IndirectSymbols)) {
553 const auto &Section = cast<MCSectionMachO>(*ISD.Section);
554
555 if (Section.getType() != MachO::S_LAZY_SYMBOL_POINTERS &&
556 Section.getType() != MachO::S_SYMBOL_STUBS)
557 continue;
558
559 // Initialize the section indirect symbol base, if necessary.
560 IndirectSymBase.insert(std::make_pair(ISD.Section, IndirectIndex));
561
562 // Set the symbol type to undefined lazy, but only on construction.
563 //
564 // FIXME: Do not hardcode.
565 if (Asm.registerSymbol(*ISD.Symbol))
566 cast<MCSymbolMachO>(ISD.Symbol)->setReferenceTypeUndefinedLazy(true);
567 }
568}
569
570/// computeSymbolTable - Compute the symbol table data
572 MCAssembler &Asm, std::vector<MachSymbolData> &LocalSymbolData,
573 std::vector<MachSymbolData> &ExternalSymbolData,
574 std::vector<MachSymbolData> &UndefinedSymbolData) {
575 // Build section lookup table.
577 unsigned Index = 1;
578 for (MCSection &Sec : Asm)
579 SectionIndexMap[&Sec] = Index++;
580 assert(Index <= 256 && "Too many sections!");
581
582 // Build the string table.
583 for (const MCSymbol &Symbol : Asm.symbols()) {
584 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
585 continue;
586
587 StringTable.add(Symbol.getName());
588 }
589 StringTable.finalize();
590
591 // Build the symbol arrays but only for non-local symbols.
592 //
593 // The particular order that we collect and then sort the symbols is chosen to
594 // match 'as'. Even though it doesn't matter for correctness, this is
595 // important for letting us diff .o files.
596 for (const MCSymbol &Symbol : Asm.symbols()) {
597 // Ignore non-linker visible symbols.
598 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
599 continue;
600
601 if (!Symbol.isExternal() && !Symbol.isUndefined())
602 continue;
603
604 MachSymbolData MSD;
605 MSD.Symbol = &Symbol;
606 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
607
608 if (Symbol.isUndefined()) {
609 MSD.SectionIndex = 0;
610 UndefinedSymbolData.push_back(MSD);
611 } else if (Symbol.isAbsolute()) {
612 MSD.SectionIndex = 0;
613 ExternalSymbolData.push_back(MSD);
614 } else {
615 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
616 assert(MSD.SectionIndex && "Invalid section index!");
617 ExternalSymbolData.push_back(MSD);
618 }
619 }
620
621 // Now add the data for local symbols.
622 for (const MCSymbol &Symbol : Asm.symbols()) {
623 // Ignore non-linker visible symbols.
624 if (!cast<MCSymbolMachO>(Symbol).isSymbolLinkerVisible())
625 continue;
626
627 if (Symbol.isExternal() || Symbol.isUndefined())
628 continue;
629
630 MachSymbolData MSD;
631 MSD.Symbol = &Symbol;
632 MSD.StringIndex = StringTable.getOffset(Symbol.getName());
633
634 if (Symbol.isAbsolute()) {
635 MSD.SectionIndex = 0;
636 LocalSymbolData.push_back(MSD);
637 } else {
638 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
639 assert(MSD.SectionIndex && "Invalid section index!");
640 LocalSymbolData.push_back(MSD);
641 }
642 }
643
644 // External and undefined symbols are required to be in lexicographic order.
645 llvm::sort(ExternalSymbolData);
646 llvm::sort(UndefinedSymbolData);
647
648 // Set the symbol indices.
649 Index = 0;
650 for (auto *SymbolData :
651 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
652 for (MachSymbolData &Entry : *SymbolData)
653 Entry.Symbol->setIndex(Index++);
654
655 for (const MCSection &Section : Asm) {
656 for (RelAndSymbol &Rel : Relocations[&Section]) {
657 if (!Rel.Sym)
658 continue;
659
660 // Set the Index and the IsExtern bit.
661 unsigned Index = Rel.Sym->getIndex();
662 assert(isInt<24>(Index));
664 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & (~0U << 24)) | Index | (1 << 27);
665 else
666 Rel.MRE.r_word1 = (Rel.MRE.r_word1 & 0xff) | Index << 8 | (1 << 4);
667 }
668 }
669}
670
672 // Assign layout order indices to sections.
673 unsigned i = 0;
674 // Compute the section layout order. Virtual sections must go last.
675 for (MCSection &Sec : Asm) {
676 if (!Sec.isVirtualSection()) {
677 SectionOrder.push_back(&Sec);
678 cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
679 }
680 }
681 for (MCSection &Sec : Asm) {
682 if (Sec.isVirtualSection()) {
683 SectionOrder.push_back(&Sec);
684 cast<MCSectionMachO>(Sec).setLayoutOrder(i++);
685 }
686 }
687
688 uint64_t StartAddress = 0;
689 for (const MCSection *Sec : SectionOrder) {
690 StartAddress = alignTo(StartAddress, Sec->getAlign());
691 SectionAddress[Sec] = StartAddress;
692 StartAddress += Asm.getSectionAddressSize(*Sec);
693
694 // Explicitly pad the section to match the alignment requirements of the
695 // following one. This is for 'gas' compatibility, it shouldn't
696 /// strictly be necessary.
697 StartAddress += getPaddingSize(Asm, Sec);
698 }
699}
700
703
704 // Create symbol data for any indirect symbols.
706}
707
709 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
710 bool InSet, bool IsPCRel) const {
711 if (InSet)
712 return true;
713
714 // The effective address is
715 // addr(atom(A)) + offset(A)
716 // - addr(atom(B)) - offset(B)
717 // and the offsets are not relocatable, so the fixup is fully resolved when
718 // addr(atom(A)) - addr(atom(B)) == 0.
719 const MCSymbol &SA = findAliasedSymbol(SymA);
720 const MCSection &SecA = SA.getSection();
721 const MCSection &SecB = *FB.getParent();
722
723 if (IsPCRel) {
724 // The simple (Darwin, except on x86_64) way of dealing with this was to
725 // assume that any reference to a temporary symbol *must* be a temporary
726 // symbol in the same atom, unless the sections differ. Therefore, any PCrel
727 // relocation to a temporary symbol (in the same section) is fully
728 // resolved. This also works in conjunction with absolutized .set, which
729 // requires the compiler to use .set to absolutize the differences between
730 // symbols which the compiler knows to be assembly time constants, so we
731 // don't need to worry about considering symbol differences fully resolved.
732 //
733 // If the file isn't using sub-sections-via-symbols, we can make the
734 // same assumptions about any symbol that we normally make about
735 // assembler locals.
736
737 bool hasReliableSymbolDifference = isX86_64();
738 if (!hasReliableSymbolDifference) {
739 if (!SA.isInSection() || &SecA != &SecB ||
740 (!SA.isTemporary() && FB.getAtom() != SA.getFragment()->getAtom() &&
741 Asm.getSubsectionsViaSymbols()))
742 return false;
743 return true;
744 }
745 }
746
747 // If they are not in the same section, we can't compute the diff.
748 if (&SecA != &SecB)
749 return false;
750
751 // If the atoms are the same, they are guaranteed to have the same address.
752 return SA.getFragment()->getAtom() == FB.getAtom();
753}
754
756 switch (Type) {
757 case MCVM_OSXVersionMin: return MachO::LC_VERSION_MIN_MACOSX;
758 case MCVM_IOSVersionMin: return MachO::LC_VERSION_MIN_IPHONEOS;
759 case MCVM_TvOSVersionMin: return MachO::LC_VERSION_MIN_TVOS;
760 case MCVM_WatchOSVersionMin: return MachO::LC_VERSION_MIN_WATCHOS;
761 }
762 llvm_unreachable("Invalid mc version min type");
763}
764
766 MCSection *AddrSigSection =
767 Asm.getContext().getObjectFileInfo()->getAddrSigSection();
768 unsigned Log2Size = is64Bit() ? 3 : 2;
769 for (const MCSymbol *S : getAddrsigSyms()) {
770 if (!S->isRegistered())
771 continue;
773 MRE.r_word0 = 0;
774 MRE.r_word1 = (Log2Size << 25) | (MachO::GENERIC_RELOC_VANILLA << 28);
775 addRelocation(S, AddrSigSection, MRE);
776 }
777}
778
780 uint64_t StartOffset = W.OS.tell();
781 auto NumBytesWritten = [&] { return W.OS.tell() - StartOffset; };
782
784
785 // Compute symbol table information and bind symbol indices.
786 computeSymbolTable(Asm, LocalSymbolData, ExternalSymbolData,
787 UndefinedSymbolData);
788
789 if (!Asm.CGProfile.empty()) {
790 MCSection *CGProfileSection = Asm.getContext().getMachOSection(
791 "__LLVM", "__cg_profile", 0, SectionKind::getMetadata());
792 auto &Frag = cast<MCDataFragment>(*CGProfileSection->begin());
793 Frag.getContents().clear();
794 raw_svector_ostream OS(Frag.getContents());
795 for (const MCAssembler::CGProfileEntry &CGPE : Asm.CGProfile) {
796 uint32_t FromIndex = CGPE.From->getSymbol().getIndex();
797 uint32_t ToIndex = CGPE.To->getSymbol().getIndex();
798 support::endian::write(OS, FromIndex, W.Endian);
801 }
802 }
803
804 unsigned NumSections = Asm.end() - Asm.begin();
805 const MCAssembler::VersionInfoType &VersionInfo = Asm.getVersionInfo();
806
807 // The section data starts after the header, the segment load command (and
808 // section headers) and the symbol table.
809 unsigned NumLoadCommands = 1;
810 uint64_t LoadCommandsSize = is64Bit() ?
811 sizeof(MachO::segment_command_64) + NumSections * sizeof(MachO::section_64):
812 sizeof(MachO::segment_command) + NumSections * sizeof(MachO::section);
813
814 // Add the deployment target version info load command size, if used.
815 if (VersionInfo.Major != 0) {
816 ++NumLoadCommands;
817 if (VersionInfo.EmitBuildVersion)
818 LoadCommandsSize += sizeof(MachO::build_version_command);
819 else
820 LoadCommandsSize += sizeof(MachO::version_min_command);
821 }
822
823 const MCAssembler::VersionInfoType &TargetVariantVersionInfo =
824 Asm.getDarwinTargetVariantVersionInfo();
825
826 // Add the target variant version info load command size, if used.
827 if (TargetVariantVersionInfo.Major != 0) {
828 ++NumLoadCommands;
829 assert(TargetVariantVersionInfo.EmitBuildVersion &&
830 "target variant should use build version");
831 LoadCommandsSize += sizeof(MachO::build_version_command);
832 }
833
834 // Add the data-in-code load command size, if used.
835 unsigned NumDataRegions = DataRegions.size();
836 if (NumDataRegions) {
837 ++NumLoadCommands;
838 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
839 }
840
841 // Add the loh load command size, if used.
842 uint64_t LOHRawSize = Asm.getLOHContainer().getEmitSize(Asm, *this);
843 uint64_t LOHSize = alignTo(LOHRawSize, is64Bit() ? 8 : 4);
844 if (LOHSize) {
845 ++NumLoadCommands;
846 LoadCommandsSize += sizeof(MachO::linkedit_data_command);
847 }
848
849 // Add the symbol table load command sizes, if used.
850 unsigned NumSymbols = LocalSymbolData.size() + ExternalSymbolData.size() +
851 UndefinedSymbolData.size();
852 if (NumSymbols) {
853 NumLoadCommands += 2;
854 LoadCommandsSize += (sizeof(MachO::symtab_command) +
856 }
857
858 // Add the linker option load commands sizes.
859 for (const auto &Option : Asm.getLinkerOptions()) {
860 ++NumLoadCommands;
861 LoadCommandsSize += ComputeLinkerOptionsLoadCommandSize(Option, is64Bit());
862 }
863
864 // Compute the total size of the section data, as well as its file size and vm
865 // size.
866 uint64_t SectionDataStart = (is64Bit() ? sizeof(MachO::mach_header_64) :
867 sizeof(MachO::mach_header)) + LoadCommandsSize;
868 uint64_t SectionDataSize = 0;
869 uint64_t SectionDataFileSize = 0;
870 uint64_t VMSize = 0;
871 for (const MCSection &Sec : Asm) {
873 uint64_t Size = Asm.getSectionAddressSize(Sec);
874 uint64_t FileSize = Asm.getSectionFileSize(Sec);
875 FileSize += getPaddingSize(Asm, &Sec);
876
877 VMSize = std::max(VMSize, Address + Size);
878
879 if (Sec.isVirtualSection())
880 continue;
881
882 SectionDataSize = std::max(SectionDataSize, Address + Size);
883 SectionDataFileSize = std::max(SectionDataFileSize, Address + FileSize);
884 }
885
886 // The section data is padded to pointer size bytes.
887 //
888 // FIXME: Is this machine dependent?
889 unsigned SectionDataPadding =
890 offsetToAlignment(SectionDataFileSize, is64Bit() ? Align(8) : Align(4));
891 SectionDataFileSize += SectionDataPadding;
892
893 // Write the prolog, starting with the header and load command...
894 writeHeader(MachO::MH_OBJECT, NumLoadCommands, LoadCommandsSize,
895 Asm.getSubsectionsViaSymbols());
896 uint32_t Prot =
898 writeSegmentLoadCommand("", NumSections, 0, VMSize, SectionDataStart,
899 SectionDataSize, Prot, Prot);
900
901 // ... and then the section headers.
902 uint64_t RelocTableEnd = SectionDataStart + SectionDataFileSize;
903 for (const MCSection &Section : Asm) {
904 const auto &Sec = cast<MCSectionMachO>(Section);
905 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
906 unsigned NumRelocs = Relocs.size();
907 uint64_t SectionStart = SectionDataStart + getSectionAddress(&Sec);
908 unsigned Flags = Sec.getTypeAndAttributes();
909 if (Sec.hasInstructions())
911 if (!cast<MCSectionMachO>(Sec).isVirtualSection() &&
912 !isUInt<32>(SectionStart)) {
913 Asm.getContext().reportError(
914 SMLoc(), "cannot encode offset of section; object file too large");
915 return NumBytesWritten();
916 }
917 if (NumRelocs && !isUInt<32>(RelocTableEnd)) {
918 Asm.getContext().reportError(
919 SMLoc(),
920 "cannot encode offset of relocations; object file too large");
921 return NumBytesWritten();
922 }
923 writeSection(Asm, Sec, getSectionAddress(&Sec), SectionStart, Flags,
924 RelocTableEnd, NumRelocs);
925 RelocTableEnd += NumRelocs * sizeof(MachO::any_relocation_info);
926 }
927
928 // Write out the deployment target information, if it's available.
929 auto EmitDeploymentTargetVersion =
930 [&](const MCAssembler::VersionInfoType &VersionInfo) {
931 auto EncodeVersion = [](VersionTuple V) -> uint32_t {
932 assert(!V.empty() && "empty version");
933 unsigned Update = V.getSubminor().value_or(0);
934 unsigned Minor = V.getMinor().value_or(0);
935 assert(Update < 256 && "unencodable update target version");
936 assert(Minor < 256 && "unencodable minor target version");
937 assert(V.getMajor() < 65536 && "unencodable major target version");
938 return Update | (Minor << 8) | (V.getMajor() << 16);
939 };
940 uint32_t EncodedVersion = EncodeVersion(VersionTuple(
941 VersionInfo.Major, VersionInfo.Minor, VersionInfo.Update));
942 uint32_t SDKVersion = !VersionInfo.SDKVersion.empty()
943 ? EncodeVersion(VersionInfo.SDKVersion)
944 : 0;
945 if (VersionInfo.EmitBuildVersion) {
946 // FIXME: Currently empty tools. Add clang version in the future.
947 W.write<uint32_t>(MachO::LC_BUILD_VERSION);
949 W.write<uint32_t>(VersionInfo.TypeOrPlatform.Platform);
950 W.write<uint32_t>(EncodedVersion);
951 W.write<uint32_t>(SDKVersion);
952 W.write<uint32_t>(0); // Empty tools list.
953 } else {
955 getLCFromMCVM(VersionInfo.TypeOrPlatform.Type);
956 W.write<uint32_t>(LCType);
958 W.write<uint32_t>(EncodedVersion);
959 W.write<uint32_t>(SDKVersion);
960 }
961 };
962 if (VersionInfo.Major != 0)
963 EmitDeploymentTargetVersion(VersionInfo);
964 if (TargetVariantVersionInfo.Major != 0)
965 EmitDeploymentTargetVersion(TargetVariantVersionInfo);
966
967 // Write the data-in-code load command, if used.
968 uint64_t DataInCodeTableEnd = RelocTableEnd + NumDataRegions * 8;
969 if (NumDataRegions) {
970 uint64_t DataRegionsOffset = RelocTableEnd;
971 uint64_t DataRegionsSize = NumDataRegions * 8;
972 writeLinkeditLoadCommand(MachO::LC_DATA_IN_CODE, DataRegionsOffset,
973 DataRegionsSize);
974 }
975
976 // Write the loh load command, if used.
977 uint64_t LOHTableEnd = DataInCodeTableEnd + LOHSize;
978 if (LOHSize)
979 writeLinkeditLoadCommand(MachO::LC_LINKER_OPTIMIZATION_HINT,
980 DataInCodeTableEnd, LOHSize);
981
982 // Write the symbol table load command, if used.
983 if (NumSymbols) {
984 unsigned FirstLocalSymbol = 0;
985 unsigned NumLocalSymbols = LocalSymbolData.size();
986 unsigned FirstExternalSymbol = FirstLocalSymbol + NumLocalSymbols;
987 unsigned NumExternalSymbols = ExternalSymbolData.size();
988 unsigned FirstUndefinedSymbol = FirstExternalSymbol + NumExternalSymbols;
989 unsigned NumUndefinedSymbols = UndefinedSymbolData.size();
990 unsigned NumIndirectSymbols = IndirectSymbols.size();
991 unsigned NumSymTabSymbols =
992 NumLocalSymbols + NumExternalSymbols + NumUndefinedSymbols;
993 uint64_t IndirectSymbolSize = NumIndirectSymbols * 4;
994 uint64_t IndirectSymbolOffset = 0;
995
996 // If used, the indirect symbols are written after the section data.
997 if (NumIndirectSymbols)
998 IndirectSymbolOffset = LOHTableEnd;
999
1000 // The symbol table is written after the indirect symbol data.
1001 uint64_t SymbolTableOffset = LOHTableEnd + IndirectSymbolSize;
1002
1003 // The string table is written after symbol table.
1004 uint64_t StringTableOffset =
1005 SymbolTableOffset + NumSymTabSymbols * (is64Bit() ?
1006 sizeof(MachO::nlist_64) :
1007 sizeof(MachO::nlist));
1008 writeSymtabLoadCommand(SymbolTableOffset, NumSymTabSymbols,
1009 StringTableOffset, StringTable.getSize());
1010
1011 writeDysymtabLoadCommand(FirstLocalSymbol, NumLocalSymbols,
1012 FirstExternalSymbol, NumExternalSymbols,
1013 FirstUndefinedSymbol, NumUndefinedSymbols,
1014 IndirectSymbolOffset, NumIndirectSymbols);
1015 }
1016
1017 // Write the linker options load commands.
1018 for (const auto &Option : Asm.getLinkerOptions())
1020
1021 // Write the actual section data.
1022 for (const MCSection &Sec : Asm) {
1023 Asm.writeSectionData(W.OS, &Sec);
1024
1025 uint64_t Pad = getPaddingSize(Asm, &Sec);
1026 W.OS.write_zeros(Pad);
1027 }
1028
1029 // Write the extra padding.
1030 W.OS.write_zeros(SectionDataPadding);
1031
1032 // Write the relocation entries.
1033 for (const MCSection &Sec : Asm) {
1034 // Write the section relocation entries, in reverse order to match 'as'
1035 // (approximately, the exact algorithm is more complicated than this).
1036 std::vector<RelAndSymbol> &Relocs = Relocations[&Sec];
1037 for (const RelAndSymbol &Rel : llvm::reverse(Relocs)) {
1038 W.write<uint32_t>(Rel.MRE.r_word0);
1039 W.write<uint32_t>(Rel.MRE.r_word1);
1040 }
1041 }
1042
1043 // Write out the data-in-code region payload, if there is one.
1044 for (DataRegionData Data : DataRegions) {
1045 uint64_t Start = getSymbolAddress(*Data.Start, Asm);
1046 uint64_t End;
1047 if (Data.End)
1048 End = getSymbolAddress(*Data.End, Asm);
1049 else
1050 report_fatal_error("Data region not terminated");
1051
1052 LLVM_DEBUG(dbgs() << "data in code region-- kind: " << Data.Kind
1053 << " start: " << Start << "(" << Data.Start->getName()
1054 << ")" << " end: " << End << "(" << Data.End->getName()
1055 << ")" << " size: " << End - Start << "\n");
1056 W.write<uint32_t>(Start);
1057 W.write<uint16_t>(End - Start);
1058 W.write<uint16_t>(Data.Kind);
1059 }
1060
1061 // Write out the loh commands, if there is one.
1062 if (LOHSize) {
1063#ifndef NDEBUG
1064 unsigned Start = W.OS.tell();
1065#endif
1066 Asm.getLOHContainer().emit(Asm, *this);
1067 // Pad to a multiple of the pointer size.
1069 offsetToAlignment(LOHRawSize, is64Bit() ? Align(8) : Align(4)));
1070 assert(W.OS.tell() - Start == LOHSize);
1071 }
1072
1073 // Write the symbol table data, if used.
1074 if (NumSymbols) {
1075 // Write the indirect symbol entries.
1076 for (auto &ISD : IndirectSymbols) {
1077 // Indirect symbols in the non-lazy symbol pointer section have some
1078 // special handling.
1079 const MCSectionMachO &Section =
1080 static_cast<const MCSectionMachO &>(*ISD.Section);
1081 if (Section.getType() == MachO::S_NON_LAZY_SYMBOL_POINTERS) {
1082 // If this symbol is defined and internal, mark it as such.
1083 if (ISD.Symbol->isDefined() && !ISD.Symbol->isExternal()) {
1085 if (ISD.Symbol->isAbsolute())
1087 W.write<uint32_t>(Flags);
1088 continue;
1089 }
1090 }
1091
1092 W.write<uint32_t>(ISD.Symbol->getIndex());
1093 }
1094
1095 // FIXME: Check that offsets match computed ones.
1096
1097 // Write the symbol table entries.
1098 for (auto *SymbolData :
1099 {&LocalSymbolData, &ExternalSymbolData, &UndefinedSymbolData})
1100 for (MachSymbolData &Entry : *SymbolData)
1101 writeNlist(Entry, Asm);
1102
1103 // Write the string table.
1104 StringTable.write(W.OS);
1105 }
1106
1107 return NumBytesWritten();
1108}
1109
1110std::unique_ptr<MCObjectWriter>
1111llvm::createMachObjectWriter(std::unique_ptr<MCMachObjectTargetWriter> MOTW,
1112 raw_pwrite_stream &OS, bool IsLittleEndian) {
1113 return std::make_unique<MachObjectWriter>(std::move(MOTW), OS,
1114 IsLittleEndian);
1115}
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:480
Symbol * Sym
Definition: ELF_riscv.cpp:479
static LVOptions Options
Definition: LVOptions.cpp:25
static unsigned ComputeLinkerOptionsLoadCommandSize(const std::vector< std::string > &Options, bool is64Bit)
static bool isFixupTargetValid(const MCValue &Target)
static MachO::LoadCommandType getLCFromMCVM(MCVersionMinType Type)
static bool isSymbolLinkerVisible(const MCSymbol &Symbol)
PowerPC TLS Dynamic Call Fixup
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
static bool is64Bit(const char *name)
Value * RHS
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: DenseMap.h:202
static bool isSectionAtomizableBySymbols(const MCSection &Section)
True if the section is atomized using the symbols in it.
{ bool EmitBuildVersion VersionInfoType
MachO specific deployment target version info.
Definition: MCAssembler.h:66
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
bool evaluateAsRelocatable(MCValue &Res, const MCAssembler *Asm, const MCFixup *Fixup) const
Try to evaluate the expression to a relocatable value, i.e.
Definition: MCExpr.cpp:789
Encode information on a single operation to perform on a byte sequence (e.g., an encoded instruction)...
Definition: MCFixup.h:71
const MCSymbol * getAtom() const
Definition: MCFragment.cpp:85
MCSection * getParent() const
Definition: MCFragment.h:93
std::vector< const MCSymbol * > & getAddrsigSyms()
virtual void reset()
lifetime management
This represents a section on a Mach-O system (used by Mac OS X).
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
Align getAlign() const
Definition: MCSection.h:146
bool isVirtualSection() const
Check whether this section is "virtual", that is has no actual object file contents.
Definition: MCSection.h:198
iterator begin() const
Definition: MCSection.h:182
const MCSymbol & getSymbol() const
Definition: MCExpr.h:406
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
const MCExpr * getVariableValue(bool SetUsed=true) const
getVariableValue - Get the value for variable symbols.
Definition: MCSymbol.h:305
bool isInSection() const
isInSection - Check if this symbol is defined in some section (i.e., it is defined but not absolute).
Definition: MCSymbol.h:254
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
bool isVariable() const
isVariable - Check if this is a variable symbol.
Definition: MCSymbol.h:300
bool isUndefined(bool SetUsed=true) const
isUndefined - Check if this symbol undefined (i.e., implicitly defined).
Definition: MCSymbol.h:259
uint32_t getIndex() const
Get the (implementation defined) index.
Definition: MCSymbol.h:316
MCSection & getSection() const
Get the section associated with a defined, non-absolute symbol.
Definition: MCSymbol.h:269
bool isTemporary() const
isTemporary - Check if this is an assembler temporary symbol.
Definition: MCSymbol.h:222
MCFragment * getFragment(bool SetUsed=true) const
Definition: MCSymbol.h:397
This represents an "assembler immediate".
Definition: MCValue.h:36
uint64_t getPaddingSize(const MCAssembler &Asm, const MCSection *SD) const
void computeSectionAddresses(const MCAssembler &Asm)
void writeSection(const MCAssembler &Asm, const MCSection &Sec, uint64_t VMAddr, uint64_t FileOffset, unsigned Flags, uint64_t RelocationsStart, unsigned NumRelocations)
bool doesSymbolRequireExternRelocation(const MCSymbol &S)
void computeSymbolTable(MCAssembler &Asm, std::vector< MachSymbolData > &LocalSymbolData, std::vector< MachSymbolData > &ExternalSymbolData, std::vector< MachSymbolData > &UndefinedSymbolData)
Compute the symbol table data.
uint64_t getFragmentAddress(const MCAssembler &Asm, const MCFragment *Fragment) const
void executePostLayoutBinding(MCAssembler &Asm) override
Perform any late binding of symbols (for example, to assign symbol indices for use when generating re...
uint64_t getSectionAddress(const MCSection *Sec) const
void addRelocation(const MCSymbol *RelSymbol, const MCSection *Sec, MachO::any_relocation_info &MRE)
void populateAddrSigSection(MCAssembler &Asm)
bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind)
support::endian::Writer W
void writeLinkerOptionsLoadCommand(const std::vector< std::string > &Options)
void recordRelocation(MCAssembler &Asm, const MCFragment *Fragment, const MCFixup &Fixup, MCValue Target, uint64_t &FixedValue) override
Record a relocation entry.
void writeNlist(MachSymbolData &MSD, const MCAssembler &Asm)
bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB, bool InSet, bool IsPCRel) const override
void writeDysymtabLoadCommand(uint32_t FirstLocalSymbol, uint32_t NumLocalSymbols, uint32_t FirstExternalSymbol, uint32_t NumExternalSymbols, uint32_t FirstUndefinedSymbol, uint32_t NumUndefinedSymbols, uint32_t IndirectSymbolOffset, uint32_t NumIndirectSymbols)
const MCSymbol & findAliasedSymbol(const MCSymbol &Sym) const
uint64_t getSymbolAddress(const MCSymbol &S, const MCAssembler &Asm) const
void writeSegmentLoadCommand(StringRef Name, unsigned NumSections, uint64_t VMAddr, uint64_t VMSize, uint64_t SectionDataStartOffset, uint64_t SectionDataSize, uint32_t MaxProt, uint32_t InitProt)
Write a segment load command.
const MCSymbol * getAtom(const MCSymbol &S) const
void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset, uint32_t DataSize)
void writeHeader(MachO::HeaderFileType Type, unsigned NumLoadCommands, unsigned LoadCommandsSize, bool SubsectionsViaSymbols)
void reset() override
lifetime management
void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols, uint32_t StringTableOffset, uint32_t StringTableSize)
void bindIndirectSymbols(MCAssembler &Asm)
uint64_t writeObject(MCAssembler &Asm) override
Write the object file and returns the number of bytes written.
Represents a location in source code.
Definition: SMLoc.h:23
static SectionKind getMetadata()
Definition: SectionKind.h:188
size_t size() const
Definition: SmallVector.h:91
void push_back(const T &Elt)
Definition: SmallVector.h:426
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
Target - Wrapper for Target specific information.
const char * getName() const
getName - Get the target name.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:29
raw_ostream & write_zeros(unsigned NumZeros)
write_zeros - Insert 'NumZeros' nulls.
uint64_t tell() const
tell - Return the current offset with the file.
Definition: raw_ostream.h:147
An abstract base class for streams implementations that also support a pwrite operation.
Definition: raw_ostream.h:434
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ S_ATTR_SOME_INSTRUCTIONS
S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions.
Definition: MachO.h:213
@ INDIRECT_SYMBOL_ABS
Definition: MachO.h:222
@ INDIRECT_SYMBOL_LOCAL
Definition: MachO.h:221
@ N_PEXT
Definition: MachO.h:308
@ MH_SUBSECTIONS_VIA_SYMBOLS
Definition: MachO.h:73
HeaderFileType
Definition: MachO.h:40
@ MH_OBJECT
Definition: MachO.h:43
@ S_THREAD_LOCAL_VARIABLE_POINTERS
S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread local structures.
Definition: MachO.h:175
@ S_LAZY_SYMBOL_POINTERS
S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers.
Definition: MachO.h:141
@ S_NON_LAZY_SYMBOL_POINTERS
S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers.
Definition: MachO.h:139
@ S_SYMBOL_STUBS
S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in the Reserved2 field.
Definition: MachO.h:144
@ VM_PROT_EXECUTE
Definition: MachO.h:497
@ VM_PROT_READ
Definition: MachO.h:497
@ VM_PROT_WRITE
Definition: MachO.h:497
@ MH_MAGIC
Definition: MachO.h:30
@ MH_MAGIC_64
Definition: MachO.h:32
@ N_SECT
Definition: MachO.h:318
@ N_INDR
Definition: MachO.h:320
@ N_UNDF
Definition: MachO.h:316
@ GENERIC_RELOC_VANILLA
Definition: MachO.h:410
LoadCommandType
Definition: MachO.h:98
void write(void *memory, value_type value, endianness endian)
Write a value to memory with a particular endianness.
Definition: Endian.h:92
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are are tuples (A,...
Definition: STLExtras.h:2400
std::unique_ptr< MCObjectWriter > createMachObjectWriter(std::unique_ptr< MCMachObjectTargetWriter > MOTW, raw_pwrite_stream &OS, bool IsLittleEndian)
Construct a new Mach-O writer instance.
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
MCVersionMinType
Definition: MCDirectives.h:69
@ MCVM_WatchOSVersionMin
.watchos_version_min
Definition: MCDirectives.h:73
@ MCVM_OSXVersionMin
.macosx_version_min
Definition: MCDirectives.h:71
@ MCVM_TvOSVersionMin
.tvos_version_min
Definition: MCDirectives.h:72
@ MCVM_IOSVersionMin
.ios_version_min
Definition: MCDirectives.h:70
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
MCFixupKind
Extensible enumeration to represent the type of a fixup.
Definition: MCFixup.h:21
uint64_t offsetToAlignment(uint64_t Value, Align Alignment)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: Alignment.h:197
@ Ref
The access may reference the value stored in memory.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition: Alignment.h:155
unsigned Log2(Align A)
Returns the log2 of the alignment.
Definition: Alignment.h:208
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
const MCSymbolRefExpr * From
Definition: MCAssembler.h:353
const MCSymbolRefExpr * To
Definition: MCAssembler.h:354
Target independent information on a fixup kind.
@ FKF_IsPCRel
Is this fixup kind PCrelative? This is used by the assembler backend to evaluate fixup values in a ta...
unsigned Flags
Flags describing additional information on this fixup kind.
void write(ArrayRef< value_type > Val)
Definition: EndianStream.h:71