xref: /llvm-project/llvm/lib/MC/XCOFFObjectWriter.cpp (revision a03a6e99647318a86ea398c42e241da43e3c550e)
1 //===-- lib/MC/XCOFFObjectWriter.cpp - XCOFF 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 // This file implements XCOFF object file writer information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/BinaryFormat/XCOFF.h"
14 #include "llvm/MC/MCAsmBackend.h"
15 #include "llvm/MC/MCAsmLayout.h"
16 #include "llvm/MC/MCAssembler.h"
17 #include "llvm/MC/MCFixup.h"
18 #include "llvm/MC/MCFixupKindInfo.h"
19 #include "llvm/MC/MCObjectWriter.h"
20 #include "llvm/MC/MCSectionXCOFF.h"
21 #include "llvm/MC/MCSymbolXCOFF.h"
22 #include "llvm/MC/MCValue.h"
23 #include "llvm/MC/MCXCOFFObjectWriter.h"
24 #include "llvm/MC/StringTableBuilder.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/EndianStream.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MathExtras.h"
29 
30 #include <deque>
31 #include <map>
32 
33 using namespace llvm;
34 
35 // An XCOFF object file has a limited set of predefined sections. The most
36 // important ones for us (right now) are:
37 // .text --> contains program code and read-only data.
38 // .data --> contains initialized data, function descriptors, and the TOC.
39 // .bss  --> contains uninitialized data.
40 // Each of these sections is composed of 'Control Sections'. A Control Section
41 // is more commonly referred to as a csect. A csect is an indivisible unit of
42 // code or data, and acts as a container for symbols. A csect is mapped
43 // into a section based on its storage-mapping class, with the exception of
44 // XMC_RW which gets mapped to either .data or .bss based on whether it's
45 // explicitly initialized or not.
46 //
47 // We don't represent the sections in the MC layer as there is nothing
48 // interesting about them at at that level: they carry information that is
49 // only relevant to the ObjectWriter, so we materialize them in this class.
50 namespace {
51 
52 constexpr unsigned DefaultSectionAlign = 4;
53 constexpr int16_t MaxSectionIndex = INT16_MAX;
54 
55 // Packs the csect's alignment and type into a byte.
56 uint8_t getEncodedType(const MCSectionXCOFF *);
57 
58 struct XCOFFRelocation {
59   uint32_t SymbolTableIndex;
60   uint32_t FixupOffsetInCsect;
61   uint8_t SignAndSize;
62   uint8_t Type;
63 };
64 
65 // Wrapper around an MCSymbolXCOFF.
66 struct Symbol {
67   const MCSymbolXCOFF *const MCSym;
68   uint32_t SymbolTableIndex;
69 
70   XCOFF::VisibilityType getVisibilityType() const {
71     return MCSym->getVisibilityType();
72   }
73 
74   XCOFF::StorageClass getStorageClass() const {
75     return MCSym->getStorageClass();
76   }
77   StringRef getSymbolTableName() const { return MCSym->getSymbolTableName(); }
78   Symbol(const MCSymbolXCOFF *MCSym) : MCSym(MCSym), SymbolTableIndex(-1) {}
79 };
80 
81 // Wrapper for an MCSectionXCOFF.
82 // It can be a Csect or debug section or DWARF section and so on.
83 struct XCOFFSection {
84   const MCSectionXCOFF *const MCSec;
85   uint32_t SymbolTableIndex;
86   uint64_t Address;
87   uint64_t Size;
88 
89   SmallVector<Symbol, 1> Syms;
90   SmallVector<XCOFFRelocation, 1> Relocations;
91   StringRef getSymbolTableName() const { return MCSec->getSymbolTableName(); }
92   XCOFF::VisibilityType getVisibilityType() const {
93     return MCSec->getVisibilityType();
94   }
95   XCOFFSection(const MCSectionXCOFF *MCSec)
96       : MCSec(MCSec), SymbolTableIndex(-1), Address(-1), Size(0) {}
97 };
98 
99 // Type to be used for a container representing a set of csects with
100 // (approximately) the same storage mapping class. For example all the csects
101 // with a storage mapping class of `xmc_pr` will get placed into the same
102 // container.
103 using CsectGroup = std::deque<XCOFFSection>;
104 using CsectGroups = std::deque<CsectGroup *>;
105 
106 // The basic section entry defination. This Section represents a section entry
107 // in XCOFF section header table.
108 struct SectionEntry {
109   char Name[XCOFF::NameSize];
110   // The physical/virtual address of the section. For an object file these
111   // values are equivalent, except for in the overflow section header, where
112   // the physical address specifies the number of relocation entries and the
113   // virtual address specifies the number of line number entries.
114   // TODO: Divide Address into PhysicalAddress and VirtualAddress when line
115   // number entries are supported.
116   uint64_t Address;
117   uint64_t Size;
118   uint64_t FileOffsetToData;
119   uint64_t FileOffsetToRelocations;
120   uint32_t RelocationCount;
121   int32_t Flags;
122 
123   int16_t Index;
124 
125   virtual uint64_t advanceFileOffset(const uint64_t MaxRawDataSize,
126                                      const uint64_t RawPointer) {
127     FileOffsetToData = RawPointer;
128     uint64_t NewPointer = RawPointer + Size;
129     if (NewPointer > MaxRawDataSize)
130       report_fatal_error("Section raw data overflowed this object file.");
131     return NewPointer;
132   }
133 
134   // XCOFF has special section numbers for symbols:
135   // -2 Specifies N_DEBUG, a special symbolic debugging symbol.
136   // -1 Specifies N_ABS, an absolute symbol. The symbol has a value but is not
137   // relocatable.
138   //  0 Specifies N_UNDEF, an undefined external symbol.
139   // Therefore, we choose -3 (N_DEBUG - 1) to represent a section index that
140   // hasn't been initialized.
141   static constexpr int16_t UninitializedIndex =
142       XCOFF::ReservedSectionNum::N_DEBUG - 1;
143 
144   SectionEntry(StringRef N, int32_t Flags)
145       : Name(), Address(0), Size(0), FileOffsetToData(0),
146         FileOffsetToRelocations(0), RelocationCount(0), Flags(Flags),
147         Index(UninitializedIndex) {
148     assert(N.size() <= XCOFF::NameSize && "section name too long");
149     memcpy(Name, N.data(), N.size());
150   }
151 
152   virtual void reset() {
153     Address = 0;
154     Size = 0;
155     FileOffsetToData = 0;
156     FileOffsetToRelocations = 0;
157     RelocationCount = 0;
158     Index = UninitializedIndex;
159   }
160 
161   virtual ~SectionEntry() = default;
162 };
163 
164 // Represents the data related to a section excluding the csects that make up
165 // the raw data of the section. The csects are stored separately as not all
166 // sections contain csects, and some sections contain csects which are better
167 // stored separately, e.g. the .data section containing read-write, descriptor,
168 // TOCBase and TOC-entry csects.
169 struct CsectSectionEntry : public SectionEntry {
170   // Virtual sections do not need storage allocated in the object file.
171   const bool IsVirtual;
172 
173   // This is a section containing csect groups.
174   CsectGroups Groups;
175 
176   CsectSectionEntry(StringRef N, XCOFF::SectionTypeFlags Flags, bool IsVirtual,
177                     CsectGroups Groups)
178       : SectionEntry(N, Flags), IsVirtual(IsVirtual), Groups(Groups) {
179     assert(N.size() <= XCOFF::NameSize && "section name too long");
180     memcpy(Name, N.data(), N.size());
181   }
182 
183   void reset() override {
184     SectionEntry::reset();
185     // Clear any csects we have stored.
186     for (auto *Group : Groups)
187       Group->clear();
188   }
189 
190   virtual ~CsectSectionEntry() = default;
191 };
192 
193 struct DwarfSectionEntry : public SectionEntry {
194   // For DWARF section entry.
195   std::unique_ptr<XCOFFSection> DwarfSect;
196 
197   // For DWARF section, we must use real size in the section header. MemorySize
198   // is for the size the DWARF section occupies including paddings.
199   uint32_t MemorySize;
200 
201   // TODO: Remove this override. Loadable sections (e.g., .text, .data) may need
202   // to be aligned. Other sections generally don't need any alignment, but if
203   // they're aligned, the RawPointer should be adjusted before writing the
204   // section. Then a dwarf-specific function wouldn't be needed.
205   uint64_t advanceFileOffset(const uint64_t MaxRawDataSize,
206                              const uint64_t RawPointer) override {
207     FileOffsetToData = RawPointer;
208     uint64_t NewPointer = RawPointer + MemorySize;
209     assert(NewPointer <= MaxRawDataSize &&
210            "Section raw data overflowed this object file.");
211     return NewPointer;
212   }
213 
214   DwarfSectionEntry(StringRef N, int32_t Flags,
215                     std::unique_ptr<XCOFFSection> Sect)
216       : SectionEntry(N, Flags | XCOFF::STYP_DWARF), DwarfSect(std::move(Sect)),
217         MemorySize(0) {
218     assert(DwarfSect->MCSec->isDwarfSect() &&
219            "This should be a DWARF section!");
220     assert(N.size() <= XCOFF::NameSize && "section name too long");
221     memcpy(Name, N.data(), N.size());
222   }
223 
224   DwarfSectionEntry(DwarfSectionEntry &&s) = default;
225 
226   virtual ~DwarfSectionEntry() = default;
227 };
228 
229 struct ExceptionTableEntry {
230   const MCSymbol *Trap;
231   uint64_t TrapAddress = ~0ul;
232   unsigned Lang;
233   unsigned Reason;
234 
235   ExceptionTableEntry(const MCSymbol *Trap, unsigned Lang, unsigned Reason)
236       : Trap(Trap), Lang(Lang), Reason(Reason) {}
237 };
238 
239 struct ExceptionInfo {
240   const MCSymbol *FunctionSymbol;
241   unsigned FunctionSize;
242   std::vector<ExceptionTableEntry> Entries;
243 };
244 
245 struct ExceptionSectionEntry : public SectionEntry {
246   std::map<const StringRef, ExceptionInfo> ExceptionTable;
247   bool isDebugEnabled = false;
248 
249   ExceptionSectionEntry(StringRef N, int32_t Flags)
250       : SectionEntry(N, Flags | XCOFF::STYP_EXCEPT) {
251     assert(N.size() <= XCOFF::NameSize && "Section too long.");
252     memcpy(Name, N.data(), N.size());
253   }
254 
255   virtual ~ExceptionSectionEntry() = default;
256 };
257 
258 struct CInfoSymInfo {
259   // Name of the C_INFO symbol associated with the section
260   std::string Name;
261   std::string Metadata;
262   // Offset into the start of the metadata in the section
263   uint64_t Offset;
264 
265   CInfoSymInfo(std::string Name, std::string Metadata)
266       : Name(Name), Metadata(Metadata) {}
267   // Metadata needs to be padded out to an even word size.
268   uint32_t paddingSize() const {
269     return alignTo(Metadata.size(), sizeof(uint32_t)) - Metadata.size();
270   };
271 
272   // Total size of the entry, including the 4 byte length
273   uint32_t size() const {
274     return Metadata.size() + paddingSize() + sizeof(uint32_t);
275   };
276 };
277 
278 struct CInfoSymSectionEntry : public SectionEntry {
279   std::unique_ptr<CInfoSymInfo> Entry;
280 
281   CInfoSymSectionEntry(StringRef N, int32_t Flags) : SectionEntry(N, Flags) {}
282   virtual ~CInfoSymSectionEntry() = default;
283   void addEntry(std::unique_ptr<CInfoSymInfo> NewEntry) {
284     Entry = std::move(NewEntry);
285     Entry->Offset = sizeof(uint32_t);
286     Size += Entry->size();
287   }
288   void reset() override {
289     SectionEntry::reset();
290     Entry.reset();
291   }
292 };
293 
294 class XCOFFObjectWriter : public MCObjectWriter {
295 
296   uint32_t SymbolTableEntryCount = 0;
297   uint64_t SymbolTableOffset = 0;
298   uint16_t SectionCount = 0;
299   uint32_t PaddingsBeforeDwarf = 0;
300   std::vector<std::pair<std::string, size_t>> FileNames;
301   bool HasVisibility = false;
302 
303   support::endian::Writer W;
304   std::unique_ptr<MCXCOFFObjectTargetWriter> TargetObjectWriter;
305   StringTableBuilder Strings;
306 
307   const uint64_t MaxRawDataSize =
308       TargetObjectWriter->is64Bit() ? UINT64_MAX : UINT32_MAX;
309 
310   // Maps the MCSection representation to its corresponding XCOFFSection
311   // wrapper. Needed for finding the XCOFFSection to insert an MCSymbol into
312   // from its containing MCSectionXCOFF.
313   DenseMap<const MCSectionXCOFF *, XCOFFSection *> SectionMap;
314 
315   // Maps the MCSymbol representation to its corrresponding symbol table index.
316   // Needed for relocation.
317   DenseMap<const MCSymbol *, uint32_t> SymbolIndexMap;
318 
319   // CsectGroups. These store the csects which make up different parts of
320   // the sections. Should have one for each set of csects that get mapped into
321   // the same section and get handled in a 'similar' way.
322   CsectGroup UndefinedCsects;
323   CsectGroup ProgramCodeCsects;
324   CsectGroup ReadOnlyCsects;
325   CsectGroup DataCsects;
326   CsectGroup FuncDSCsects;
327   CsectGroup TOCCsects;
328   CsectGroup BSSCsects;
329   CsectGroup TDataCsects;
330   CsectGroup TBSSCsects;
331 
332   // The Predefined sections.
333   CsectSectionEntry Text;
334   CsectSectionEntry Data;
335   CsectSectionEntry BSS;
336   CsectSectionEntry TData;
337   CsectSectionEntry TBSS;
338 
339   // All the XCOFF sections, in the order they will appear in the section header
340   // table.
341   std::array<CsectSectionEntry *const, 5> Sections{
342       {&Text, &Data, &BSS, &TData, &TBSS}};
343 
344   std::vector<DwarfSectionEntry> DwarfSections;
345   std::vector<SectionEntry> OverflowSections;
346 
347   ExceptionSectionEntry ExceptionSection;
348   CInfoSymSectionEntry CInfoSymSection;
349 
350   CsectGroup &getCsectGroup(const MCSectionXCOFF *MCSec);
351 
352   void reset() override;
353 
354   void executePostLayoutBinding(MCAssembler &, const MCAsmLayout &) override;
355 
356   void recordRelocation(MCAssembler &, const MCAsmLayout &, const MCFragment *,
357                         const MCFixup &, MCValue, uint64_t &) override;
358 
359   uint64_t writeObject(MCAssembler &, const MCAsmLayout &) override;
360 
361   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
362   bool nameShouldBeInStringTable(const StringRef &);
363   void writeSymbolName(const StringRef &);
364 
365   void writeSymbolEntryForCsectMemberLabel(const Symbol &SymbolRef,
366                                            const XCOFFSection &CSectionRef,
367                                            int16_t SectionIndex,
368                                            uint64_t SymbolOffset);
369   void writeSymbolEntryForControlSection(const XCOFFSection &CSectionRef,
370                                          int16_t SectionIndex,
371                                          XCOFF::StorageClass StorageClass);
372   void writeSymbolEntryForDwarfSection(const XCOFFSection &DwarfSectionRef,
373                                        int16_t SectionIndex);
374   void writeFileHeader();
375   void writeAuxFileHeader();
376   void writeSectionHeader(const SectionEntry *Sec);
377   void writeSectionHeaderTable();
378   void writeSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
379   void writeSectionForControlSectionEntry(const MCAssembler &Asm,
380                                           const MCAsmLayout &Layout,
381                                           const CsectSectionEntry &CsectEntry,
382                                           uint64_t &CurrentAddressLocation);
383   void writeSectionForDwarfSectionEntry(const MCAssembler &Asm,
384                                         const MCAsmLayout &Layout,
385                                         const DwarfSectionEntry &DwarfEntry,
386                                         uint64_t &CurrentAddressLocation);
387   void writeSectionForExceptionSectionEntry(
388       const MCAssembler &Asm, const MCAsmLayout &Layout,
389       ExceptionSectionEntry &ExceptionEntry, uint64_t &CurrentAddressLocation);
390   void writeSectionForCInfoSymSectionEntry(const MCAssembler &Asm,
391                                            const MCAsmLayout &Layout,
392                                            CInfoSymSectionEntry &CInfoSymEntry,
393                                            uint64_t &CurrentAddressLocation);
394   void writeSymbolTable(const MCAsmLayout &Layout);
395   void writeSymbolAuxDwarfEntry(uint64_t LengthOfSectionPortion,
396                                 uint64_t NumberOfRelocEnt = 0);
397   void writeSymbolAuxCsectEntry(uint64_t SectionOrLength,
398                                 uint8_t SymbolAlignmentAndType,
399                                 uint8_t StorageMappingClass);
400   void writeSymbolAuxFunctionEntry(uint32_t EntryOffset, uint32_t FunctionSize,
401                                    uint64_t LineNumberPointer,
402                                    uint32_t EndIndex);
403   void writeSymbolAuxExceptionEntry(uint64_t EntryOffset, uint32_t FunctionSize,
404                                     uint32_t EndIndex);
405   void writeSymbolEntry(StringRef SymbolName, uint64_t Value,
406                         int16_t SectionNumber, uint16_t SymbolType,
407                         uint8_t StorageClass, uint8_t NumberOfAuxEntries = 1);
408   void writeRelocations();
409   void writeRelocation(XCOFFRelocation Reloc, const XCOFFSection &Section);
410 
411   // Called after all the csects and symbols have been processed by
412   // `executePostLayoutBinding`, this function handles building up the majority
413   // of the structures in the object file representation. Namely:
414   // *) Calculates physical/virtual addresses, raw-pointer offsets, and section
415   //    sizes.
416   // *) Assigns symbol table indices.
417   // *) Builds up the section header table by adding any non-empty sections to
418   //    `Sections`.
419   void assignAddressesAndIndices(const MCAsmLayout &);
420   // Called after relocations are recorded.
421   void finalizeSectionInfo();
422   void finalizeRelocationInfo(SectionEntry *Sec, uint64_t RelCount);
423   void calcOffsetToRelocations(SectionEntry *Sec, uint64_t &RawPointer);
424 
425   void addExceptionEntry(const MCSymbol *Symbol, const MCSymbol *Trap,
426                          unsigned LanguageCode, unsigned ReasonCode,
427                          unsigned FunctionSize, bool hasDebug) override;
428   bool hasExceptionSection() {
429     return !ExceptionSection.ExceptionTable.empty();
430   }
431   unsigned getExceptionSectionSize();
432   unsigned getExceptionOffset(const MCSymbol *Symbol);
433 
434   void addCInfoSymEntry(StringRef Name, StringRef Metadata) override;
435   size_t auxiliaryHeaderSize() const {
436     // 64-bit object files have no auxiliary header.
437     return HasVisibility && !is64Bit() ? XCOFF::AuxFileHeaderSizeShort : 0;
438   }
439 
440 public:
441   XCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
442                     raw_pwrite_stream &OS);
443 
444   void writeWord(uint64_t Word) {
445     is64Bit() ? W.write<uint64_t>(Word) : W.write<uint32_t>(Word);
446   }
447 };
448 
449 XCOFFObjectWriter::XCOFFObjectWriter(
450     std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
451     : W(OS, llvm::endianness::big), TargetObjectWriter(std::move(MOTW)),
452       Strings(StringTableBuilder::XCOFF),
453       Text(".text", XCOFF::STYP_TEXT, /* IsVirtual */ false,
454            CsectGroups{&ProgramCodeCsects, &ReadOnlyCsects}),
455       Data(".data", XCOFF::STYP_DATA, /* IsVirtual */ false,
456            CsectGroups{&DataCsects, &FuncDSCsects, &TOCCsects}),
457       BSS(".bss", XCOFF::STYP_BSS, /* IsVirtual */ true,
458           CsectGroups{&BSSCsects}),
459       TData(".tdata", XCOFF::STYP_TDATA, /* IsVirtual */ false,
460             CsectGroups{&TDataCsects}),
461       TBSS(".tbss", XCOFF::STYP_TBSS, /* IsVirtual */ true,
462            CsectGroups{&TBSSCsects}),
463       ExceptionSection(".except", XCOFF::STYP_EXCEPT),
464       CInfoSymSection(".info", XCOFF::STYP_INFO) {}
465 
466 void XCOFFObjectWriter::reset() {
467   // Clear the mappings we created.
468   SymbolIndexMap.clear();
469   SectionMap.clear();
470 
471   UndefinedCsects.clear();
472   // Reset any sections we have written to, and empty the section header table.
473   for (auto *Sec : Sections)
474     Sec->reset();
475   for (auto &DwarfSec : DwarfSections)
476     DwarfSec.reset();
477   for (auto &OverflowSec : OverflowSections)
478     OverflowSec.reset();
479   ExceptionSection.reset();
480   CInfoSymSection.reset();
481 
482   // Reset states in XCOFFObjectWriter.
483   SymbolTableEntryCount = 0;
484   SymbolTableOffset = 0;
485   SectionCount = 0;
486   PaddingsBeforeDwarf = 0;
487   Strings.clear();
488 
489   MCObjectWriter::reset();
490 }
491 
492 CsectGroup &XCOFFObjectWriter::getCsectGroup(const MCSectionXCOFF *MCSec) {
493   switch (MCSec->getMappingClass()) {
494   case XCOFF::XMC_PR:
495     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
496            "Only an initialized csect can contain program code.");
497     return ProgramCodeCsects;
498   case XCOFF::XMC_RO:
499     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
500            "Only an initialized csect can contain read only data.");
501     return ReadOnlyCsects;
502   case XCOFF::XMC_RW:
503     if (XCOFF::XTY_CM == MCSec->getCSectType())
504       return BSSCsects;
505 
506     if (XCOFF::XTY_SD == MCSec->getCSectType())
507       return DataCsects;
508 
509     report_fatal_error("Unhandled mapping of read-write csect to section.");
510   case XCOFF::XMC_DS:
511     return FuncDSCsects;
512   case XCOFF::XMC_BS:
513     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
514            "Mapping invalid csect. CSECT with bss storage class must be "
515            "common type.");
516     return BSSCsects;
517   case XCOFF::XMC_TL:
518     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
519            "Mapping invalid csect. CSECT with tdata storage class must be "
520            "an initialized csect.");
521     return TDataCsects;
522   case XCOFF::XMC_UL:
523     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
524            "Mapping invalid csect. CSECT with tbss storage class must be "
525            "an uninitialized csect.");
526     return TBSSCsects;
527   case XCOFF::XMC_TC0:
528     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
529            "Only an initialized csect can contain TOC-base.");
530     assert(TOCCsects.empty() &&
531            "We should have only one TOC-base, and it should be the first csect "
532            "in this CsectGroup.");
533     return TOCCsects;
534   case XCOFF::XMC_TC:
535   case XCOFF::XMC_TE:
536     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
537            "A TOC symbol must be an initialized csect.");
538     assert(!TOCCsects.empty() &&
539            "We should at least have a TOC-base in this CsectGroup.");
540     return TOCCsects;
541   case XCOFF::XMC_TD:
542     assert((XCOFF::XTY_SD == MCSec->getCSectType() ||
543             XCOFF::XTY_CM == MCSec->getCSectType()) &&
544            "Symbol type incompatible with toc-data.");
545     assert(!TOCCsects.empty() &&
546            "We should at least have a TOC-base in this CsectGroup.");
547     return TOCCsects;
548   default:
549     report_fatal_error("Unhandled mapping of csect to section.");
550   }
551 }
552 
553 static MCSectionXCOFF *getContainingCsect(const MCSymbolXCOFF *XSym) {
554   if (XSym->isDefined())
555     return cast<MCSectionXCOFF>(XSym->getFragment()->getParent());
556   return XSym->getRepresentedCsect();
557 }
558 
559 void XCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
560                                                  const MCAsmLayout &Layout) {
561   for (const auto &S : Asm) {
562     const auto *MCSec = cast<const MCSectionXCOFF>(&S);
563     assert(!SectionMap.contains(MCSec) && "Cannot add a section twice.");
564 
565     // If the name does not fit in the storage provided in the symbol table
566     // entry, add it to the string table.
567     if (nameShouldBeInStringTable(MCSec->getSymbolTableName()))
568       Strings.add(MCSec->getSymbolTableName());
569     if (MCSec->isCsect()) {
570       // A new control section. Its CsectSectionEntry should already be staticly
571       // generated as Text/Data/BSS/TDATA/TBSS. Add this section to the group of
572       // the CsectSectionEntry.
573       assert(XCOFF::XTY_ER != MCSec->getCSectType() &&
574              "An undefined csect should not get registered.");
575       CsectGroup &Group = getCsectGroup(MCSec);
576       Group.emplace_back(MCSec);
577       SectionMap[MCSec] = &Group.back();
578     } else if (MCSec->isDwarfSect()) {
579       // A new DwarfSectionEntry.
580       std::unique_ptr<XCOFFSection> DwarfSec =
581           std::make_unique<XCOFFSection>(MCSec);
582       SectionMap[MCSec] = DwarfSec.get();
583 
584       DwarfSectionEntry SecEntry(MCSec->getName(),
585                                  *MCSec->getDwarfSubtypeFlags(),
586                                  std::move(DwarfSec));
587       DwarfSections.push_back(std::move(SecEntry));
588     } else
589       llvm_unreachable("unsupport section type!");
590   }
591 
592   for (const MCSymbol &S : Asm.symbols()) {
593     // Nothing to do for temporary symbols.
594     if (S.isTemporary())
595       continue;
596 
597     const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(&S);
598     const MCSectionXCOFF *ContainingCsect = getContainingCsect(XSym);
599 
600     if (XSym->getVisibilityType() != XCOFF::SYM_V_UNSPECIFIED)
601       HasVisibility = true;
602 
603     if (ContainingCsect->getCSectType() == XCOFF::XTY_ER) {
604       // Handle undefined symbol.
605       UndefinedCsects.emplace_back(ContainingCsect);
606       SectionMap[ContainingCsect] = &UndefinedCsects.back();
607       if (nameShouldBeInStringTable(ContainingCsect->getSymbolTableName()))
608         Strings.add(ContainingCsect->getSymbolTableName());
609       continue;
610     }
611 
612     // If the symbol is the csect itself, we don't need to put the symbol
613     // into csect's Syms.
614     if (XSym == ContainingCsect->getQualNameSymbol())
615       continue;
616 
617     // Only put a label into the symbol table when it is an external label.
618     if (!XSym->isExternal())
619       continue;
620 
621     assert(SectionMap.contains(ContainingCsect) &&
622            "Expected containing csect to exist in map");
623     XCOFFSection *Csect = SectionMap[ContainingCsect];
624     // Lookup the containing csect and add the symbol to it.
625     assert(Csect->MCSec->isCsect() && "only csect is supported now!");
626     Csect->Syms.emplace_back(XSym);
627 
628     // If the name does not fit in the storage provided in the symbol table
629     // entry, add it to the string table.
630     if (nameShouldBeInStringTable(XSym->getSymbolTableName()))
631       Strings.add(XSym->getSymbolTableName());
632   }
633 
634   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymSection.Entry;
635   if (CISI && nameShouldBeInStringTable(CISI->Name))
636     Strings.add(CISI->Name);
637 
638   FileNames = Asm.getFileNames();
639   // Emit ".file" as the source file name when there is no file name.
640   if (FileNames.empty())
641     FileNames.emplace_back(".file", 0);
642   for (const std::pair<std::string, size_t> &F : FileNames) {
643     if (nameShouldBeInStringTable(F.first))
644       Strings.add(F.first);
645   }
646 
647   Strings.finalize();
648   assignAddressesAndIndices(Layout);
649 }
650 
651 void XCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
652                                          const MCAsmLayout &Layout,
653                                          const MCFragment *Fragment,
654                                          const MCFixup &Fixup, MCValue Target,
655                                          uint64_t &FixedValue) {
656   auto getIndex = [this](const MCSymbol *Sym,
657                          const MCSectionXCOFF *ContainingCsect) {
658     // If we could not find the symbol directly in SymbolIndexMap, this symbol
659     // could either be a temporary symbol or an undefined symbol. In this case,
660     // we would need to have the relocation reference its csect instead.
661     return SymbolIndexMap.contains(Sym)
662                ? SymbolIndexMap[Sym]
663                : SymbolIndexMap[ContainingCsect->getQualNameSymbol()];
664   };
665 
666   auto getVirtualAddress =
667       [this, &Layout](const MCSymbol *Sym,
668                       const MCSectionXCOFF *ContainingSect) -> uint64_t {
669     // A DWARF section.
670     if (ContainingSect->isDwarfSect())
671       return Layout.getSymbolOffset(*Sym);
672 
673     // A csect.
674     if (!Sym->isDefined())
675       return SectionMap[ContainingSect]->Address;
676 
677     // A label.
678     assert(Sym->isDefined() && "not a valid object that has address!");
679     return SectionMap[ContainingSect]->Address + Layout.getSymbolOffset(*Sym);
680   };
681 
682   const MCSymbol *const SymA = &Target.getSymA()->getSymbol();
683 
684   MCAsmBackend &Backend = Asm.getBackend();
685   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
686                  MCFixupKindInfo::FKF_IsPCRel;
687 
688   uint8_t Type;
689   uint8_t SignAndSize;
690   std::tie(Type, SignAndSize) =
691       TargetObjectWriter->getRelocTypeAndSignSize(Target, Fixup, IsPCRel);
692 
693   const MCSectionXCOFF *SymASec = getContainingCsect(cast<MCSymbolXCOFF>(SymA));
694   assert(SectionMap.contains(SymASec) &&
695          "Expected containing csect to exist in map.");
696 
697   assert((Fixup.getOffset() <=
698           MaxRawDataSize - Layout.getFragmentOffset(Fragment)) &&
699          "Fragment offset + fixup offset is overflowed.");
700   uint32_t FixupOffsetInCsect =
701       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
702 
703   const uint32_t Index = getIndex(SymA, SymASec);
704   if (Type == XCOFF::RelocationType::R_POS ||
705       Type == XCOFF::RelocationType::R_TLS ||
706       Type == XCOFF::RelocationType::R_TLS_LE ||
707       Type == XCOFF::RelocationType::R_TLS_IE)
708     // The FixedValue should be symbol's virtual address in this object file
709     // plus any constant value that we might get.
710     FixedValue = getVirtualAddress(SymA, SymASec) + Target.getConstant();
711   else if (Type == XCOFF::RelocationType::R_TLSM)
712     // The FixedValue should always be zero since the region handle is only
713     // known at load time.
714     FixedValue = 0;
715   else if (Type == XCOFF::RelocationType::R_TOC ||
716            Type == XCOFF::RelocationType::R_TOCL) {
717     // For non toc-data external symbols, R_TOC type relocation will relocate to
718     // data symbols that have XCOFF::XTY_SD type csect. For toc-data external
719     // symbols, R_TOC type relocation will relocate to data symbols that have
720     // XCOFF_ER type csect. For XCOFF_ER kind symbols, there will be no TOC
721     // entry for them, so the FixedValue should always be 0.
722     if (SymASec->getCSectType() == XCOFF::XTY_ER) {
723       FixedValue = 0;
724     } else {
725       // The FixedValue should be the TOC entry offset from the TOC-base plus
726       // any constant offset value.
727       const int64_t TOCEntryOffset = SectionMap[SymASec]->Address -
728                                      TOCCsects.front().Address +
729                                      Target.getConstant();
730       if (Type == XCOFF::RelocationType::R_TOC && !isInt<16>(TOCEntryOffset))
731         report_fatal_error("TOCEntryOffset overflows in small code model mode");
732 
733       FixedValue = TOCEntryOffset;
734     }
735   } else if (Type == XCOFF::RelocationType::R_RBR) {
736     MCSectionXCOFF *ParentSec = cast<MCSectionXCOFF>(Fragment->getParent());
737     assert((SymASec->getMappingClass() == XCOFF::XMC_PR &&
738             ParentSec->getMappingClass() == XCOFF::XMC_PR) &&
739            "Only XMC_PR csect may have the R_RBR relocation.");
740 
741     // The address of the branch instruction should be the sum of section
742     // address, fragment offset and Fixup offset.
743     uint64_t BRInstrAddress =
744         SectionMap[ParentSec]->Address + FixupOffsetInCsect;
745     // The FixedValue should be the difference between symbol's virtual address
746     // and BR instr address plus any constant value.
747     FixedValue = getVirtualAddress(SymA, SymASec) - BRInstrAddress +
748                  Target.getConstant();
749   } else if (Type == XCOFF::RelocationType::R_REF) {
750     // The FixedValue and FixupOffsetInCsect should always be 0 since it
751     // specifies a nonrelocating reference.
752     FixedValue = 0;
753     FixupOffsetInCsect = 0;
754   }
755 
756   XCOFFRelocation Reloc = {Index, FixupOffsetInCsect, SignAndSize, Type};
757   MCSectionXCOFF *RelocationSec = cast<MCSectionXCOFF>(Fragment->getParent());
758   assert(SectionMap.contains(RelocationSec) &&
759          "Expected containing csect to exist in map.");
760   SectionMap[RelocationSec]->Relocations.push_back(Reloc);
761 
762   if (!Target.getSymB())
763     return;
764 
765   const MCSymbol *const SymB = &Target.getSymB()->getSymbol();
766   if (SymA == SymB)
767     report_fatal_error("relocation for opposite term is not yet supported");
768 
769   const MCSectionXCOFF *SymBSec = getContainingCsect(cast<MCSymbolXCOFF>(SymB));
770   assert(SectionMap.contains(SymBSec) &&
771          "Expected containing csect to exist in map.");
772   if (SymASec == SymBSec)
773     report_fatal_error(
774         "relocation for paired relocatable term is not yet supported");
775 
776   assert(Type == XCOFF::RelocationType::R_POS &&
777          "SymA must be R_POS here if it's not opposite term or paired "
778          "relocatable term.");
779   const uint32_t IndexB = getIndex(SymB, SymBSec);
780   // SymB must be R_NEG here, given the general form of Target(MCValue) is
781   // "SymbolA - SymbolB + imm64".
782   const uint8_t TypeB = XCOFF::RelocationType::R_NEG;
783   XCOFFRelocation RelocB = {IndexB, FixupOffsetInCsect, SignAndSize, TypeB};
784   SectionMap[RelocationSec]->Relocations.push_back(RelocB);
785   // We already folded "SymbolA + imm64" above when Type is R_POS for SymbolA,
786   // now we just need to fold "- SymbolB" here.
787   FixedValue -= getVirtualAddress(SymB, SymBSec);
788 }
789 
790 void XCOFFObjectWriter::writeSections(const MCAssembler &Asm,
791                                       const MCAsmLayout &Layout) {
792   uint64_t CurrentAddressLocation = 0;
793   for (const auto *Section : Sections)
794     writeSectionForControlSectionEntry(Asm, Layout, *Section,
795                                        CurrentAddressLocation);
796   for (const auto &DwarfSection : DwarfSections)
797     writeSectionForDwarfSectionEntry(Asm, Layout, DwarfSection,
798                                      CurrentAddressLocation);
799   writeSectionForExceptionSectionEntry(Asm, Layout, ExceptionSection,
800                                        CurrentAddressLocation);
801   writeSectionForCInfoSymSectionEntry(Asm, Layout, CInfoSymSection,
802                                       CurrentAddressLocation);
803 }
804 
805 uint64_t XCOFFObjectWriter::writeObject(MCAssembler &Asm,
806                                         const MCAsmLayout &Layout) {
807   // We always emit a timestamp of 0 for reproducibility, so ensure incremental
808   // linking is not enabled, in case, like with Windows COFF, such a timestamp
809   // is incompatible with incremental linking of XCOFF.
810   if (Asm.isIncrementalLinkerCompatible())
811     report_fatal_error("Incremental linking not supported for XCOFF.");
812 
813   finalizeSectionInfo();
814   uint64_t StartOffset = W.OS.tell();
815 
816   writeFileHeader();
817   writeAuxFileHeader();
818   writeSectionHeaderTable();
819   writeSections(Asm, Layout);
820   writeRelocations();
821   writeSymbolTable(Layout);
822   // Write the string table.
823   Strings.write(W.OS);
824 
825   return W.OS.tell() - StartOffset;
826 }
827 
828 bool XCOFFObjectWriter::nameShouldBeInStringTable(const StringRef &SymbolName) {
829   return SymbolName.size() > XCOFF::NameSize || is64Bit();
830 }
831 
832 void XCOFFObjectWriter::writeSymbolName(const StringRef &SymbolName) {
833   // Magic, Offset or SymbolName.
834   if (nameShouldBeInStringTable(SymbolName)) {
835     W.write<int32_t>(0);
836     W.write<uint32_t>(Strings.getOffset(SymbolName));
837   } else {
838     char Name[XCOFF::NameSize + 1];
839     std::strncpy(Name, SymbolName.data(), XCOFF::NameSize);
840     ArrayRef<char> NameRef(Name, XCOFF::NameSize);
841     W.write(NameRef);
842   }
843 }
844 
845 void XCOFFObjectWriter::writeSymbolEntry(StringRef SymbolName, uint64_t Value,
846                                          int16_t SectionNumber,
847                                          uint16_t SymbolType,
848                                          uint8_t StorageClass,
849                                          uint8_t NumberOfAuxEntries) {
850   if (is64Bit()) {
851     W.write<uint64_t>(Value);
852     W.write<uint32_t>(Strings.getOffset(SymbolName));
853   } else {
854     writeSymbolName(SymbolName);
855     W.write<uint32_t>(Value);
856   }
857   W.write<int16_t>(SectionNumber);
858   W.write<uint16_t>(SymbolType);
859   W.write<uint8_t>(StorageClass);
860   W.write<uint8_t>(NumberOfAuxEntries);
861 }
862 
863 void XCOFFObjectWriter::writeSymbolAuxCsectEntry(uint64_t SectionOrLength,
864                                                  uint8_t SymbolAlignmentAndType,
865                                                  uint8_t StorageMappingClass) {
866   W.write<uint32_t>(is64Bit() ? Lo_32(SectionOrLength) : SectionOrLength);
867   W.write<uint32_t>(0); // ParameterHashIndex
868   W.write<uint16_t>(0); // TypeChkSectNum
869   W.write<uint8_t>(SymbolAlignmentAndType);
870   W.write<uint8_t>(StorageMappingClass);
871   if (is64Bit()) {
872     W.write<uint32_t>(Hi_32(SectionOrLength));
873     W.OS.write_zeros(1); // Reserved
874     W.write<uint8_t>(XCOFF::AUX_CSECT);
875   } else {
876     W.write<uint32_t>(0); // StabInfoIndex
877     W.write<uint16_t>(0); // StabSectNum
878   }
879 }
880 
881 void XCOFFObjectWriter::writeSymbolAuxDwarfEntry(
882     uint64_t LengthOfSectionPortion, uint64_t NumberOfRelocEnt) {
883   writeWord(LengthOfSectionPortion);
884   if (!is64Bit())
885     W.OS.write_zeros(4); // Reserved
886   writeWord(NumberOfRelocEnt);
887   if (is64Bit()) {
888     W.OS.write_zeros(1); // Reserved
889     W.write<uint8_t>(XCOFF::AUX_SECT);
890   } else {
891     W.OS.write_zeros(6); // Reserved
892   }
893 }
894 
895 void XCOFFObjectWriter::writeSymbolEntryForCsectMemberLabel(
896     const Symbol &SymbolRef, const XCOFFSection &CSectionRef,
897     int16_t SectionIndex, uint64_t SymbolOffset) {
898   assert(SymbolOffset <= MaxRawDataSize - CSectionRef.Address &&
899          "Symbol address overflowed.");
900 
901   auto Entry = ExceptionSection.ExceptionTable.find(SymbolRef.MCSym->getName());
902   if (Entry != ExceptionSection.ExceptionTable.end()) {
903     writeSymbolEntry(SymbolRef.getSymbolTableName(),
904                      CSectionRef.Address + SymbolOffset, SectionIndex,
905                      // In the old version of the 32-bit XCOFF interpretation,
906                      // symbols may require bit 10 (0x0020) to be set if the
907                      // symbol is a function, otherwise the bit should be 0.
908                      is64Bit() ? SymbolRef.getVisibilityType()
909                                : SymbolRef.getVisibilityType() | 0x0020,
910                      SymbolRef.getStorageClass(),
911                      (is64Bit() && ExceptionSection.isDebugEnabled) ? 3 : 2);
912     if (is64Bit() && ExceptionSection.isDebugEnabled) {
913       // On 64 bit with debugging enabled, we have a csect, exception, and
914       // function auxilliary entries, so we must increment symbol index by 4.
915       writeSymbolAuxExceptionEntry(
916           ExceptionSection.FileOffsetToData +
917               getExceptionOffset(Entry->second.FunctionSymbol),
918           Entry->second.FunctionSize,
919           SymbolIndexMap[Entry->second.FunctionSymbol] + 4);
920     }
921     // For exception section entries, csect and function auxilliary entries
922     // must exist. On 64-bit there is also an exception auxilliary entry.
923     writeSymbolAuxFunctionEntry(
924         ExceptionSection.FileOffsetToData +
925             getExceptionOffset(Entry->second.FunctionSymbol),
926         Entry->second.FunctionSize, 0,
927         (is64Bit() && ExceptionSection.isDebugEnabled)
928             ? SymbolIndexMap[Entry->second.FunctionSymbol] + 4
929             : SymbolIndexMap[Entry->second.FunctionSymbol] + 3);
930   } else {
931     writeSymbolEntry(SymbolRef.getSymbolTableName(),
932                      CSectionRef.Address + SymbolOffset, SectionIndex,
933                      SymbolRef.getVisibilityType(),
934                      SymbolRef.getStorageClass());
935   }
936   writeSymbolAuxCsectEntry(CSectionRef.SymbolTableIndex, XCOFF::XTY_LD,
937                            CSectionRef.MCSec->getMappingClass());
938 }
939 
940 void XCOFFObjectWriter::writeSymbolEntryForDwarfSection(
941     const XCOFFSection &DwarfSectionRef, int16_t SectionIndex) {
942   assert(DwarfSectionRef.MCSec->isDwarfSect() && "Not a DWARF section!");
943 
944   writeSymbolEntry(DwarfSectionRef.getSymbolTableName(), /*Value=*/0,
945                    SectionIndex, /*SymbolType=*/0, XCOFF::C_DWARF);
946 
947   writeSymbolAuxDwarfEntry(DwarfSectionRef.Size);
948 }
949 
950 void XCOFFObjectWriter::writeSymbolEntryForControlSection(
951     const XCOFFSection &CSectionRef, int16_t SectionIndex,
952     XCOFF::StorageClass StorageClass) {
953   writeSymbolEntry(CSectionRef.getSymbolTableName(), CSectionRef.Address,
954                    SectionIndex, CSectionRef.getVisibilityType(), StorageClass);
955 
956   writeSymbolAuxCsectEntry(CSectionRef.Size, getEncodedType(CSectionRef.MCSec),
957                            CSectionRef.MCSec->getMappingClass());
958 }
959 
960 void XCOFFObjectWriter::writeSymbolAuxFunctionEntry(uint32_t EntryOffset,
961                                                     uint32_t FunctionSize,
962                                                     uint64_t LineNumberPointer,
963                                                     uint32_t EndIndex) {
964   if (is64Bit())
965     writeWord(LineNumberPointer);
966   else
967     W.write<uint32_t>(EntryOffset);
968   W.write<uint32_t>(FunctionSize);
969   if (!is64Bit())
970     writeWord(LineNumberPointer);
971   W.write<uint32_t>(EndIndex);
972   if (is64Bit()) {
973     W.OS.write_zeros(1);
974     W.write<uint8_t>(XCOFF::AUX_FCN);
975   } else {
976     W.OS.write_zeros(2);
977   }
978 }
979 
980 void XCOFFObjectWriter::writeSymbolAuxExceptionEntry(uint64_t EntryOffset,
981                                                      uint32_t FunctionSize,
982                                                      uint32_t EndIndex) {
983   assert(is64Bit() && "Exception auxilliary entries are 64-bit only.");
984   W.write<uint64_t>(EntryOffset);
985   W.write<uint32_t>(FunctionSize);
986   W.write<uint32_t>(EndIndex);
987   W.OS.write_zeros(1); // Pad (unused)
988   W.write<uint8_t>(XCOFF::AUX_EXCEPT);
989 }
990 
991 void XCOFFObjectWriter::writeFileHeader() {
992   W.write<uint16_t>(is64Bit() ? XCOFF::XCOFF64 : XCOFF::XCOFF32);
993   W.write<uint16_t>(SectionCount);
994   W.write<int32_t>(0); // TimeStamp
995   writeWord(SymbolTableOffset);
996   if (is64Bit()) {
997     W.write<uint16_t>(auxiliaryHeaderSize());
998     W.write<uint16_t>(0); // Flags
999     W.write<int32_t>(SymbolTableEntryCount);
1000   } else {
1001     W.write<int32_t>(SymbolTableEntryCount);
1002     W.write<uint16_t>(auxiliaryHeaderSize());
1003     W.write<uint16_t>(0); // Flags
1004   }
1005 }
1006 
1007 void XCOFFObjectWriter::writeAuxFileHeader() {
1008   if (!auxiliaryHeaderSize())
1009     return;
1010   W.write<uint16_t>(0); // Magic
1011   W.write<uint16_t>(
1012       XCOFF::NEW_XCOFF_INTERPRET); // Version. The new interpretation of the
1013                                    // n_type field in the symbol table entry is
1014                                    // used in XCOFF32.
1015   W.write<uint32_t>(Sections[0]->Size);    // TextSize
1016   W.write<uint32_t>(Sections[1]->Size);    // InitDataSize
1017   W.write<uint32_t>(Sections[2]->Size);    // BssDataSize
1018   W.write<uint32_t>(0);                    // EntryPointAddr
1019   W.write<uint32_t>(Sections[0]->Address); // TextStartAddr
1020   W.write<uint32_t>(Sections[1]->Address); // DataStartAddr
1021 }
1022 
1023 void XCOFFObjectWriter::writeSectionHeader(const SectionEntry *Sec) {
1024   bool IsDwarf = (Sec->Flags & XCOFF::STYP_DWARF) != 0;
1025   bool IsOvrflo = (Sec->Flags & XCOFF::STYP_OVRFLO) != 0;
1026   // Nothing to write for this Section.
1027   if (Sec->Index == SectionEntry::UninitializedIndex)
1028     return;
1029 
1030   // Write Name.
1031   ArrayRef<char> NameRef(Sec->Name, XCOFF::NameSize);
1032   W.write(NameRef);
1033 
1034   // Write the Physical Address and Virtual Address.
1035   // We use 0 for DWARF sections' Physical and Virtual Addresses.
1036   writeWord(IsDwarf ? 0 : Sec->Address);
1037   // Since line number is not supported, we set it to 0 for overflow sections.
1038   writeWord((IsDwarf || IsOvrflo) ? 0 : Sec->Address);
1039 
1040   writeWord(Sec->Size);
1041   writeWord(Sec->FileOffsetToData);
1042   writeWord(Sec->FileOffsetToRelocations);
1043   writeWord(0); // FileOffsetToLineNumberInfo. Not supported yet.
1044 
1045   if (is64Bit()) {
1046     W.write<uint32_t>(Sec->RelocationCount);
1047     W.write<uint32_t>(0); // NumberOfLineNumbers. Not supported yet.
1048     W.write<int32_t>(Sec->Flags);
1049     W.OS.write_zeros(4);
1050   } else {
1051     // For the overflow section header, s_nreloc provides a reference to the
1052     // primary section header and s_nlnno must have the same value.
1053     // For common section headers, if either of s_nreloc or s_nlnno are set to
1054     // 65535, the other one must also be set to 65535.
1055     W.write<uint16_t>(Sec->RelocationCount);
1056     W.write<uint16_t>((IsOvrflo || Sec->RelocationCount == XCOFF::RelocOverflow)
1057                           ? Sec->RelocationCount
1058                           : 0); // NumberOfLineNumbers. Not supported yet.
1059     W.write<int32_t>(Sec->Flags);
1060   }
1061 }
1062 
1063 void XCOFFObjectWriter::writeSectionHeaderTable() {
1064   for (const auto *CsectSec : Sections)
1065     writeSectionHeader(CsectSec);
1066   for (const auto &DwarfSec : DwarfSections)
1067     writeSectionHeader(&DwarfSec);
1068   for (const auto &OverflowSec : OverflowSections)
1069     writeSectionHeader(&OverflowSec);
1070   if (hasExceptionSection())
1071     writeSectionHeader(&ExceptionSection);
1072   if (CInfoSymSection.Entry)
1073     writeSectionHeader(&CInfoSymSection);
1074 }
1075 
1076 void XCOFFObjectWriter::writeRelocation(XCOFFRelocation Reloc,
1077                                         const XCOFFSection &Section) {
1078   if (Section.MCSec->isCsect())
1079     writeWord(Section.Address + Reloc.FixupOffsetInCsect);
1080   else {
1081     // DWARF sections' address is set to 0.
1082     assert(Section.MCSec->isDwarfSect() && "unsupport section type!");
1083     writeWord(Reloc.FixupOffsetInCsect);
1084   }
1085   W.write<uint32_t>(Reloc.SymbolTableIndex);
1086   W.write<uint8_t>(Reloc.SignAndSize);
1087   W.write<uint8_t>(Reloc.Type);
1088 }
1089 
1090 void XCOFFObjectWriter::writeRelocations() {
1091   for (const auto *Section : Sections) {
1092     if (Section->Index == SectionEntry::UninitializedIndex)
1093       // Nothing to write for this Section.
1094       continue;
1095 
1096     for (const auto *Group : Section->Groups) {
1097       if (Group->empty())
1098         continue;
1099 
1100       for (const auto &Csect : *Group) {
1101         for (const auto Reloc : Csect.Relocations)
1102           writeRelocation(Reloc, Csect);
1103       }
1104     }
1105   }
1106 
1107   for (const auto &DwarfSection : DwarfSections)
1108     for (const auto &Reloc : DwarfSection.DwarfSect->Relocations)
1109       writeRelocation(Reloc, *DwarfSection.DwarfSect);
1110 }
1111 
1112 void XCOFFObjectWriter::writeSymbolTable(const MCAsmLayout &Layout) {
1113   // Write C_FILE symbols.
1114   for (const std::pair<std::string, size_t> &F : FileNames) {
1115     // The n_name of a C_FILE symbol is the source file's name when no auxiliary
1116     // entries are present.
1117     StringRef FileName = F.first;
1118 
1119     // For C_FILE symbols, the Source Language ID overlays the high-order byte
1120     // of the SymbolType field, and the CPU Version ID is defined as the
1121     // low-order byte.
1122     // AIX's system assembler determines the source language ID based on the
1123     // source file's name suffix, and the behavior here is consistent with it.
1124     uint8_t LangID;
1125     if (FileName.ends_with(".c"))
1126       LangID = XCOFF::TB_C;
1127     else if (FileName.ends_with_insensitive(".f") ||
1128              FileName.ends_with_insensitive(".f77") ||
1129              FileName.ends_with_insensitive(".f90") ||
1130              FileName.ends_with_insensitive(".f95") ||
1131              FileName.ends_with_insensitive(".f03") ||
1132              FileName.ends_with_insensitive(".f08"))
1133       LangID = XCOFF::TB_Fortran;
1134     else
1135       LangID = XCOFF::TB_CPLUSPLUS;
1136     uint8_t CpuID;
1137     if (is64Bit())
1138       CpuID = XCOFF::TCPU_PPC64;
1139     else
1140       CpuID = XCOFF::TCPU_COM;
1141 
1142     writeSymbolEntry(FileName, /*Value=*/0, XCOFF::ReservedSectionNum::N_DEBUG,
1143                      /*SymbolType=*/(LangID << 8) | CpuID, XCOFF::C_FILE,
1144                      /*NumberOfAuxEntries=*/0);
1145   }
1146 
1147   if (CInfoSymSection.Entry)
1148     writeSymbolEntry(CInfoSymSection.Entry->Name, CInfoSymSection.Entry->Offset,
1149                      CInfoSymSection.Index,
1150                      /*SymbolType=*/0, XCOFF::C_INFO,
1151                      /*NumberOfAuxEntries=*/0);
1152 
1153   for (const auto &Csect : UndefinedCsects) {
1154     writeSymbolEntryForControlSection(Csect, XCOFF::ReservedSectionNum::N_UNDEF,
1155                                       Csect.MCSec->getStorageClass());
1156   }
1157 
1158   for (const auto *Section : Sections) {
1159     if (Section->Index == SectionEntry::UninitializedIndex)
1160       // Nothing to write for this Section.
1161       continue;
1162 
1163     for (const auto *Group : Section->Groups) {
1164       if (Group->empty())
1165         continue;
1166 
1167       const int16_t SectionIndex = Section->Index;
1168       for (const auto &Csect : *Group) {
1169         // Write out the control section first and then each symbol in it.
1170         writeSymbolEntryForControlSection(Csect, SectionIndex,
1171                                           Csect.MCSec->getStorageClass());
1172 
1173         for (const auto &Sym : Csect.Syms)
1174           writeSymbolEntryForCsectMemberLabel(
1175               Sym, Csect, SectionIndex, Layout.getSymbolOffset(*(Sym.MCSym)));
1176       }
1177     }
1178   }
1179 
1180   for (const auto &DwarfSection : DwarfSections)
1181     writeSymbolEntryForDwarfSection(*DwarfSection.DwarfSect,
1182                                     DwarfSection.Index);
1183 }
1184 
1185 void XCOFFObjectWriter::finalizeRelocationInfo(SectionEntry *Sec,
1186                                                uint64_t RelCount) {
1187   // Handles relocation field overflows in an XCOFF32 file. An XCOFF64 file
1188   // may not contain an overflow section header.
1189   if (!is64Bit() && (RelCount >= static_cast<uint32_t>(XCOFF::RelocOverflow))) {
1190     // Generate an overflow section header.
1191     SectionEntry SecEntry(".ovrflo", XCOFF::STYP_OVRFLO);
1192 
1193     // This field specifies the file section number of the section header that
1194     // overflowed.
1195     SecEntry.RelocationCount = Sec->Index;
1196 
1197     // This field specifies the number of relocation entries actually
1198     // required.
1199     SecEntry.Address = RelCount;
1200     SecEntry.Index = ++SectionCount;
1201     OverflowSections.push_back(std::move(SecEntry));
1202 
1203     // The field in the primary section header is always 65535
1204     // (XCOFF::RelocOverflow).
1205     Sec->RelocationCount = XCOFF::RelocOverflow;
1206   } else {
1207     Sec->RelocationCount = RelCount;
1208   }
1209 }
1210 
1211 void XCOFFObjectWriter::calcOffsetToRelocations(SectionEntry *Sec,
1212                                                 uint64_t &RawPointer) {
1213   if (!Sec->RelocationCount)
1214     return;
1215 
1216   Sec->FileOffsetToRelocations = RawPointer;
1217   uint64_t RelocationSizeInSec = 0;
1218   if (!is64Bit() &&
1219       Sec->RelocationCount == static_cast<uint32_t>(XCOFF::RelocOverflow)) {
1220     // Find its corresponding overflow section.
1221     for (auto &OverflowSec : OverflowSections) {
1222       if (OverflowSec.RelocationCount == static_cast<uint32_t>(Sec->Index)) {
1223         RelocationSizeInSec =
1224             OverflowSec.Address * XCOFF::RelocationSerializationSize32;
1225 
1226         // This field must have the same values as in the corresponding
1227         // primary section header.
1228         OverflowSec.FileOffsetToRelocations = Sec->FileOffsetToRelocations;
1229       }
1230     }
1231     assert(RelocationSizeInSec && "Overflow section header doesn't exist.");
1232   } else {
1233     RelocationSizeInSec = Sec->RelocationCount *
1234                           (is64Bit() ? XCOFF::RelocationSerializationSize64
1235                                      : XCOFF::RelocationSerializationSize32);
1236   }
1237 
1238   RawPointer += RelocationSizeInSec;
1239   if (RawPointer > MaxRawDataSize)
1240     report_fatal_error("Relocation data overflowed this object file.");
1241 }
1242 
1243 void XCOFFObjectWriter::finalizeSectionInfo() {
1244   for (auto *Section : Sections) {
1245     if (Section->Index == SectionEntry::UninitializedIndex)
1246       // Nothing to record for this Section.
1247       continue;
1248 
1249     uint64_t RelCount = 0;
1250     for (const auto *Group : Section->Groups) {
1251       if (Group->empty())
1252         continue;
1253 
1254       for (auto &Csect : *Group)
1255         RelCount += Csect.Relocations.size();
1256     }
1257     finalizeRelocationInfo(Section, RelCount);
1258   }
1259 
1260   for (auto &DwarfSection : DwarfSections)
1261     finalizeRelocationInfo(&DwarfSection,
1262                            DwarfSection.DwarfSect->Relocations.size());
1263 
1264   // Calculate the RawPointer value for all headers.
1265   uint64_t RawPointer =
1266       (is64Bit() ? (XCOFF::FileHeaderSize64 +
1267                     SectionCount * XCOFF::SectionHeaderSize64)
1268                  : (XCOFF::FileHeaderSize32 +
1269                     SectionCount * XCOFF::SectionHeaderSize32)) +
1270       auxiliaryHeaderSize();
1271 
1272   // Calculate the file offset to the section data.
1273   for (auto *Sec : Sections) {
1274     if (Sec->Index == SectionEntry::UninitializedIndex || Sec->IsVirtual)
1275       continue;
1276 
1277     RawPointer = Sec->advanceFileOffset(MaxRawDataSize, RawPointer);
1278   }
1279 
1280   if (!DwarfSections.empty()) {
1281     RawPointer += PaddingsBeforeDwarf;
1282     for (auto &DwarfSection : DwarfSections) {
1283       RawPointer = DwarfSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1284     }
1285   }
1286 
1287   if (hasExceptionSection())
1288     RawPointer = ExceptionSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1289 
1290   if (CInfoSymSection.Entry)
1291     RawPointer = CInfoSymSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1292 
1293   for (auto *Sec : Sections) {
1294     if (Sec->Index != SectionEntry::UninitializedIndex)
1295       calcOffsetToRelocations(Sec, RawPointer);
1296   }
1297 
1298   for (auto &DwarfSec : DwarfSections)
1299     calcOffsetToRelocations(&DwarfSec, RawPointer);
1300 
1301   // TODO Error check that the number of symbol table entries fits in 32-bits
1302   // signed ...
1303   if (SymbolTableEntryCount)
1304     SymbolTableOffset = RawPointer;
1305 }
1306 
1307 void XCOFFObjectWriter::addExceptionEntry(
1308     const MCSymbol *Symbol, const MCSymbol *Trap, unsigned LanguageCode,
1309     unsigned ReasonCode, unsigned FunctionSize, bool hasDebug) {
1310   // If a module had debug info, debugging is enabled and XCOFF emits the
1311   // exception auxilliary entry.
1312   if (hasDebug)
1313     ExceptionSection.isDebugEnabled = true;
1314   auto Entry = ExceptionSection.ExceptionTable.find(Symbol->getName());
1315   if (Entry != ExceptionSection.ExceptionTable.end()) {
1316     Entry->second.Entries.push_back(
1317         ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1318     return;
1319   }
1320   ExceptionInfo NewEntry;
1321   NewEntry.FunctionSymbol = Symbol;
1322   NewEntry.FunctionSize = FunctionSize;
1323   NewEntry.Entries.push_back(
1324       ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1325   ExceptionSection.ExceptionTable.insert(
1326       std::pair<const StringRef, ExceptionInfo>(Symbol->getName(), NewEntry));
1327 }
1328 
1329 unsigned XCOFFObjectWriter::getExceptionSectionSize() {
1330   unsigned EntryNum = 0;
1331 
1332   for (auto it = ExceptionSection.ExceptionTable.begin();
1333        it != ExceptionSection.ExceptionTable.end(); ++it)
1334     // The size() gets +1 to account for the initial entry containing the
1335     // symbol table index.
1336     EntryNum += it->second.Entries.size() + 1;
1337 
1338   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1339                                : XCOFF::ExceptionSectionEntrySize32);
1340 }
1341 
1342 unsigned XCOFFObjectWriter::getExceptionOffset(const MCSymbol *Symbol) {
1343   unsigned EntryNum = 0;
1344   for (auto it = ExceptionSection.ExceptionTable.begin();
1345        it != ExceptionSection.ExceptionTable.end(); ++it) {
1346     if (Symbol == it->second.FunctionSymbol)
1347       break;
1348     EntryNum += it->second.Entries.size() + 1;
1349   }
1350   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1351                                : XCOFF::ExceptionSectionEntrySize32);
1352 }
1353 
1354 void XCOFFObjectWriter::addCInfoSymEntry(StringRef Name, StringRef Metadata) {
1355   assert(!CInfoSymSection.Entry && "Multiple entries are not supported");
1356   CInfoSymSection.addEntry(
1357       std::make_unique<CInfoSymInfo>(Name.str(), Metadata.str()));
1358 }
1359 
1360 void XCOFFObjectWriter::assignAddressesAndIndices(const MCAsmLayout &Layout) {
1361   // The symbol table starts with all the C_FILE symbols.
1362   uint32_t SymbolTableIndex = FileNames.size();
1363 
1364   if (CInfoSymSection.Entry)
1365     SymbolTableIndex++;
1366 
1367   // Calculate indices for undefined symbols.
1368   for (auto &Csect : UndefinedCsects) {
1369     Csect.Size = 0;
1370     Csect.Address = 0;
1371     Csect.SymbolTableIndex = SymbolTableIndex;
1372     SymbolIndexMap[Csect.MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1373     // 1 main and 1 auxiliary symbol table entry for each contained symbol.
1374     SymbolTableIndex += 2;
1375   }
1376 
1377   // The address corrresponds to the address of sections and symbols in the
1378   // object file. We place the shared address 0 immediately after the
1379   // section header table.
1380   uint64_t Address = 0;
1381   // Section indices are 1-based in XCOFF.
1382   int32_t SectionIndex = 1;
1383   bool HasTDataSection = false;
1384 
1385   for (auto *Section : Sections) {
1386     const bool IsEmpty =
1387         llvm::all_of(Section->Groups,
1388                      [](const CsectGroup *Group) { return Group->empty(); });
1389     if (IsEmpty)
1390       continue;
1391 
1392     if (SectionIndex > MaxSectionIndex)
1393       report_fatal_error("Section index overflow!");
1394     Section->Index = SectionIndex++;
1395     SectionCount++;
1396 
1397     bool SectionAddressSet = false;
1398     // Reset the starting address to 0 for TData section.
1399     if (Section->Flags == XCOFF::STYP_TDATA) {
1400       Address = 0;
1401       HasTDataSection = true;
1402     }
1403     // Reset the starting address to 0 for TBSS section if the object file does
1404     // not contain TData Section.
1405     if ((Section->Flags == XCOFF::STYP_TBSS) && !HasTDataSection)
1406       Address = 0;
1407 
1408     for (auto *Group : Section->Groups) {
1409       if (Group->empty())
1410         continue;
1411 
1412       for (auto &Csect : *Group) {
1413         const MCSectionXCOFF *MCSec = Csect.MCSec;
1414         Csect.Address = alignTo(Address, MCSec->getAlign());
1415         Csect.Size = Layout.getSectionAddressSize(MCSec);
1416         Address = Csect.Address + Csect.Size;
1417         Csect.SymbolTableIndex = SymbolTableIndex;
1418         SymbolIndexMap[MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1419         // 1 main and 1 auxiliary symbol table entry for the csect.
1420         SymbolTableIndex += 2;
1421 
1422         for (auto &Sym : Csect.Syms) {
1423           bool hasExceptEntry = false;
1424           auto Entry =
1425               ExceptionSection.ExceptionTable.find(Sym.MCSym->getName());
1426           if (Entry != ExceptionSection.ExceptionTable.end()) {
1427             hasExceptEntry = true;
1428             for (auto &TrapEntry : Entry->second.Entries) {
1429               TrapEntry.TrapAddress = Layout.getSymbolOffset(*(Sym.MCSym)) +
1430                                       TrapEntry.Trap->getOffset();
1431             }
1432           }
1433           Sym.SymbolTableIndex = SymbolTableIndex;
1434           SymbolIndexMap[Sym.MCSym] = Sym.SymbolTableIndex;
1435           // 1 main and 1 auxiliary symbol table entry for each contained
1436           // symbol. For symbols with exception section entries, a function
1437           // auxilliary entry is needed, and on 64-bit XCOFF with debugging
1438           // enabled, an additional exception auxilliary entry is needed.
1439           SymbolTableIndex += 2;
1440           if (hasExceptionSection() && hasExceptEntry) {
1441             if (is64Bit() && ExceptionSection.isDebugEnabled)
1442               SymbolTableIndex += 2;
1443             else
1444               SymbolTableIndex += 1;
1445           }
1446         }
1447       }
1448 
1449       if (!SectionAddressSet) {
1450         Section->Address = Group->front().Address;
1451         SectionAddressSet = true;
1452       }
1453     }
1454 
1455     // Make sure the address of the next section aligned to
1456     // DefaultSectionAlign.
1457     Address = alignTo(Address, DefaultSectionAlign);
1458     Section->Size = Address - Section->Address;
1459   }
1460 
1461   // Start to generate DWARF sections. Sections other than DWARF section use
1462   // DefaultSectionAlign as the default alignment, while DWARF sections have
1463   // their own alignments. If these two alignments are not the same, we need
1464   // some paddings here and record the paddings bytes for FileOffsetToData
1465   // calculation.
1466   if (!DwarfSections.empty())
1467     PaddingsBeforeDwarf =
1468         alignTo(Address,
1469                 (*DwarfSections.begin()).DwarfSect->MCSec->getAlign()) -
1470         Address;
1471 
1472   DwarfSectionEntry *LastDwarfSection = nullptr;
1473   for (auto &DwarfSection : DwarfSections) {
1474     assert((SectionIndex <= MaxSectionIndex) && "Section index overflow!");
1475 
1476     XCOFFSection &DwarfSect = *DwarfSection.DwarfSect;
1477     const MCSectionXCOFF *MCSec = DwarfSect.MCSec;
1478 
1479     // Section index.
1480     DwarfSection.Index = SectionIndex++;
1481     SectionCount++;
1482 
1483     // Symbol index.
1484     DwarfSect.SymbolTableIndex = SymbolTableIndex;
1485     SymbolIndexMap[MCSec->getQualNameSymbol()] = DwarfSect.SymbolTableIndex;
1486     // 1 main and 1 auxiliary symbol table entry for the csect.
1487     SymbolTableIndex += 2;
1488 
1489     // Section address. Make it align to section alignment.
1490     // We use address 0 for DWARF sections' Physical and Virtual Addresses.
1491     // This address is used to tell where is the section in the final object.
1492     // See writeSectionForDwarfSectionEntry().
1493     DwarfSection.Address = DwarfSect.Address =
1494         alignTo(Address, MCSec->getAlign());
1495 
1496     // Section size.
1497     // For DWARF section, we must use the real size which may be not aligned.
1498     DwarfSection.Size = DwarfSect.Size = Layout.getSectionAddressSize(MCSec);
1499 
1500     Address = DwarfSection.Address + DwarfSection.Size;
1501 
1502     if (LastDwarfSection)
1503       LastDwarfSection->MemorySize =
1504           DwarfSection.Address - LastDwarfSection->Address;
1505     LastDwarfSection = &DwarfSection;
1506   }
1507   if (LastDwarfSection) {
1508     // Make the final DWARF section address align to the default section
1509     // alignment for follow contents.
1510     Address = alignTo(LastDwarfSection->Address + LastDwarfSection->Size,
1511                       DefaultSectionAlign);
1512     LastDwarfSection->MemorySize = Address - LastDwarfSection->Address;
1513   }
1514   if (hasExceptionSection()) {
1515     ExceptionSection.Index = SectionIndex++;
1516     SectionCount++;
1517     ExceptionSection.Address = 0;
1518     ExceptionSection.Size = getExceptionSectionSize();
1519     Address += ExceptionSection.Size;
1520     Address = alignTo(Address, DefaultSectionAlign);
1521   }
1522 
1523   if (CInfoSymSection.Entry) {
1524     CInfoSymSection.Index = SectionIndex++;
1525     SectionCount++;
1526     CInfoSymSection.Address = 0;
1527     Address += CInfoSymSection.Size;
1528     Address = alignTo(Address, DefaultSectionAlign);
1529   }
1530 
1531   SymbolTableEntryCount = SymbolTableIndex;
1532 }
1533 
1534 void XCOFFObjectWriter::writeSectionForControlSectionEntry(
1535     const MCAssembler &Asm, const MCAsmLayout &Layout,
1536     const CsectSectionEntry &CsectEntry, uint64_t &CurrentAddressLocation) {
1537   // Nothing to write for this Section.
1538   if (CsectEntry.Index == SectionEntry::UninitializedIndex)
1539     return;
1540 
1541   // There could be a gap (without corresponding zero padding) between
1542   // sections.
1543   // There could be a gap (without corresponding zero padding) between
1544   // sections.
1545   assert(((CurrentAddressLocation <= CsectEntry.Address) ||
1546           (CsectEntry.Flags == XCOFF::STYP_TDATA) ||
1547           (CsectEntry.Flags == XCOFF::STYP_TBSS)) &&
1548          "CurrentAddressLocation should be less than or equal to section "
1549          "address if the section is not TData or TBSS.");
1550 
1551   CurrentAddressLocation = CsectEntry.Address;
1552 
1553   // For virtual sections, nothing to write. But need to increase
1554   // CurrentAddressLocation for later sections like DWARF section has a correct
1555   // writing location.
1556   if (CsectEntry.IsVirtual) {
1557     CurrentAddressLocation += CsectEntry.Size;
1558     return;
1559   }
1560 
1561   for (const auto &Group : CsectEntry.Groups) {
1562     for (const auto &Csect : *Group) {
1563       if (uint32_t PaddingSize = Csect.Address - CurrentAddressLocation)
1564         W.OS.write_zeros(PaddingSize);
1565       if (Csect.Size)
1566         Asm.writeSectionData(W.OS, Csect.MCSec, Layout);
1567       CurrentAddressLocation = Csect.Address + Csect.Size;
1568     }
1569   }
1570 
1571   // The size of the tail padding in a section is the end virtual address of
1572   // the current section minus the end virtual address of the last csect
1573   // in that section.
1574   if (uint64_t PaddingSize =
1575           CsectEntry.Address + CsectEntry.Size - CurrentAddressLocation) {
1576     W.OS.write_zeros(PaddingSize);
1577     CurrentAddressLocation += PaddingSize;
1578   }
1579 }
1580 
1581 void XCOFFObjectWriter::writeSectionForDwarfSectionEntry(
1582     const MCAssembler &Asm, const MCAsmLayout &Layout,
1583     const DwarfSectionEntry &DwarfEntry, uint64_t &CurrentAddressLocation) {
1584   // There could be a gap (without corresponding zero padding) between
1585   // sections. For example DWARF section alignment is bigger than
1586   // DefaultSectionAlign.
1587   assert(CurrentAddressLocation <= DwarfEntry.Address &&
1588          "CurrentAddressLocation should be less than or equal to section "
1589          "address.");
1590 
1591   if (uint64_t PaddingSize = DwarfEntry.Address - CurrentAddressLocation)
1592     W.OS.write_zeros(PaddingSize);
1593 
1594   if (DwarfEntry.Size)
1595     Asm.writeSectionData(W.OS, DwarfEntry.DwarfSect->MCSec, Layout);
1596 
1597   CurrentAddressLocation = DwarfEntry.Address + DwarfEntry.Size;
1598 
1599   // DWARF section size is not aligned to DefaultSectionAlign.
1600   // Make sure CurrentAddressLocation is aligned to DefaultSectionAlign.
1601   uint32_t Mod = CurrentAddressLocation % DefaultSectionAlign;
1602   uint32_t TailPaddingSize = Mod ? DefaultSectionAlign - Mod : 0;
1603   if (TailPaddingSize)
1604     W.OS.write_zeros(TailPaddingSize);
1605 
1606   CurrentAddressLocation += TailPaddingSize;
1607 }
1608 
1609 void XCOFFObjectWriter::writeSectionForExceptionSectionEntry(
1610     const MCAssembler &Asm, const MCAsmLayout &Layout,
1611     ExceptionSectionEntry &ExceptionEntry, uint64_t &CurrentAddressLocation) {
1612   for (auto it = ExceptionEntry.ExceptionTable.begin();
1613        it != ExceptionEntry.ExceptionTable.end(); it++) {
1614     // For every symbol that has exception entries, you must start the entries
1615     // with an initial symbol table index entry
1616     W.write<uint32_t>(SymbolIndexMap[it->second.FunctionSymbol]);
1617     if (is64Bit()) {
1618       // 4-byte padding on 64-bit.
1619       W.OS.write_zeros(4);
1620     }
1621     W.OS.write_zeros(2);
1622     for (auto &TrapEntry : it->second.Entries) {
1623       writeWord(TrapEntry.TrapAddress);
1624       W.write<uint8_t>(TrapEntry.Lang);
1625       W.write<uint8_t>(TrapEntry.Reason);
1626     }
1627   }
1628 
1629   CurrentAddressLocation += getExceptionSectionSize();
1630 }
1631 
1632 void XCOFFObjectWriter::writeSectionForCInfoSymSectionEntry(
1633     const MCAssembler &Asm, const MCAsmLayout &Layout,
1634     CInfoSymSectionEntry &CInfoSymEntry, uint64_t &CurrentAddressLocation) {
1635   if (!CInfoSymSection.Entry)
1636     return;
1637 
1638   constexpr int WordSize = sizeof(uint32_t);
1639   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymEntry.Entry;
1640   const std::string &Metadata = CISI->Metadata;
1641 
1642   // Emit the 4-byte length of the metadata.
1643   W.write<uint32_t>(Metadata.size());
1644 
1645   if (Metadata.size() == 0)
1646     return;
1647 
1648   // Write out the payload one word at a time.
1649   size_t Index = 0;
1650   while (Index + WordSize <= Metadata.size()) {
1651     uint32_t NextWord =
1652         llvm::support::endian::read32be(Metadata.data() + Index);
1653     W.write<uint32_t>(NextWord);
1654     Index += WordSize;
1655   }
1656 
1657   // If there is padding, we have at least one byte of payload left to emit.
1658   if (CISI->paddingSize()) {
1659     std::array<uint8_t, WordSize> LastWord = {0};
1660     ::memcpy(LastWord.data(), Metadata.data() + Index, Metadata.size() - Index);
1661     W.write<uint32_t>(llvm::support::endian::read32be(LastWord.data()));
1662   }
1663 
1664   CurrentAddressLocation += CISI->size();
1665 }
1666 
1667 // Takes the log base 2 of the alignment and shifts the result into the 5 most
1668 // significant bits of a byte, then or's in the csect type into the least
1669 // significant 3 bits.
1670 uint8_t getEncodedType(const MCSectionXCOFF *Sec) {
1671   unsigned Log2Align = Log2(Sec->getAlign());
1672   // Result is a number in the range [0, 31] which fits in the 5 least
1673   // significant bits. Shift this value into the 5 most significant bits, and
1674   // bitwise-or in the csect type.
1675   uint8_t EncodedAlign = Log2Align << 3;
1676   return EncodedAlign | Sec->getCSectType();
1677 }
1678 
1679 } // end anonymous namespace
1680 
1681 std::unique_ptr<MCObjectWriter>
1682 llvm::createXCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
1683                               raw_pwrite_stream &OS) {
1684   return std::make_unique<XCOFFObjectWriter>(std::move(MOTW), OS);
1685 }
1686