xref: /freebsd/contrib/llvm-project/llvm/lib/MC/XCOFFObjectWriter.cpp (revision 5ca8e32633c4ffbbcd6762e5888b6a4ba0708c6c)
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, support::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   case XCOFF::XMC_TD:
537     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
538            "Only an initialized csect can contain TC entry.");
539     assert(!TOCCsects.empty() &&
540            "We should at least have a TOC-base in this CsectGroup.");
541     return TOCCsects;
542   default:
543     report_fatal_error("Unhandled mapping of csect to section.");
544   }
545 }
546 
547 static MCSectionXCOFF *getContainingCsect(const MCSymbolXCOFF *XSym) {
548   if (XSym->isDefined())
549     return cast<MCSectionXCOFF>(XSym->getFragment()->getParent());
550   return XSym->getRepresentedCsect();
551 }
552 
553 void XCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
554                                                  const MCAsmLayout &Layout) {
555   for (const auto &S : Asm) {
556     const auto *MCSec = cast<const MCSectionXCOFF>(&S);
557     assert(!SectionMap.contains(MCSec) && "Cannot add a section twice.");
558 
559     // If the name does not fit in the storage provided in the symbol table
560     // entry, add it to the string table.
561     if (nameShouldBeInStringTable(MCSec->getSymbolTableName()))
562       Strings.add(MCSec->getSymbolTableName());
563     if (MCSec->isCsect()) {
564       // A new control section. Its CsectSectionEntry should already be staticly
565       // generated as Text/Data/BSS/TDATA/TBSS. Add this section to the group of
566       // the CsectSectionEntry.
567       assert(XCOFF::XTY_ER != MCSec->getCSectType() &&
568              "An undefined csect should not get registered.");
569       CsectGroup &Group = getCsectGroup(MCSec);
570       Group.emplace_back(MCSec);
571       SectionMap[MCSec] = &Group.back();
572     } else if (MCSec->isDwarfSect()) {
573       // A new DwarfSectionEntry.
574       std::unique_ptr<XCOFFSection> DwarfSec =
575           std::make_unique<XCOFFSection>(MCSec);
576       SectionMap[MCSec] = DwarfSec.get();
577 
578       DwarfSectionEntry SecEntry(MCSec->getName(),
579                                  *MCSec->getDwarfSubtypeFlags(),
580                                  std::move(DwarfSec));
581       DwarfSections.push_back(std::move(SecEntry));
582     } else
583       llvm_unreachable("unsupport section type!");
584   }
585 
586   for (const MCSymbol &S : Asm.symbols()) {
587     // Nothing to do for temporary symbols.
588     if (S.isTemporary())
589       continue;
590 
591     const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(&S);
592     const MCSectionXCOFF *ContainingCsect = getContainingCsect(XSym);
593 
594     if (XSym->getVisibilityType() != XCOFF::SYM_V_UNSPECIFIED)
595       HasVisibility = true;
596 
597     if (ContainingCsect->getCSectType() == XCOFF::XTY_ER) {
598       // Handle undefined symbol.
599       UndefinedCsects.emplace_back(ContainingCsect);
600       SectionMap[ContainingCsect] = &UndefinedCsects.back();
601       if (nameShouldBeInStringTable(ContainingCsect->getSymbolTableName()))
602         Strings.add(ContainingCsect->getSymbolTableName());
603       continue;
604     }
605 
606     // If the symbol is the csect itself, we don't need to put the symbol
607     // into csect's Syms.
608     if (XSym == ContainingCsect->getQualNameSymbol())
609       continue;
610 
611     // Only put a label into the symbol table when it is an external label.
612     if (!XSym->isExternal())
613       continue;
614 
615     assert(SectionMap.contains(ContainingCsect) &&
616            "Expected containing csect to exist in map");
617     XCOFFSection *Csect = SectionMap[ContainingCsect];
618     // Lookup the containing csect and add the symbol to it.
619     assert(Csect->MCSec->isCsect() && "only csect is supported now!");
620     Csect->Syms.emplace_back(XSym);
621 
622     // If the name does not fit in the storage provided in the symbol table
623     // entry, add it to the string table.
624     if (nameShouldBeInStringTable(XSym->getSymbolTableName()))
625       Strings.add(XSym->getSymbolTableName());
626   }
627 
628   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymSection.Entry;
629   if (CISI && nameShouldBeInStringTable(CISI->Name))
630     Strings.add(CISI->Name);
631 
632   FileNames = Asm.getFileNames();
633   // Emit ".file" as the source file name when there is no file name.
634   if (FileNames.empty())
635     FileNames.emplace_back(".file", 0);
636   for (const std::pair<std::string, size_t> &F : FileNames) {
637     if (nameShouldBeInStringTable(F.first))
638       Strings.add(F.first);
639   }
640 
641   Strings.finalize();
642   assignAddressesAndIndices(Layout);
643 }
644 
645 void XCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
646                                          const MCAsmLayout &Layout,
647                                          const MCFragment *Fragment,
648                                          const MCFixup &Fixup, MCValue Target,
649                                          uint64_t &FixedValue) {
650   auto getIndex = [this](const MCSymbol *Sym,
651                          const MCSectionXCOFF *ContainingCsect) {
652     // If we could not find the symbol directly in SymbolIndexMap, this symbol
653     // could either be a temporary symbol or an undefined symbol. In this case,
654     // we would need to have the relocation reference its csect instead.
655     return SymbolIndexMap.contains(Sym)
656                ? SymbolIndexMap[Sym]
657                : SymbolIndexMap[ContainingCsect->getQualNameSymbol()];
658   };
659 
660   auto getVirtualAddress =
661       [this, &Layout](const MCSymbol *Sym,
662                       const MCSectionXCOFF *ContainingSect) -> uint64_t {
663     // A DWARF section.
664     if (ContainingSect->isDwarfSect())
665       return Layout.getSymbolOffset(*Sym);
666 
667     // A csect.
668     if (!Sym->isDefined())
669       return SectionMap[ContainingSect]->Address;
670 
671     // A label.
672     assert(Sym->isDefined() && "not a valid object that has address!");
673     return SectionMap[ContainingSect]->Address + Layout.getSymbolOffset(*Sym);
674   };
675 
676   const MCSymbol *const SymA = &Target.getSymA()->getSymbol();
677 
678   MCAsmBackend &Backend = Asm.getBackend();
679   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
680                  MCFixupKindInfo::FKF_IsPCRel;
681 
682   uint8_t Type;
683   uint8_t SignAndSize;
684   std::tie(Type, SignAndSize) =
685       TargetObjectWriter->getRelocTypeAndSignSize(Target, Fixup, IsPCRel);
686 
687   const MCSectionXCOFF *SymASec = getContainingCsect(cast<MCSymbolXCOFF>(SymA));
688   assert(SectionMap.contains(SymASec) &&
689          "Expected containing csect to exist in map.");
690 
691   assert((Fixup.getOffset() <=
692           MaxRawDataSize - Layout.getFragmentOffset(Fragment)) &&
693          "Fragment offset + fixup offset is overflowed.");
694   uint32_t FixupOffsetInCsect =
695       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
696 
697   const uint32_t Index = getIndex(SymA, SymASec);
698   if (Type == XCOFF::RelocationType::R_POS ||
699       Type == XCOFF::RelocationType::R_TLS ||
700       Type == XCOFF::RelocationType::R_TLS_LE)
701     // The FixedValue should be symbol's virtual address in this object file
702     // plus any constant value that we might get.
703     FixedValue = getVirtualAddress(SymA, SymASec) + Target.getConstant();
704   else if (Type == XCOFF::RelocationType::R_TLSM)
705     // The FixedValue should always be zero since the region handle is only
706     // known at load time.
707     FixedValue = 0;
708   else if (Type == XCOFF::RelocationType::R_TOC ||
709            Type == XCOFF::RelocationType::R_TOCL) {
710     // For non toc-data external symbols, R_TOC type relocation will relocate to
711     // data symbols that have XCOFF::XTY_SD type csect. For toc-data external
712     // symbols, R_TOC type relocation will relocate to data symbols that have
713     // XCOFF_ER type csect. For XCOFF_ER kind symbols, there will be no TOC
714     // entry for them, so the FixedValue should always be 0.
715     if (SymASec->getCSectType() == XCOFF::XTY_ER) {
716       FixedValue = 0;
717     } else {
718       // The FixedValue should be the TOC entry offset from the TOC-base plus
719       // any constant offset value.
720       const int64_t TOCEntryOffset = SectionMap[SymASec]->Address -
721                                      TOCCsects.front().Address +
722                                      Target.getConstant();
723       if (Type == XCOFF::RelocationType::R_TOC && !isInt<16>(TOCEntryOffset))
724         report_fatal_error("TOCEntryOffset overflows in small code model mode");
725 
726       FixedValue = TOCEntryOffset;
727     }
728   } else if (Type == XCOFF::RelocationType::R_RBR) {
729     MCSectionXCOFF *ParentSec = cast<MCSectionXCOFF>(Fragment->getParent());
730     assert((SymASec->getMappingClass() == XCOFF::XMC_PR &&
731             ParentSec->getMappingClass() == XCOFF::XMC_PR) &&
732            "Only XMC_PR csect may have the R_RBR relocation.");
733 
734     // The address of the branch instruction should be the sum of section
735     // address, fragment offset and Fixup offset.
736     uint64_t BRInstrAddress =
737         SectionMap[ParentSec]->Address + FixupOffsetInCsect;
738     // The FixedValue should be the difference between symbol's virtual address
739     // and BR instr address plus any constant value.
740     FixedValue = getVirtualAddress(SymA, SymASec) - BRInstrAddress +
741                  Target.getConstant();
742   } else if (Type == XCOFF::RelocationType::R_REF) {
743     // The FixedValue and FixupOffsetInCsect should always be 0 since it
744     // specifies a nonrelocating reference.
745     FixedValue = 0;
746     FixupOffsetInCsect = 0;
747   }
748 
749   XCOFFRelocation Reloc = {Index, FixupOffsetInCsect, SignAndSize, Type};
750   MCSectionXCOFF *RelocationSec = cast<MCSectionXCOFF>(Fragment->getParent());
751   assert(SectionMap.contains(RelocationSec) &&
752          "Expected containing csect to exist in map.");
753   SectionMap[RelocationSec]->Relocations.push_back(Reloc);
754 
755   if (!Target.getSymB())
756     return;
757 
758   const MCSymbol *const SymB = &Target.getSymB()->getSymbol();
759   if (SymA == SymB)
760     report_fatal_error("relocation for opposite term is not yet supported");
761 
762   const MCSectionXCOFF *SymBSec = getContainingCsect(cast<MCSymbolXCOFF>(SymB));
763   assert(SectionMap.contains(SymBSec) &&
764          "Expected containing csect to exist in map.");
765   if (SymASec == SymBSec)
766     report_fatal_error(
767         "relocation for paired relocatable term is not yet supported");
768 
769   assert(Type == XCOFF::RelocationType::R_POS &&
770          "SymA must be R_POS here if it's not opposite term or paired "
771          "relocatable term.");
772   const uint32_t IndexB = getIndex(SymB, SymBSec);
773   // SymB must be R_NEG here, given the general form of Target(MCValue) is
774   // "SymbolA - SymbolB + imm64".
775   const uint8_t TypeB = XCOFF::RelocationType::R_NEG;
776   XCOFFRelocation RelocB = {IndexB, FixupOffsetInCsect, SignAndSize, TypeB};
777   SectionMap[RelocationSec]->Relocations.push_back(RelocB);
778   // We already folded "SymbolA + imm64" above when Type is R_POS for SymbolA,
779   // now we just need to fold "- SymbolB" here.
780   FixedValue -= getVirtualAddress(SymB, SymBSec);
781 }
782 
783 void XCOFFObjectWriter::writeSections(const MCAssembler &Asm,
784                                       const MCAsmLayout &Layout) {
785   uint64_t CurrentAddressLocation = 0;
786   for (const auto *Section : Sections)
787     writeSectionForControlSectionEntry(Asm, Layout, *Section,
788                                        CurrentAddressLocation);
789   for (const auto &DwarfSection : DwarfSections)
790     writeSectionForDwarfSectionEntry(Asm, Layout, DwarfSection,
791                                      CurrentAddressLocation);
792   writeSectionForExceptionSectionEntry(Asm, Layout, ExceptionSection,
793                                        CurrentAddressLocation);
794   writeSectionForCInfoSymSectionEntry(Asm, Layout, CInfoSymSection,
795                                       CurrentAddressLocation);
796 }
797 
798 uint64_t XCOFFObjectWriter::writeObject(MCAssembler &Asm,
799                                         const MCAsmLayout &Layout) {
800   // We always emit a timestamp of 0 for reproducibility, so ensure incremental
801   // linking is not enabled, in case, like with Windows COFF, such a timestamp
802   // is incompatible with incremental linking of XCOFF.
803   if (Asm.isIncrementalLinkerCompatible())
804     report_fatal_error("Incremental linking not supported for XCOFF.");
805 
806   finalizeSectionInfo();
807   uint64_t StartOffset = W.OS.tell();
808 
809   writeFileHeader();
810   writeAuxFileHeader();
811   writeSectionHeaderTable();
812   writeSections(Asm, Layout);
813   writeRelocations();
814   writeSymbolTable(Layout);
815   // Write the string table.
816   Strings.write(W.OS);
817 
818   return W.OS.tell() - StartOffset;
819 }
820 
821 bool XCOFFObjectWriter::nameShouldBeInStringTable(const StringRef &SymbolName) {
822   return SymbolName.size() > XCOFF::NameSize || is64Bit();
823 }
824 
825 void XCOFFObjectWriter::writeSymbolName(const StringRef &SymbolName) {
826   // Magic, Offset or SymbolName.
827   if (nameShouldBeInStringTable(SymbolName)) {
828     W.write<int32_t>(0);
829     W.write<uint32_t>(Strings.getOffset(SymbolName));
830   } else {
831     char Name[XCOFF::NameSize + 1];
832     std::strncpy(Name, SymbolName.data(), XCOFF::NameSize);
833     ArrayRef<char> NameRef(Name, XCOFF::NameSize);
834     W.write(NameRef);
835   }
836 }
837 
838 void XCOFFObjectWriter::writeSymbolEntry(StringRef SymbolName, uint64_t Value,
839                                          int16_t SectionNumber,
840                                          uint16_t SymbolType,
841                                          uint8_t StorageClass,
842                                          uint8_t NumberOfAuxEntries) {
843   if (is64Bit()) {
844     W.write<uint64_t>(Value);
845     W.write<uint32_t>(Strings.getOffset(SymbolName));
846   } else {
847     writeSymbolName(SymbolName);
848     W.write<uint32_t>(Value);
849   }
850   W.write<int16_t>(SectionNumber);
851   W.write<uint16_t>(SymbolType);
852   W.write<uint8_t>(StorageClass);
853   W.write<uint8_t>(NumberOfAuxEntries);
854 }
855 
856 void XCOFFObjectWriter::writeSymbolAuxCsectEntry(uint64_t SectionOrLength,
857                                                  uint8_t SymbolAlignmentAndType,
858                                                  uint8_t StorageMappingClass) {
859   W.write<uint32_t>(is64Bit() ? Lo_32(SectionOrLength) : SectionOrLength);
860   W.write<uint32_t>(0); // ParameterHashIndex
861   W.write<uint16_t>(0); // TypeChkSectNum
862   W.write<uint8_t>(SymbolAlignmentAndType);
863   W.write<uint8_t>(StorageMappingClass);
864   if (is64Bit()) {
865     W.write<uint32_t>(Hi_32(SectionOrLength));
866     W.OS.write_zeros(1); // Reserved
867     W.write<uint8_t>(XCOFF::AUX_CSECT);
868   } else {
869     W.write<uint32_t>(0); // StabInfoIndex
870     W.write<uint16_t>(0); // StabSectNum
871   }
872 }
873 
874 void XCOFFObjectWriter::writeSymbolAuxDwarfEntry(
875     uint64_t LengthOfSectionPortion, uint64_t NumberOfRelocEnt) {
876   writeWord(LengthOfSectionPortion);
877   if (!is64Bit())
878     W.OS.write_zeros(4); // Reserved
879   writeWord(NumberOfRelocEnt);
880   if (is64Bit()) {
881     W.OS.write_zeros(1); // Reserved
882     W.write<uint8_t>(XCOFF::AUX_SECT);
883   } else {
884     W.OS.write_zeros(6); // Reserved
885   }
886 }
887 
888 void XCOFFObjectWriter::writeSymbolEntryForCsectMemberLabel(
889     const Symbol &SymbolRef, const XCOFFSection &CSectionRef,
890     int16_t SectionIndex, uint64_t SymbolOffset) {
891   assert(SymbolOffset <= MaxRawDataSize - CSectionRef.Address &&
892          "Symbol address overflowed.");
893 
894   auto Entry = ExceptionSection.ExceptionTable.find(SymbolRef.MCSym->getName());
895   if (Entry != ExceptionSection.ExceptionTable.end()) {
896     writeSymbolEntry(SymbolRef.getSymbolTableName(),
897                      CSectionRef.Address + SymbolOffset, SectionIndex,
898                      // In the old version of the 32-bit XCOFF interpretation,
899                      // symbols may require bit 10 (0x0020) to be set if the
900                      // symbol is a function, otherwise the bit should be 0.
901                      is64Bit() ? SymbolRef.getVisibilityType()
902                                : SymbolRef.getVisibilityType() | 0x0020,
903                      SymbolRef.getStorageClass(),
904                      (is64Bit() && ExceptionSection.isDebugEnabled) ? 3 : 2);
905     if (is64Bit() && ExceptionSection.isDebugEnabled) {
906       // On 64 bit with debugging enabled, we have a csect, exception, and
907       // function auxilliary entries, so we must increment symbol index by 4.
908       writeSymbolAuxExceptionEntry(
909           ExceptionSection.FileOffsetToData +
910               getExceptionOffset(Entry->second.FunctionSymbol),
911           Entry->second.FunctionSize,
912           SymbolIndexMap[Entry->second.FunctionSymbol] + 4);
913     }
914     // For exception section entries, csect and function auxilliary entries
915     // must exist. On 64-bit there is also an exception auxilliary entry.
916     writeSymbolAuxFunctionEntry(
917         ExceptionSection.FileOffsetToData +
918             getExceptionOffset(Entry->second.FunctionSymbol),
919         Entry->second.FunctionSize, 0,
920         (is64Bit() && ExceptionSection.isDebugEnabled)
921             ? SymbolIndexMap[Entry->second.FunctionSymbol] + 4
922             : SymbolIndexMap[Entry->second.FunctionSymbol] + 3);
923   } else {
924     writeSymbolEntry(SymbolRef.getSymbolTableName(),
925                      CSectionRef.Address + SymbolOffset, SectionIndex,
926                      SymbolRef.getVisibilityType(),
927                      SymbolRef.getStorageClass());
928   }
929   writeSymbolAuxCsectEntry(CSectionRef.SymbolTableIndex, XCOFF::XTY_LD,
930                            CSectionRef.MCSec->getMappingClass());
931 }
932 
933 void XCOFFObjectWriter::writeSymbolEntryForDwarfSection(
934     const XCOFFSection &DwarfSectionRef, int16_t SectionIndex) {
935   assert(DwarfSectionRef.MCSec->isDwarfSect() && "Not a DWARF section!");
936 
937   writeSymbolEntry(DwarfSectionRef.getSymbolTableName(), /*Value=*/0,
938                    SectionIndex, /*SymbolType=*/0, XCOFF::C_DWARF);
939 
940   writeSymbolAuxDwarfEntry(DwarfSectionRef.Size);
941 }
942 
943 void XCOFFObjectWriter::writeSymbolEntryForControlSection(
944     const XCOFFSection &CSectionRef, int16_t SectionIndex,
945     XCOFF::StorageClass StorageClass) {
946   writeSymbolEntry(CSectionRef.getSymbolTableName(), CSectionRef.Address,
947                    SectionIndex, CSectionRef.getVisibilityType(), StorageClass);
948 
949   writeSymbolAuxCsectEntry(CSectionRef.Size, getEncodedType(CSectionRef.MCSec),
950                            CSectionRef.MCSec->getMappingClass());
951 }
952 
953 void XCOFFObjectWriter::writeSymbolAuxFunctionEntry(uint32_t EntryOffset,
954                                                     uint32_t FunctionSize,
955                                                     uint64_t LineNumberPointer,
956                                                     uint32_t EndIndex) {
957   if (is64Bit())
958     writeWord(LineNumberPointer);
959   else
960     W.write<uint32_t>(EntryOffset);
961   W.write<uint32_t>(FunctionSize);
962   if (!is64Bit())
963     writeWord(LineNumberPointer);
964   W.write<uint32_t>(EndIndex);
965   if (is64Bit()) {
966     W.OS.write_zeros(1);
967     W.write<uint8_t>(XCOFF::AUX_FCN);
968   } else {
969     W.OS.write_zeros(2);
970   }
971 }
972 
973 void XCOFFObjectWriter::writeSymbolAuxExceptionEntry(uint64_t EntryOffset,
974                                                      uint32_t FunctionSize,
975                                                      uint32_t EndIndex) {
976   assert(is64Bit() && "Exception auxilliary entries are 64-bit only.");
977   W.write<uint64_t>(EntryOffset);
978   W.write<uint32_t>(FunctionSize);
979   W.write<uint32_t>(EndIndex);
980   W.OS.write_zeros(1); // Pad (unused)
981   W.write<uint8_t>(XCOFF::AUX_EXCEPT);
982 }
983 
984 void XCOFFObjectWriter::writeFileHeader() {
985   W.write<uint16_t>(is64Bit() ? XCOFF::XCOFF64 : XCOFF::XCOFF32);
986   W.write<uint16_t>(SectionCount);
987   W.write<int32_t>(0); // TimeStamp
988   writeWord(SymbolTableOffset);
989   if (is64Bit()) {
990     W.write<uint16_t>(auxiliaryHeaderSize());
991     W.write<uint16_t>(0); // Flags
992     W.write<int32_t>(SymbolTableEntryCount);
993   } else {
994     W.write<int32_t>(SymbolTableEntryCount);
995     W.write<uint16_t>(auxiliaryHeaderSize());
996     W.write<uint16_t>(0); // Flags
997   }
998 }
999 
1000 void XCOFFObjectWriter::writeAuxFileHeader() {
1001   if (!auxiliaryHeaderSize())
1002     return;
1003   W.write<uint16_t>(0); // Magic
1004   W.write<uint16_t>(
1005       XCOFF::NEW_XCOFF_INTERPRET); // Version. The new interpretation of the
1006                                    // n_type field in the symbol table entry is
1007                                    // used in XCOFF32.
1008   W.write<uint32_t>(Sections[0]->Size);    // TextSize
1009   W.write<uint32_t>(Sections[1]->Size);    // InitDataSize
1010   W.write<uint32_t>(Sections[2]->Size);    // BssDataSize
1011   W.write<uint32_t>(0);                    // EntryPointAddr
1012   W.write<uint32_t>(Sections[0]->Address); // TextStartAddr
1013   W.write<uint32_t>(Sections[1]->Address); // DataStartAddr
1014 }
1015 
1016 void XCOFFObjectWriter::writeSectionHeader(const SectionEntry *Sec) {
1017   bool IsDwarf = (Sec->Flags & XCOFF::STYP_DWARF) != 0;
1018   bool IsOvrflo = (Sec->Flags & XCOFF::STYP_OVRFLO) != 0;
1019   // Nothing to write for this Section.
1020   if (Sec->Index == SectionEntry::UninitializedIndex)
1021     return;
1022 
1023   // Write Name.
1024   ArrayRef<char> NameRef(Sec->Name, XCOFF::NameSize);
1025   W.write(NameRef);
1026 
1027   // Write the Physical Address and Virtual Address.
1028   // We use 0 for DWARF sections' Physical and Virtual Addresses.
1029   writeWord(IsDwarf ? 0 : Sec->Address);
1030   // Since line number is not supported, we set it to 0 for overflow sections.
1031   writeWord((IsDwarf || IsOvrflo) ? 0 : Sec->Address);
1032 
1033   writeWord(Sec->Size);
1034   writeWord(Sec->FileOffsetToData);
1035   writeWord(Sec->FileOffsetToRelocations);
1036   writeWord(0); // FileOffsetToLineNumberInfo. Not supported yet.
1037 
1038   if (is64Bit()) {
1039     W.write<uint32_t>(Sec->RelocationCount);
1040     W.write<uint32_t>(0); // NumberOfLineNumbers. Not supported yet.
1041     W.write<int32_t>(Sec->Flags);
1042     W.OS.write_zeros(4);
1043   } else {
1044     // For the overflow section header, s_nreloc provides a reference to the
1045     // primary section header and s_nlnno must have the same value.
1046     // For common section headers, if either of s_nreloc or s_nlnno are set to
1047     // 65535, the other one must also be set to 65535.
1048     W.write<uint16_t>(Sec->RelocationCount);
1049     W.write<uint16_t>((IsOvrflo || Sec->RelocationCount == XCOFF::RelocOverflow)
1050                           ? Sec->RelocationCount
1051                           : 0); // NumberOfLineNumbers. Not supported yet.
1052     W.write<int32_t>(Sec->Flags);
1053   }
1054 }
1055 
1056 void XCOFFObjectWriter::writeSectionHeaderTable() {
1057   for (const auto *CsectSec : Sections)
1058     writeSectionHeader(CsectSec);
1059   for (const auto &DwarfSec : DwarfSections)
1060     writeSectionHeader(&DwarfSec);
1061   for (const auto &OverflowSec : OverflowSections)
1062     writeSectionHeader(&OverflowSec);
1063   if (hasExceptionSection())
1064     writeSectionHeader(&ExceptionSection);
1065   if (CInfoSymSection.Entry)
1066     writeSectionHeader(&CInfoSymSection);
1067 }
1068 
1069 void XCOFFObjectWriter::writeRelocation(XCOFFRelocation Reloc,
1070                                         const XCOFFSection &Section) {
1071   if (Section.MCSec->isCsect())
1072     writeWord(Section.Address + Reloc.FixupOffsetInCsect);
1073   else {
1074     // DWARF sections' address is set to 0.
1075     assert(Section.MCSec->isDwarfSect() && "unsupport section type!");
1076     writeWord(Reloc.FixupOffsetInCsect);
1077   }
1078   W.write<uint32_t>(Reloc.SymbolTableIndex);
1079   W.write<uint8_t>(Reloc.SignAndSize);
1080   W.write<uint8_t>(Reloc.Type);
1081 }
1082 
1083 void XCOFFObjectWriter::writeRelocations() {
1084   for (const auto *Section : Sections) {
1085     if (Section->Index == SectionEntry::UninitializedIndex)
1086       // Nothing to write for this Section.
1087       continue;
1088 
1089     for (const auto *Group : Section->Groups) {
1090       if (Group->empty())
1091         continue;
1092 
1093       for (const auto &Csect : *Group) {
1094         for (const auto Reloc : Csect.Relocations)
1095           writeRelocation(Reloc, Csect);
1096       }
1097     }
1098   }
1099 
1100   for (const auto &DwarfSection : DwarfSections)
1101     for (const auto &Reloc : DwarfSection.DwarfSect->Relocations)
1102       writeRelocation(Reloc, *DwarfSection.DwarfSect);
1103 }
1104 
1105 void XCOFFObjectWriter::writeSymbolTable(const MCAsmLayout &Layout) {
1106   // Write C_FILE symbols.
1107   for (const std::pair<std::string, size_t> &F : FileNames) {
1108     // The n_name of a C_FILE symbol is the source file's name when no auxiliary
1109     // entries are present.
1110     StringRef FileName = F.first;
1111 
1112     // For C_FILE symbols, the Source Language ID overlays the high-order byte
1113     // of the SymbolType field, and the CPU Version ID is defined as the
1114     // low-order byte.
1115     // AIX's system assembler determines the source language ID based on the
1116     // source file's name suffix, and the behavior here is consistent with it.
1117     uint8_t LangID;
1118     if (FileName.ends_with(".c"))
1119       LangID = XCOFF::TB_C;
1120     else if (FileName.ends_with_insensitive(".f") ||
1121              FileName.ends_with_insensitive(".f77") ||
1122              FileName.ends_with_insensitive(".f90") ||
1123              FileName.ends_with_insensitive(".f95") ||
1124              FileName.ends_with_insensitive(".f03") ||
1125              FileName.ends_with_insensitive(".f08"))
1126       LangID = XCOFF::TB_Fortran;
1127     else
1128       LangID = XCOFF::TB_CPLUSPLUS;
1129     uint8_t CpuID;
1130     if (is64Bit())
1131       CpuID = XCOFF::TCPU_PPC64;
1132     else
1133       CpuID = XCOFF::TCPU_COM;
1134 
1135     writeSymbolEntry(FileName, /*Value=*/0, XCOFF::ReservedSectionNum::N_DEBUG,
1136                      /*SymbolType=*/(LangID << 8) | CpuID, XCOFF::C_FILE,
1137                      /*NumberOfAuxEntries=*/0);
1138   }
1139 
1140   if (CInfoSymSection.Entry)
1141     writeSymbolEntry(CInfoSymSection.Entry->Name, CInfoSymSection.Entry->Offset,
1142                      CInfoSymSection.Index,
1143                      /*SymbolType=*/0, XCOFF::C_INFO,
1144                      /*NumberOfAuxEntries=*/0);
1145 
1146   for (const auto &Csect : UndefinedCsects) {
1147     writeSymbolEntryForControlSection(Csect, XCOFF::ReservedSectionNum::N_UNDEF,
1148                                       Csect.MCSec->getStorageClass());
1149   }
1150 
1151   for (const auto *Section : Sections) {
1152     if (Section->Index == SectionEntry::UninitializedIndex)
1153       // Nothing to write for this Section.
1154       continue;
1155 
1156     for (const auto *Group : Section->Groups) {
1157       if (Group->empty())
1158         continue;
1159 
1160       const int16_t SectionIndex = Section->Index;
1161       for (const auto &Csect : *Group) {
1162         // Write out the control section first and then each symbol in it.
1163         writeSymbolEntryForControlSection(Csect, SectionIndex,
1164                                           Csect.MCSec->getStorageClass());
1165 
1166         for (const auto &Sym : Csect.Syms)
1167           writeSymbolEntryForCsectMemberLabel(
1168               Sym, Csect, SectionIndex, Layout.getSymbolOffset(*(Sym.MCSym)));
1169       }
1170     }
1171   }
1172 
1173   for (const auto &DwarfSection : DwarfSections)
1174     writeSymbolEntryForDwarfSection(*DwarfSection.DwarfSect,
1175                                     DwarfSection.Index);
1176 }
1177 
1178 void XCOFFObjectWriter::finalizeRelocationInfo(SectionEntry *Sec,
1179                                                uint64_t RelCount) {
1180   // Handles relocation field overflows in an XCOFF32 file. An XCOFF64 file
1181   // may not contain an overflow section header.
1182   if (!is64Bit() && (RelCount >= static_cast<uint32_t>(XCOFF::RelocOverflow))) {
1183     // Generate an overflow section header.
1184     SectionEntry SecEntry(".ovrflo", XCOFF::STYP_OVRFLO);
1185 
1186     // This field specifies the file section number of the section header that
1187     // overflowed.
1188     SecEntry.RelocationCount = Sec->Index;
1189 
1190     // This field specifies the number of relocation entries actually
1191     // required.
1192     SecEntry.Address = RelCount;
1193     SecEntry.Index = ++SectionCount;
1194     OverflowSections.push_back(std::move(SecEntry));
1195 
1196     // The field in the primary section header is always 65535
1197     // (XCOFF::RelocOverflow).
1198     Sec->RelocationCount = XCOFF::RelocOverflow;
1199   } else {
1200     Sec->RelocationCount = RelCount;
1201   }
1202 }
1203 
1204 void XCOFFObjectWriter::calcOffsetToRelocations(SectionEntry *Sec,
1205                                                 uint64_t &RawPointer) {
1206   if (!Sec->RelocationCount)
1207     return;
1208 
1209   Sec->FileOffsetToRelocations = RawPointer;
1210   uint64_t RelocationSizeInSec = 0;
1211   if (!is64Bit() &&
1212       Sec->RelocationCount == static_cast<uint32_t>(XCOFF::RelocOverflow)) {
1213     // Find its corresponding overflow section.
1214     for (auto &OverflowSec : OverflowSections) {
1215       if (OverflowSec.RelocationCount == static_cast<uint32_t>(Sec->Index)) {
1216         RelocationSizeInSec =
1217             OverflowSec.Address * XCOFF::RelocationSerializationSize32;
1218 
1219         // This field must have the same values as in the corresponding
1220         // primary section header.
1221         OverflowSec.FileOffsetToRelocations = Sec->FileOffsetToRelocations;
1222       }
1223     }
1224     assert(RelocationSizeInSec && "Overflow section header doesn't exist.");
1225   } else {
1226     RelocationSizeInSec = Sec->RelocationCount *
1227                           (is64Bit() ? XCOFF::RelocationSerializationSize64
1228                                      : XCOFF::RelocationSerializationSize32);
1229   }
1230 
1231   RawPointer += RelocationSizeInSec;
1232   if (RawPointer > MaxRawDataSize)
1233     report_fatal_error("Relocation data overflowed this object file.");
1234 }
1235 
1236 void XCOFFObjectWriter::finalizeSectionInfo() {
1237   for (auto *Section : Sections) {
1238     if (Section->Index == SectionEntry::UninitializedIndex)
1239       // Nothing to record for this Section.
1240       continue;
1241 
1242     uint64_t RelCount = 0;
1243     for (const auto *Group : Section->Groups) {
1244       if (Group->empty())
1245         continue;
1246 
1247       for (auto &Csect : *Group)
1248         RelCount += Csect.Relocations.size();
1249     }
1250     finalizeRelocationInfo(Section, RelCount);
1251   }
1252 
1253   for (auto &DwarfSection : DwarfSections)
1254     finalizeRelocationInfo(&DwarfSection,
1255                            DwarfSection.DwarfSect->Relocations.size());
1256 
1257   // Calculate the RawPointer value for all headers.
1258   uint64_t RawPointer =
1259       (is64Bit() ? (XCOFF::FileHeaderSize64 +
1260                     SectionCount * XCOFF::SectionHeaderSize64)
1261                  : (XCOFF::FileHeaderSize32 +
1262                     SectionCount * XCOFF::SectionHeaderSize32)) +
1263       auxiliaryHeaderSize();
1264 
1265   // Calculate the file offset to the section data.
1266   for (auto *Sec : Sections) {
1267     if (Sec->Index == SectionEntry::UninitializedIndex || Sec->IsVirtual)
1268       continue;
1269 
1270     RawPointer = Sec->advanceFileOffset(MaxRawDataSize, RawPointer);
1271   }
1272 
1273   if (!DwarfSections.empty()) {
1274     RawPointer += PaddingsBeforeDwarf;
1275     for (auto &DwarfSection : DwarfSections) {
1276       RawPointer = DwarfSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1277     }
1278   }
1279 
1280   if (hasExceptionSection())
1281     RawPointer = ExceptionSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1282 
1283   if (CInfoSymSection.Entry)
1284     RawPointer = CInfoSymSection.advanceFileOffset(MaxRawDataSize, RawPointer);
1285 
1286   for (auto *Sec : Sections) {
1287     if (Sec->Index != SectionEntry::UninitializedIndex)
1288       calcOffsetToRelocations(Sec, RawPointer);
1289   }
1290 
1291   for (auto &DwarfSec : DwarfSections)
1292     calcOffsetToRelocations(&DwarfSec, RawPointer);
1293 
1294   // TODO Error check that the number of symbol table entries fits in 32-bits
1295   // signed ...
1296   if (SymbolTableEntryCount)
1297     SymbolTableOffset = RawPointer;
1298 }
1299 
1300 void XCOFFObjectWriter::addExceptionEntry(
1301     const MCSymbol *Symbol, const MCSymbol *Trap, unsigned LanguageCode,
1302     unsigned ReasonCode, unsigned FunctionSize, bool hasDebug) {
1303   // If a module had debug info, debugging is enabled and XCOFF emits the
1304   // exception auxilliary entry.
1305   if (hasDebug)
1306     ExceptionSection.isDebugEnabled = true;
1307   auto Entry = ExceptionSection.ExceptionTable.find(Symbol->getName());
1308   if (Entry != ExceptionSection.ExceptionTable.end()) {
1309     Entry->second.Entries.push_back(
1310         ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1311     return;
1312   }
1313   ExceptionInfo NewEntry;
1314   NewEntry.FunctionSymbol = Symbol;
1315   NewEntry.FunctionSize = FunctionSize;
1316   NewEntry.Entries.push_back(
1317       ExceptionTableEntry(Trap, LanguageCode, ReasonCode));
1318   ExceptionSection.ExceptionTable.insert(
1319       std::pair<const StringRef, ExceptionInfo>(Symbol->getName(), NewEntry));
1320 }
1321 
1322 unsigned XCOFFObjectWriter::getExceptionSectionSize() {
1323   unsigned EntryNum = 0;
1324 
1325   for (auto it = ExceptionSection.ExceptionTable.begin();
1326        it != ExceptionSection.ExceptionTable.end(); ++it)
1327     // The size() gets +1 to account for the initial entry containing the
1328     // symbol table index.
1329     EntryNum += it->second.Entries.size() + 1;
1330 
1331   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1332                                : XCOFF::ExceptionSectionEntrySize32);
1333 }
1334 
1335 unsigned XCOFFObjectWriter::getExceptionOffset(const MCSymbol *Symbol) {
1336   unsigned EntryNum = 0;
1337   for (auto it = ExceptionSection.ExceptionTable.begin();
1338        it != ExceptionSection.ExceptionTable.end(); ++it) {
1339     if (Symbol == it->second.FunctionSymbol)
1340       break;
1341     EntryNum += it->second.Entries.size() + 1;
1342   }
1343   return EntryNum * (is64Bit() ? XCOFF::ExceptionSectionEntrySize64
1344                                : XCOFF::ExceptionSectionEntrySize32);
1345 }
1346 
1347 void XCOFFObjectWriter::addCInfoSymEntry(StringRef Name, StringRef Metadata) {
1348   assert(!CInfoSymSection.Entry && "Multiple entries are not supported");
1349   CInfoSymSection.addEntry(
1350       std::make_unique<CInfoSymInfo>(Name.str(), Metadata.str()));
1351 }
1352 
1353 void XCOFFObjectWriter::assignAddressesAndIndices(const MCAsmLayout &Layout) {
1354   // The symbol table starts with all the C_FILE symbols.
1355   uint32_t SymbolTableIndex = FileNames.size();
1356 
1357   if (CInfoSymSection.Entry)
1358     SymbolTableIndex++;
1359 
1360   // Calculate indices for undefined symbols.
1361   for (auto &Csect : UndefinedCsects) {
1362     Csect.Size = 0;
1363     Csect.Address = 0;
1364     Csect.SymbolTableIndex = SymbolTableIndex;
1365     SymbolIndexMap[Csect.MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1366     // 1 main and 1 auxiliary symbol table entry for each contained symbol.
1367     SymbolTableIndex += 2;
1368   }
1369 
1370   // The address corrresponds to the address of sections and symbols in the
1371   // object file. We place the shared address 0 immediately after the
1372   // section header table.
1373   uint64_t Address = 0;
1374   // Section indices are 1-based in XCOFF.
1375   int32_t SectionIndex = 1;
1376   bool HasTDataSection = false;
1377 
1378   for (auto *Section : Sections) {
1379     const bool IsEmpty =
1380         llvm::all_of(Section->Groups,
1381                      [](const CsectGroup *Group) { return Group->empty(); });
1382     if (IsEmpty)
1383       continue;
1384 
1385     if (SectionIndex > MaxSectionIndex)
1386       report_fatal_error("Section index overflow!");
1387     Section->Index = SectionIndex++;
1388     SectionCount++;
1389 
1390     bool SectionAddressSet = false;
1391     // Reset the starting address to 0 for TData section.
1392     if (Section->Flags == XCOFF::STYP_TDATA) {
1393       Address = 0;
1394       HasTDataSection = true;
1395     }
1396     // Reset the starting address to 0 for TBSS section if the object file does
1397     // not contain TData Section.
1398     if ((Section->Flags == XCOFF::STYP_TBSS) && !HasTDataSection)
1399       Address = 0;
1400 
1401     for (auto *Group : Section->Groups) {
1402       if (Group->empty())
1403         continue;
1404 
1405       for (auto &Csect : *Group) {
1406         const MCSectionXCOFF *MCSec = Csect.MCSec;
1407         Csect.Address = alignTo(Address, MCSec->getAlign());
1408         Csect.Size = Layout.getSectionAddressSize(MCSec);
1409         Address = Csect.Address + Csect.Size;
1410         Csect.SymbolTableIndex = SymbolTableIndex;
1411         SymbolIndexMap[MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
1412         // 1 main and 1 auxiliary symbol table entry for the csect.
1413         SymbolTableIndex += 2;
1414 
1415         for (auto &Sym : Csect.Syms) {
1416           bool hasExceptEntry = false;
1417           auto Entry =
1418               ExceptionSection.ExceptionTable.find(Sym.MCSym->getName());
1419           if (Entry != ExceptionSection.ExceptionTable.end()) {
1420             hasExceptEntry = true;
1421             for (auto &TrapEntry : Entry->second.Entries) {
1422               TrapEntry.TrapAddress = Layout.getSymbolOffset(*(Sym.MCSym)) +
1423                                       TrapEntry.Trap->getOffset();
1424             }
1425           }
1426           Sym.SymbolTableIndex = SymbolTableIndex;
1427           SymbolIndexMap[Sym.MCSym] = Sym.SymbolTableIndex;
1428           // 1 main and 1 auxiliary symbol table entry for each contained
1429           // symbol. For symbols with exception section entries, a function
1430           // auxilliary entry is needed, and on 64-bit XCOFF with debugging
1431           // enabled, an additional exception auxilliary entry is needed.
1432           SymbolTableIndex += 2;
1433           if (hasExceptionSection() && hasExceptEntry) {
1434             if (is64Bit() && ExceptionSection.isDebugEnabled)
1435               SymbolTableIndex += 2;
1436             else
1437               SymbolTableIndex += 1;
1438           }
1439         }
1440       }
1441 
1442       if (!SectionAddressSet) {
1443         Section->Address = Group->front().Address;
1444         SectionAddressSet = true;
1445       }
1446     }
1447 
1448     // Make sure the address of the next section aligned to
1449     // DefaultSectionAlign.
1450     Address = alignTo(Address, DefaultSectionAlign);
1451     Section->Size = Address - Section->Address;
1452   }
1453 
1454   // Start to generate DWARF sections. Sections other than DWARF section use
1455   // DefaultSectionAlign as the default alignment, while DWARF sections have
1456   // their own alignments. If these two alignments are not the same, we need
1457   // some paddings here and record the paddings bytes for FileOffsetToData
1458   // calculation.
1459   if (!DwarfSections.empty())
1460     PaddingsBeforeDwarf =
1461         alignTo(Address,
1462                 (*DwarfSections.begin()).DwarfSect->MCSec->getAlign()) -
1463         Address;
1464 
1465   DwarfSectionEntry *LastDwarfSection = nullptr;
1466   for (auto &DwarfSection : DwarfSections) {
1467     assert((SectionIndex <= MaxSectionIndex) && "Section index overflow!");
1468 
1469     XCOFFSection &DwarfSect = *DwarfSection.DwarfSect;
1470     const MCSectionXCOFF *MCSec = DwarfSect.MCSec;
1471 
1472     // Section index.
1473     DwarfSection.Index = SectionIndex++;
1474     SectionCount++;
1475 
1476     // Symbol index.
1477     DwarfSect.SymbolTableIndex = SymbolTableIndex;
1478     SymbolIndexMap[MCSec->getQualNameSymbol()] = DwarfSect.SymbolTableIndex;
1479     // 1 main and 1 auxiliary symbol table entry for the csect.
1480     SymbolTableIndex += 2;
1481 
1482     // Section address. Make it align to section alignment.
1483     // We use address 0 for DWARF sections' Physical and Virtual Addresses.
1484     // This address is used to tell where is the section in the final object.
1485     // See writeSectionForDwarfSectionEntry().
1486     DwarfSection.Address = DwarfSect.Address =
1487         alignTo(Address, MCSec->getAlign());
1488 
1489     // Section size.
1490     // For DWARF section, we must use the real size which may be not aligned.
1491     DwarfSection.Size = DwarfSect.Size = Layout.getSectionAddressSize(MCSec);
1492 
1493     Address = DwarfSection.Address + DwarfSection.Size;
1494 
1495     if (LastDwarfSection)
1496       LastDwarfSection->MemorySize =
1497           DwarfSection.Address - LastDwarfSection->Address;
1498     LastDwarfSection = &DwarfSection;
1499   }
1500   if (LastDwarfSection) {
1501     // Make the final DWARF section address align to the default section
1502     // alignment for follow contents.
1503     Address = alignTo(LastDwarfSection->Address + LastDwarfSection->Size,
1504                       DefaultSectionAlign);
1505     LastDwarfSection->MemorySize = Address - LastDwarfSection->Address;
1506   }
1507   if (hasExceptionSection()) {
1508     ExceptionSection.Index = SectionIndex++;
1509     SectionCount++;
1510     ExceptionSection.Address = 0;
1511     ExceptionSection.Size = getExceptionSectionSize();
1512     Address += ExceptionSection.Size;
1513     Address = alignTo(Address, DefaultSectionAlign);
1514   }
1515 
1516   if (CInfoSymSection.Entry) {
1517     CInfoSymSection.Index = SectionIndex++;
1518     SectionCount++;
1519     CInfoSymSection.Address = 0;
1520     Address += CInfoSymSection.Size;
1521     Address = alignTo(Address, DefaultSectionAlign);
1522   }
1523 
1524   SymbolTableEntryCount = SymbolTableIndex;
1525 }
1526 
1527 void XCOFFObjectWriter::writeSectionForControlSectionEntry(
1528     const MCAssembler &Asm, const MCAsmLayout &Layout,
1529     const CsectSectionEntry &CsectEntry, uint64_t &CurrentAddressLocation) {
1530   // Nothing to write for this Section.
1531   if (CsectEntry.Index == SectionEntry::UninitializedIndex)
1532     return;
1533 
1534   // There could be a gap (without corresponding zero padding) between
1535   // sections.
1536   // There could be a gap (without corresponding zero padding) between
1537   // sections.
1538   assert(((CurrentAddressLocation <= CsectEntry.Address) ||
1539           (CsectEntry.Flags == XCOFF::STYP_TDATA) ||
1540           (CsectEntry.Flags == XCOFF::STYP_TBSS)) &&
1541          "CurrentAddressLocation should be less than or equal to section "
1542          "address if the section is not TData or TBSS.");
1543 
1544   CurrentAddressLocation = CsectEntry.Address;
1545 
1546   // For virtual sections, nothing to write. But need to increase
1547   // CurrentAddressLocation for later sections like DWARF section has a correct
1548   // writing location.
1549   if (CsectEntry.IsVirtual) {
1550     CurrentAddressLocation += CsectEntry.Size;
1551     return;
1552   }
1553 
1554   for (const auto &Group : CsectEntry.Groups) {
1555     for (const auto &Csect : *Group) {
1556       if (uint32_t PaddingSize = Csect.Address - CurrentAddressLocation)
1557         W.OS.write_zeros(PaddingSize);
1558       if (Csect.Size)
1559         Asm.writeSectionData(W.OS, Csect.MCSec, Layout);
1560       CurrentAddressLocation = Csect.Address + Csect.Size;
1561     }
1562   }
1563 
1564   // The size of the tail padding in a section is the end virtual address of
1565   // the current section minus the the end virtual address of the last csect
1566   // in that section.
1567   if (uint64_t PaddingSize =
1568           CsectEntry.Address + CsectEntry.Size - CurrentAddressLocation) {
1569     W.OS.write_zeros(PaddingSize);
1570     CurrentAddressLocation += PaddingSize;
1571   }
1572 }
1573 
1574 void XCOFFObjectWriter::writeSectionForDwarfSectionEntry(
1575     const MCAssembler &Asm, const MCAsmLayout &Layout,
1576     const DwarfSectionEntry &DwarfEntry, uint64_t &CurrentAddressLocation) {
1577   // There could be a gap (without corresponding zero padding) between
1578   // sections. For example DWARF section alignment is bigger than
1579   // DefaultSectionAlign.
1580   assert(CurrentAddressLocation <= DwarfEntry.Address &&
1581          "CurrentAddressLocation should be less than or equal to section "
1582          "address.");
1583 
1584   if (uint64_t PaddingSize = DwarfEntry.Address - CurrentAddressLocation)
1585     W.OS.write_zeros(PaddingSize);
1586 
1587   if (DwarfEntry.Size)
1588     Asm.writeSectionData(W.OS, DwarfEntry.DwarfSect->MCSec, Layout);
1589 
1590   CurrentAddressLocation = DwarfEntry.Address + DwarfEntry.Size;
1591 
1592   // DWARF section size is not aligned to DefaultSectionAlign.
1593   // Make sure CurrentAddressLocation is aligned to DefaultSectionAlign.
1594   uint32_t Mod = CurrentAddressLocation % DefaultSectionAlign;
1595   uint32_t TailPaddingSize = Mod ? DefaultSectionAlign - Mod : 0;
1596   if (TailPaddingSize)
1597     W.OS.write_zeros(TailPaddingSize);
1598 
1599   CurrentAddressLocation += TailPaddingSize;
1600 }
1601 
1602 void XCOFFObjectWriter::writeSectionForExceptionSectionEntry(
1603     const MCAssembler &Asm, const MCAsmLayout &Layout,
1604     ExceptionSectionEntry &ExceptionEntry, uint64_t &CurrentAddressLocation) {
1605   for (auto it = ExceptionEntry.ExceptionTable.begin();
1606        it != ExceptionEntry.ExceptionTable.end(); it++) {
1607     // For every symbol that has exception entries, you must start the entries
1608     // with an initial symbol table index entry
1609     W.write<uint32_t>(SymbolIndexMap[it->second.FunctionSymbol]);
1610     if (is64Bit()) {
1611       // 4-byte padding on 64-bit.
1612       W.OS.write_zeros(4);
1613     }
1614     W.OS.write_zeros(2);
1615     for (auto &TrapEntry : it->second.Entries) {
1616       writeWord(TrapEntry.TrapAddress);
1617       W.write<uint8_t>(TrapEntry.Lang);
1618       W.write<uint8_t>(TrapEntry.Reason);
1619     }
1620   }
1621 
1622   CurrentAddressLocation += getExceptionSectionSize();
1623 }
1624 
1625 void XCOFFObjectWriter::writeSectionForCInfoSymSectionEntry(
1626     const MCAssembler &Asm, const MCAsmLayout &Layout,
1627     CInfoSymSectionEntry &CInfoSymEntry, uint64_t &CurrentAddressLocation) {
1628   if (!CInfoSymSection.Entry)
1629     return;
1630 
1631   constexpr int WordSize = sizeof(uint32_t);
1632   std::unique_ptr<CInfoSymInfo> &CISI = CInfoSymEntry.Entry;
1633   const std::string &Metadata = CISI->Metadata;
1634 
1635   // Emit the 4-byte length of the metadata.
1636   W.write<uint32_t>(Metadata.size());
1637 
1638   if (Metadata.size() == 0)
1639     return;
1640 
1641   // Write out the payload one word at a time.
1642   size_t Index = 0;
1643   while (Index + WordSize <= Metadata.size()) {
1644     uint32_t NextWord =
1645         llvm::support::endian::read32be(Metadata.data() + Index);
1646     W.write<uint32_t>(NextWord);
1647     Index += WordSize;
1648   }
1649 
1650   // If there is padding, we have at least one byte of payload left to emit.
1651   if (CISI->paddingSize()) {
1652     std::array<uint8_t, WordSize> LastWord = {0};
1653     ::memcpy(LastWord.data(), Metadata.data() + Index, Metadata.size() - Index);
1654     W.write<uint32_t>(llvm::support::endian::read32be(LastWord.data()));
1655   }
1656 
1657   CurrentAddressLocation += CISI->size();
1658 }
1659 
1660 // Takes the log base 2 of the alignment and shifts the result into the 5 most
1661 // significant bits of a byte, then or's in the csect type into the least
1662 // significant 3 bits.
1663 uint8_t getEncodedType(const MCSectionXCOFF *Sec) {
1664   unsigned Log2Align = Log2(Sec->getAlign());
1665   // Result is a number in the range [0, 31] which fits in the 5 least
1666   // significant bits. Shift this value into the 5 most significant bits, and
1667   // bitwise-or in the csect type.
1668   uint8_t EncodedAlign = Log2Align << 3;
1669   return EncodedAlign | Sec->getCSectType();
1670 }
1671 
1672 } // end anonymous namespace
1673 
1674 std::unique_ptr<MCObjectWriter>
1675 llvm::createXCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
1676                               raw_pwrite_stream &OS) {
1677   return std::make_unique<XCOFFObjectWriter>(std::move(MOTW), OS);
1678 }
1679