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/EndianStream.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/MathExtras.h"
28 
29 #include <deque>
30 
31 using namespace llvm;
32 
33 // An XCOFF object file has a limited set of predefined sections. The most
34 // important ones for us (right now) are:
35 // .text --> contains program code and read-only data.
36 // .data --> contains initialized data, function descriptors, and the TOC.
37 // .bss  --> contains uninitialized data.
38 // Each of these sections is composed of 'Control Sections'. A Control Section
39 // is more commonly referred to as a csect. A csect is an indivisible unit of
40 // code or data, and acts as a container for symbols. A csect is mapped
41 // into a section based on its storage-mapping class, with the exception of
42 // XMC_RW which gets mapped to either .data or .bss based on whether it's
43 // explicitly initialized or not.
44 //
45 // We don't represent the sections in the MC layer as there is nothing
46 // interesting about them at at that level: they carry information that is
47 // only relevant to the ObjectWriter, so we materialize them in this class.
48 namespace {
49 
50 constexpr unsigned DefaultSectionAlign = 4;
51 constexpr int16_t MaxSectionIndex = INT16_MAX;
52 
53 // Packs the csect's alignment and type into a byte.
54 uint8_t getEncodedType(const MCSectionXCOFF *);
55 
56 struct XCOFFRelocation {
57   uint32_t SymbolTableIndex;
58   uint32_t FixupOffsetInCsect;
59   uint8_t SignAndSize;
60   uint8_t Type;
61 };
62 
63 // Wrapper around an MCSymbolXCOFF.
64 struct Symbol {
65   const MCSymbolXCOFF *const MCSym;
66   uint32_t SymbolTableIndex;
67 
68   XCOFF::StorageClass getStorageClass() const {
69     return MCSym->getStorageClass();
70   }
71   StringRef getSymbolTableName() const { return MCSym->getSymbolTableName(); }
72   Symbol(const MCSymbolXCOFF *MCSym) : MCSym(MCSym), SymbolTableIndex(-1) {}
73 };
74 
75 // Wrapper for an MCSectionXCOFF.
76 struct ControlSection {
77   const MCSectionXCOFF *const MCCsect;
78   uint32_t SymbolTableIndex;
79   uint32_t Address;
80   uint32_t Size;
81 
82   SmallVector<Symbol, 1> Syms;
83   SmallVector<XCOFFRelocation, 1> Relocations;
84   StringRef getSymbolTableName() const { return MCCsect->getSymbolTableName(); }
85   ControlSection(const MCSectionXCOFF *MCSec)
86       : MCCsect(MCSec), SymbolTableIndex(-1), Address(-1), Size(0) {}
87 };
88 
89 // Type to be used for a container representing a set of csects with
90 // (approximately) the same storage mapping class. For example all the csects
91 // with a storage mapping class of `xmc_pr` will get placed into the same
92 // container.
93 using CsectGroup = std::deque<ControlSection>;
94 using CsectGroups = std::deque<CsectGroup *>;
95 
96 // Represents the data related to a section excluding the csects that make up
97 // the raw data of the section. The csects are stored separately as not all
98 // sections contain csects, and some sections contain csects which are better
99 // stored separately, e.g. the .data section containing read-write, descriptor,
100 // TOCBase and TOC-entry csects.
101 struct Section {
102   char Name[XCOFF::NameSize];
103   // The physical/virtual address of the section. For an object file
104   // these values are equivalent.
105   uint32_t Address;
106   uint32_t Size;
107   uint32_t FileOffsetToData;
108   uint32_t FileOffsetToRelocations;
109   uint32_t RelocationCount;
110   int32_t Flags;
111 
112   int16_t Index;
113 
114   // Virtual sections do not need storage allocated in the object file.
115   const bool IsVirtual;
116 
117   // XCOFF has special section numbers for symbols:
118   // -2 Specifies N_DEBUG, a special symbolic debugging symbol.
119   // -1 Specifies N_ABS, an absolute symbol. The symbol has a value but is not
120   // relocatable.
121   //  0 Specifies N_UNDEF, an undefined external symbol.
122   // Therefore, we choose -3 (N_DEBUG - 1) to represent a section index that
123   // hasn't been initialized.
124   static constexpr int16_t UninitializedIndex =
125       XCOFF::ReservedSectionNum::N_DEBUG - 1;
126 
127   CsectGroups Groups;
128 
129   void reset() {
130     Address = 0;
131     Size = 0;
132     FileOffsetToData = 0;
133     FileOffsetToRelocations = 0;
134     RelocationCount = 0;
135     Index = UninitializedIndex;
136     // Clear any csects we have stored.
137     for (auto *Group : Groups)
138       Group->clear();
139   }
140 
141   Section(StringRef N, XCOFF::SectionTypeFlags Flags, bool IsVirtual,
142           CsectGroups Groups)
143       : Name(), Address(0), Size(0), FileOffsetToData(0),
144         FileOffsetToRelocations(0), RelocationCount(0), Flags(Flags),
145         Index(UninitializedIndex), IsVirtual(IsVirtual), Groups(Groups) {
146     assert(N.size() <= XCOFF::NameSize && "section name too long");
147     memcpy(Name, N.data(), N.size());
148   }
149 };
150 
151 class XCOFFObjectWriter : public MCObjectWriter {
152 
153   uint32_t SymbolTableEntryCount = 0;
154   uint32_t SymbolTableOffset = 0;
155   uint16_t SectionCount = 0;
156   uint32_t RelocationEntryOffset = 0;
157 
158   support::endian::Writer W;
159   std::unique_ptr<MCXCOFFObjectTargetWriter> TargetObjectWriter;
160   StringTableBuilder Strings;
161 
162   // Maps the MCSection representation to its corresponding ControlSection
163   // wrapper. Needed for finding the ControlSection to insert an MCSymbol into
164   // from its containing MCSectionXCOFF.
165   DenseMap<const MCSectionXCOFF *, ControlSection *> SectionMap;
166 
167   // Maps the MCSymbol representation to its corrresponding symbol table index.
168   // Needed for relocation.
169   DenseMap<const MCSymbol *, uint32_t> SymbolIndexMap;
170 
171   // CsectGroups. These store the csects which make up different parts of
172   // the sections. Should have one for each set of csects that get mapped into
173   // the same section and get handled in a 'similar' way.
174   CsectGroup UndefinedCsects;
175   CsectGroup ProgramCodeCsects;
176   CsectGroup ReadOnlyCsects;
177   CsectGroup DataCsects;
178   CsectGroup FuncDSCsects;
179   CsectGroup TOCCsects;
180   CsectGroup BSSCsects;
181   CsectGroup TDataCsects;
182   CsectGroup TBSSCsects;
183 
184   // The Predefined sections.
185   Section Text;
186   Section Data;
187   Section BSS;
188   Section TData;
189   Section TBSS;
190 
191   // All the XCOFF sections, in the order they will appear in the section header
192   // table.
193   std::array<Section *const, 5> Sections{{&Text, &Data, &BSS, &TData, &TBSS}};
194 
195   CsectGroup &getCsectGroup(const MCSectionXCOFF *MCSec);
196 
197   virtual void reset() override;
198 
199   void executePostLayoutBinding(MCAssembler &, const MCAsmLayout &) override;
200 
201   void recordRelocation(MCAssembler &, const MCAsmLayout &, const MCFragment *,
202                         const MCFixup &, MCValue, uint64_t &) override;
203 
204   uint64_t writeObject(MCAssembler &, const MCAsmLayout &) override;
205 
206   static bool nameShouldBeInStringTable(const StringRef &);
207   void writeSymbolName(const StringRef &);
208   void writeSymbolTableEntryForCsectMemberLabel(const Symbol &,
209                                                 const ControlSection &, int16_t,
210                                                 uint64_t);
211   void writeSymbolTableEntryForControlSection(const ControlSection &, int16_t,
212                                               XCOFF::StorageClass);
213   void writeFileHeader();
214   void writeSectionHeaderTable();
215   void writeSections(const MCAssembler &Asm, const MCAsmLayout &Layout);
216   void writeSymbolTable(const MCAsmLayout &Layout);
217   void writeRelocations();
218   void writeRelocation(XCOFFRelocation Reloc, const ControlSection &CSection);
219 
220   // Called after all the csects and symbols have been processed by
221   // `executePostLayoutBinding`, this function handles building up the majority
222   // of the structures in the object file representation. Namely:
223   // *) Calculates physical/virtual addresses, raw-pointer offsets, and section
224   //    sizes.
225   // *) Assigns symbol table indices.
226   // *) Builds up the section header table by adding any non-empty sections to
227   //    `Sections`.
228   void assignAddressesAndIndices(const MCAsmLayout &);
229   void finalizeSectionInfo();
230 
231   bool
232   needsAuxiliaryHeader() const { /* TODO aux header support not implemented. */
233     return false;
234   }
235 
236   // Returns the size of the auxiliary header to be written to the object file.
237   size_t auxiliaryHeaderSize() const {
238     assert(!needsAuxiliaryHeader() &&
239            "Auxiliary header support not implemented.");
240     return 0;
241   }
242 
243 public:
244   XCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
245                     raw_pwrite_stream &OS);
246 };
247 
248 XCOFFObjectWriter::XCOFFObjectWriter(
249     std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
250     : W(OS, support::big), TargetObjectWriter(std::move(MOTW)),
251       Strings(StringTableBuilder::XCOFF),
252       Text(".text", XCOFF::STYP_TEXT, /* IsVirtual */ false,
253            CsectGroups{&ProgramCodeCsects, &ReadOnlyCsects}),
254       Data(".data", XCOFF::STYP_DATA, /* IsVirtual */ false,
255            CsectGroups{&DataCsects, &FuncDSCsects, &TOCCsects}),
256       BSS(".bss", XCOFF::STYP_BSS, /* IsVirtual */ true,
257           CsectGroups{&BSSCsects}),
258       TData(".tdata", XCOFF::STYP_TDATA, /* IsVirtual */ false,
259             CsectGroups{&TDataCsects}),
260       TBSS(".tbss", XCOFF::STYP_TBSS, /* IsVirtual */ true,
261            CsectGroups{&TBSSCsects}) {}
262 
263 void XCOFFObjectWriter::reset() {
264   // Clear the mappings we created.
265   SymbolIndexMap.clear();
266   SectionMap.clear();
267 
268   UndefinedCsects.clear();
269   // Reset any sections we have written to, and empty the section header table.
270   for (auto *Sec : Sections)
271     Sec->reset();
272 
273   // Reset states in XCOFFObjectWriter.
274   SymbolTableEntryCount = 0;
275   SymbolTableOffset = 0;
276   SectionCount = 0;
277   RelocationEntryOffset = 0;
278   Strings.clear();
279 
280   MCObjectWriter::reset();
281 }
282 
283 CsectGroup &XCOFFObjectWriter::getCsectGroup(const MCSectionXCOFF *MCSec) {
284   switch (MCSec->getMappingClass()) {
285   case XCOFF::XMC_PR:
286     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
287            "Only an initialized csect can contain program code.");
288     return ProgramCodeCsects;
289   case XCOFF::XMC_RO:
290     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
291            "Only an initialized csect can contain read only data.");
292     return ReadOnlyCsects;
293   case XCOFF::XMC_RW:
294     if (XCOFF::XTY_CM == MCSec->getCSectType())
295       return BSSCsects;
296 
297     if (XCOFF::XTY_SD == MCSec->getCSectType())
298       return DataCsects;
299 
300     report_fatal_error("Unhandled mapping of read-write csect to section.");
301   case XCOFF::XMC_DS:
302     return FuncDSCsects;
303   case XCOFF::XMC_BS:
304     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
305            "Mapping invalid csect. CSECT with bss storage class must be "
306            "common type.");
307     return BSSCsects;
308   case XCOFF::XMC_TL:
309     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
310            "Mapping invalid csect. CSECT with tdata storage class must be "
311            "an initialized csect.");
312     return TDataCsects;
313   case XCOFF::XMC_UL:
314     assert(XCOFF::XTY_CM == MCSec->getCSectType() &&
315            "Mapping invalid csect. CSECT with tbss storage class must be "
316            "an uninitialized csect.");
317     return TBSSCsects;
318   case XCOFF::XMC_TC0:
319     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
320            "Only an initialized csect can contain TOC-base.");
321     assert(TOCCsects.empty() &&
322            "We should have only one TOC-base, and it should be the first csect "
323            "in this CsectGroup.");
324     return TOCCsects;
325   case XCOFF::XMC_TC:
326   case XCOFF::XMC_TE:
327     assert(XCOFF::XTY_SD == MCSec->getCSectType() &&
328            "Only an initialized csect can contain TC entry.");
329     assert(!TOCCsects.empty() &&
330            "We should at least have a TOC-base in this CsectGroup.");
331     return TOCCsects;
332   case XCOFF::XMC_TD:
333     report_fatal_error("toc-data not yet supported when writing object files.");
334   default:
335     report_fatal_error("Unhandled mapping of csect to section.");
336   }
337 }
338 
339 static MCSectionXCOFF *getContainingCsect(const MCSymbolXCOFF *XSym) {
340   if (XSym->isDefined())
341     return cast<MCSectionXCOFF>(XSym->getFragment()->getParent());
342   return XSym->getRepresentedCsect();
343 }
344 
345 void XCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
346                                                  const MCAsmLayout &Layout) {
347   if (TargetObjectWriter->is64Bit())
348     report_fatal_error("64-bit XCOFF object files are not supported yet.");
349 
350   for (const auto &S : Asm) {
351     const auto *MCSec = cast<const MCSectionXCOFF>(&S);
352     assert(SectionMap.find(MCSec) == SectionMap.end() &&
353            "Cannot add a csect twice.");
354     assert(XCOFF::XTY_ER != MCSec->getCSectType() &&
355            "An undefined csect should not get registered.");
356 
357     // If the name does not fit in the storage provided in the symbol table
358     // entry, add it to the string table.
359     if (nameShouldBeInStringTable(MCSec->getSymbolTableName()))
360       Strings.add(MCSec->getSymbolTableName());
361 
362     CsectGroup &Group = getCsectGroup(MCSec);
363     Group.emplace_back(MCSec);
364     SectionMap[MCSec] = &Group.back();
365   }
366 
367   for (const MCSymbol &S : Asm.symbols()) {
368     // Nothing to do for temporary symbols.
369     if (S.isTemporary())
370       continue;
371 
372     const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(&S);
373     const MCSectionXCOFF *ContainingCsect = getContainingCsect(XSym);
374 
375     if (ContainingCsect->getCSectType() == XCOFF::XTY_ER) {
376       // Handle undefined symbol.
377       UndefinedCsects.emplace_back(ContainingCsect);
378       SectionMap[ContainingCsect] = &UndefinedCsects.back();
379       if (nameShouldBeInStringTable(ContainingCsect->getSymbolTableName()))
380         Strings.add(ContainingCsect->getSymbolTableName());
381       continue;
382     }
383 
384     // If the symbol is the csect itself, we don't need to put the symbol
385     // into csect's Syms.
386     if (XSym == ContainingCsect->getQualNameSymbol())
387       continue;
388 
389     // Only put a label into the symbol table when it is an external label.
390     if (!XSym->isExternal())
391       continue;
392 
393     assert(SectionMap.find(ContainingCsect) != SectionMap.end() &&
394            "Expected containing csect to exist in map");
395     // Lookup the containing csect and add the symbol to it.
396     SectionMap[ContainingCsect]->Syms.emplace_back(XSym);
397 
398     // If the name does not fit in the storage provided in the symbol table
399     // entry, add it to the string table.
400     if (nameShouldBeInStringTable(XSym->getSymbolTableName()))
401       Strings.add(XSym->getSymbolTableName());
402   }
403 
404   Strings.finalize();
405   assignAddressesAndIndices(Layout);
406 }
407 
408 void XCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
409                                          const MCAsmLayout &Layout,
410                                          const MCFragment *Fragment,
411                                          const MCFixup &Fixup, MCValue Target,
412                                          uint64_t &FixedValue) {
413   auto getIndex = [this](const MCSymbol *Sym,
414                          const MCSectionXCOFF *ContainingCsect) {
415     // If we could not find the symbol directly in SymbolIndexMap, this symbol
416     // could either be a temporary symbol or an undefined symbol. In this case,
417     // we would need to have the relocation reference its csect instead.
418     return SymbolIndexMap.find(Sym) != SymbolIndexMap.end()
419                ? SymbolIndexMap[Sym]
420                : SymbolIndexMap[ContainingCsect->getQualNameSymbol()];
421   };
422 
423   auto getVirtualAddress = [this,
424                             &Layout](const MCSymbol *Sym,
425                                      const MCSectionXCOFF *ContainingCsect) {
426     // If Sym is a csect, return csect's address.
427     // If Sym is a label, return csect's address + label's offset from the csect.
428     return SectionMap[ContainingCsect]->Address +
429            (Sym->isDefined() ? Layout.getSymbolOffset(*Sym) : 0);
430   };
431 
432   const MCSymbol *const SymA = &Target.getSymA()->getSymbol();
433 
434   MCAsmBackend &Backend = Asm.getBackend();
435   bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
436                  MCFixupKindInfo::FKF_IsPCRel;
437 
438   uint8_t Type;
439   uint8_t SignAndSize;
440   std::tie(Type, SignAndSize) =
441       TargetObjectWriter->getRelocTypeAndSignSize(Target, Fixup, IsPCRel);
442 
443   const MCSectionXCOFF *SymASec = getContainingCsect(cast<MCSymbolXCOFF>(SymA));
444 
445   if (SymASec->isCsect() && SymASec->getMappingClass() == XCOFF::XMC_TD)
446     report_fatal_error("toc-data not yet supported when writing object files.");
447 
448   assert(SectionMap.find(SymASec) != SectionMap.end() &&
449          "Expected containing csect to exist in map.");
450 
451   const uint32_t Index = getIndex(SymA, SymASec);
452   if (Type == XCOFF::RelocationType::R_POS)
453     // The FixedValue should be symbol's virtual address in this object file
454     // plus any constant value that we might get.
455     FixedValue = getVirtualAddress(SymA, SymASec) + Target.getConstant();
456   else if (Type == XCOFF::RelocationType::R_TOC ||
457            Type == XCOFF::RelocationType::R_TOCL) {
458     // The FixedValue should be the TOC entry offset from the TOC-base plus any
459     // constant offset value.
460     const int64_t TOCEntryOffset = SectionMap[SymASec]->Address -
461                                    TOCCsects.front().Address +
462                                    Target.getConstant();
463     if (Type == XCOFF::RelocationType::R_TOC && !isInt<16>(TOCEntryOffset))
464       report_fatal_error("TOCEntryOffset overflows in small code model mode");
465 
466     FixedValue = TOCEntryOffset;
467   }
468 
469   assert(
470       (TargetObjectWriter->is64Bit() ||
471        Fixup.getOffset() <= UINT32_MAX - Layout.getFragmentOffset(Fragment)) &&
472       "Fragment offset + fixup offset is overflowed in 32-bit mode.");
473   uint32_t FixupOffsetInCsect =
474       Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
475 
476   XCOFFRelocation Reloc = {Index, FixupOffsetInCsect, SignAndSize, Type};
477   MCSectionXCOFF *RelocationSec = cast<MCSectionXCOFF>(Fragment->getParent());
478   assert(SectionMap.find(RelocationSec) != SectionMap.end() &&
479          "Expected containing csect to exist in map.");
480   SectionMap[RelocationSec]->Relocations.push_back(Reloc);
481 
482   if (!Target.getSymB())
483     return;
484 
485   const MCSymbol *const SymB = &Target.getSymB()->getSymbol();
486   if (SymA == SymB)
487     report_fatal_error("relocation for opposite term is not yet supported");
488 
489   const MCSectionXCOFF *SymBSec = getContainingCsect(cast<MCSymbolXCOFF>(SymB));
490   assert(SectionMap.find(SymBSec) != SectionMap.end() &&
491          "Expected containing csect to exist in map.");
492   if (SymASec == SymBSec)
493     report_fatal_error(
494         "relocation for paired relocatable term is not yet supported");
495 
496   assert(Type == XCOFF::RelocationType::R_POS &&
497          "SymA must be R_POS here if it's not opposite term or paired "
498          "relocatable term.");
499   const uint32_t IndexB = getIndex(SymB, SymBSec);
500   // SymB must be R_NEG here, given the general form of Target(MCValue) is
501   // "SymbolA - SymbolB + imm64".
502   const uint8_t TypeB = XCOFF::RelocationType::R_NEG;
503   XCOFFRelocation RelocB = {IndexB, FixupOffsetInCsect, SignAndSize, TypeB};
504   SectionMap[RelocationSec]->Relocations.push_back(RelocB);
505   // We already folded "SymbolA + imm64" above when Type is R_POS for SymbolA,
506   // now we just need to fold "- SymbolB" here.
507   FixedValue -= getVirtualAddress(SymB, SymBSec);
508 }
509 
510 void XCOFFObjectWriter::writeSections(const MCAssembler &Asm,
511                                       const MCAsmLayout &Layout) {
512   uint32_t CurrentAddressLocation = 0;
513   for (const auto *Section : Sections) {
514     // Nothing to write for this Section.
515     if (Section->Index == Section::UninitializedIndex || Section->IsVirtual)
516       continue;
517 
518     // There could be a gap (without corresponding zero padding) between
519     // sections.
520     assert(((CurrentAddressLocation <= Section->Address) ||
521             (Section->Flags == XCOFF::STYP_TDATA) ||
522             (Section->Flags == XCOFF::STYP_TBSS)) &&
523            "CurrentAddressLocation should be less than or equal to section "
524            "address if the section is not TData or TBSS.");
525 
526     CurrentAddressLocation = Section->Address;
527 
528     for (const auto *Group : Section->Groups) {
529       for (const auto &Csect : *Group) {
530         if (uint32_t PaddingSize = Csect.Address - CurrentAddressLocation)
531           W.OS.write_zeros(PaddingSize);
532         if (Csect.Size)
533           Asm.writeSectionData(W.OS, Csect.MCCsect, Layout);
534         CurrentAddressLocation = Csect.Address + Csect.Size;
535       }
536     }
537 
538     // The size of the tail padding in a section is the end virtual address of
539     // the current section minus the the end virtual address of the last csect
540     // in that section.
541     if (uint32_t PaddingSize =
542             Section->Address + Section->Size - CurrentAddressLocation) {
543       W.OS.write_zeros(PaddingSize);
544       CurrentAddressLocation += PaddingSize;
545     }
546   }
547 }
548 
549 uint64_t XCOFFObjectWriter::writeObject(MCAssembler &Asm,
550                                         const MCAsmLayout &Layout) {
551   // We always emit a timestamp of 0 for reproducibility, so ensure incremental
552   // linking is not enabled, in case, like with Windows COFF, such a timestamp
553   // is incompatible with incremental linking of XCOFF.
554   if (Asm.isIncrementalLinkerCompatible())
555     report_fatal_error("Incremental linking not supported for XCOFF.");
556 
557   if (TargetObjectWriter->is64Bit())
558     report_fatal_error("64-bit XCOFF object files are not supported yet.");
559 
560   finalizeSectionInfo();
561   uint64_t StartOffset = W.OS.tell();
562 
563   writeFileHeader();
564   writeSectionHeaderTable();
565   writeSections(Asm, Layout);
566   writeRelocations();
567 
568   writeSymbolTable(Layout);
569   // Write the string table.
570   Strings.write(W.OS);
571 
572   return W.OS.tell() - StartOffset;
573 }
574 
575 bool XCOFFObjectWriter::nameShouldBeInStringTable(const StringRef &SymbolName) {
576   return SymbolName.size() > XCOFF::NameSize;
577 }
578 
579 void XCOFFObjectWriter::writeSymbolName(const StringRef &SymbolName) {
580   if (nameShouldBeInStringTable(SymbolName)) {
581     W.write<int32_t>(0);
582     W.write<uint32_t>(Strings.getOffset(SymbolName));
583   } else {
584     char Name[XCOFF::NameSize+1];
585     std::strncpy(Name, SymbolName.data(), XCOFF::NameSize);
586     ArrayRef<char> NameRef(Name, XCOFF::NameSize);
587     W.write(NameRef);
588   }
589 }
590 
591 void XCOFFObjectWriter::writeSymbolTableEntryForCsectMemberLabel(
592     const Symbol &SymbolRef, const ControlSection &CSectionRef,
593     int16_t SectionIndex, uint64_t SymbolOffset) {
594   // Name or Zeros and string table offset
595   writeSymbolName(SymbolRef.getSymbolTableName());
596   assert(SymbolOffset <= UINT32_MAX - CSectionRef.Address &&
597          "Symbol address overflows.");
598   W.write<uint32_t>(CSectionRef.Address + SymbolOffset);
599   W.write<int16_t>(SectionIndex);
600   // Basic/Derived type. See the description of the n_type field for symbol
601   // table entries for a detailed description. Since we don't yet support
602   // visibility, and all other bits are either optionally set or reserved, this
603   // is always zero.
604   // TODO FIXME How to assert a symbol's visibilty is default?
605   // TODO Set the function indicator (bit 10, 0x0020) for functions
606   // when debugging is enabled.
607   W.write<uint16_t>(0);
608   W.write<uint8_t>(SymbolRef.getStorageClass());
609   // Always 1 aux entry for now.
610   W.write<uint8_t>(1);
611 
612   // Now output the auxiliary entry.
613   W.write<uint32_t>(CSectionRef.SymbolTableIndex);
614   // Parameter typecheck hash. Not supported.
615   W.write<uint32_t>(0);
616   // Typecheck section number. Not supported.
617   W.write<uint16_t>(0);
618   // Symbol type: Label
619   W.write<uint8_t>(XCOFF::XTY_LD);
620   // Storage mapping class.
621   W.write<uint8_t>(CSectionRef.MCCsect->getMappingClass());
622   // Reserved (x_stab).
623   W.write<uint32_t>(0);
624   // Reserved (x_snstab).
625   W.write<uint16_t>(0);
626 }
627 
628 void XCOFFObjectWriter::writeSymbolTableEntryForControlSection(
629     const ControlSection &CSectionRef, int16_t SectionIndex,
630     XCOFF::StorageClass StorageClass) {
631   // n_name, n_zeros, n_offset
632   writeSymbolName(CSectionRef.getSymbolTableName());
633   // n_value
634   W.write<uint32_t>(CSectionRef.Address);
635   // n_scnum
636   W.write<int16_t>(SectionIndex);
637   // Basic/Derived type. See the description of the n_type field for symbol
638   // table entries for a detailed description. Since we don't yet support
639   // visibility, and all other bits are either optionally set or reserved, this
640   // is always zero.
641   // TODO FIXME How to assert a symbol's visibilty is default?
642   // TODO Set the function indicator (bit 10, 0x0020) for functions
643   // when debugging is enabled.
644   W.write<uint16_t>(0);
645   // n_sclass
646   W.write<uint8_t>(StorageClass);
647   // Always 1 aux entry for now.
648   W.write<uint8_t>(1);
649 
650   // Now output the auxiliary entry.
651   W.write<uint32_t>(CSectionRef.Size);
652   // Parameter typecheck hash. Not supported.
653   W.write<uint32_t>(0);
654   // Typecheck section number. Not supported.
655   W.write<uint16_t>(0);
656   // Symbol type.
657   W.write<uint8_t>(getEncodedType(CSectionRef.MCCsect));
658   // Storage mapping class.
659   W.write<uint8_t>(CSectionRef.MCCsect->getMappingClass());
660   // Reserved (x_stab).
661   W.write<uint32_t>(0);
662   // Reserved (x_snstab).
663   W.write<uint16_t>(0);
664 }
665 
666 void XCOFFObjectWriter::writeFileHeader() {
667   // Magic.
668   W.write<uint16_t>(0x01df);
669   // Number of sections.
670   W.write<uint16_t>(SectionCount);
671   // Timestamp field. For reproducible output we write a 0, which represents no
672   // timestamp.
673   W.write<int32_t>(0);
674   // Byte Offset to the start of the symbol table.
675   W.write<uint32_t>(SymbolTableOffset);
676   // Number of entries in the symbol table.
677   W.write<int32_t>(SymbolTableEntryCount);
678   // Size of the optional header.
679   W.write<uint16_t>(0);
680   // Flags.
681   W.write<uint16_t>(0);
682 }
683 
684 void XCOFFObjectWriter::writeSectionHeaderTable() {
685   for (const auto *Sec : Sections) {
686     // Nothing to write for this Section.
687     if (Sec->Index == Section::UninitializedIndex)
688       continue;
689 
690     // Write Name.
691     ArrayRef<char> NameRef(Sec->Name, XCOFF::NameSize);
692     W.write(NameRef);
693 
694     // Write the Physical Address and Virtual Address. In an object file these
695     // are the same.
696     W.write<uint32_t>(Sec->Address);
697     W.write<uint32_t>(Sec->Address);
698 
699     W.write<uint32_t>(Sec->Size);
700     W.write<uint32_t>(Sec->FileOffsetToData);
701     W.write<uint32_t>(Sec->FileOffsetToRelocations);
702 
703     // Line number pointer. Not supported yet.
704     W.write<uint32_t>(0);
705 
706     W.write<uint16_t>(Sec->RelocationCount);
707 
708     // Line number counts. Not supported yet.
709     W.write<uint16_t>(0);
710 
711     W.write<int32_t>(Sec->Flags);
712   }
713 }
714 
715 void XCOFFObjectWriter::writeRelocation(XCOFFRelocation Reloc,
716                                         const ControlSection &CSection) {
717   W.write<uint32_t>(CSection.Address + Reloc.FixupOffsetInCsect);
718   W.write<uint32_t>(Reloc.SymbolTableIndex);
719   W.write<uint8_t>(Reloc.SignAndSize);
720   W.write<uint8_t>(Reloc.Type);
721 }
722 
723 void XCOFFObjectWriter::writeRelocations() {
724   for (const auto *Section : Sections) {
725     if (Section->Index == Section::UninitializedIndex)
726       // Nothing to write for this Section.
727       continue;
728 
729     for (const auto *Group : Section->Groups) {
730       if (Group->empty())
731         continue;
732 
733       for (const auto &Csect : *Group) {
734         for (const auto Reloc : Csect.Relocations)
735           writeRelocation(Reloc, Csect);
736       }
737     }
738   }
739 }
740 
741 void XCOFFObjectWriter::writeSymbolTable(const MCAsmLayout &Layout) {
742   // Write symbol 0 as C_FILE.
743   // FIXME: support 64-bit C_FILE symbol.
744   //
745   // n_name. The n_name of a C_FILE symbol is the source filename when no
746   // auxiliary entries are present. The source filename is alternatively
747   // provided by an auxiliary entry, in which case the n_name of the C_FILE
748   // symbol is `.file`.
749   // FIXME: add the real source filename.
750   writeSymbolName(".file");
751   // n_value. The n_value of a C_FILE symbol is its symbol table index.
752   W.write<uint32_t>(0);
753   // n_scnum. N_DEBUG is a reserved section number for indicating a special
754   // symbolic debugging symbol.
755   W.write<int16_t>(XCOFF::ReservedSectionNum::N_DEBUG);
756   // n_type. The n_type field of a C_FILE symbol encodes the source language and
757   // CPU version info; zero indicates no info.
758   W.write<uint16_t>(0);
759   // n_sclass. The C_FILE symbol provides source file-name information,
760   // source-language ID and CPU-version ID information and some other optional
761   // infos.
762   W.write<uint8_t>(XCOFF::C_FILE);
763   // n_numaux. No aux entry for now.
764   W.write<uint8_t>(0);
765 
766   for (const auto &Csect : UndefinedCsects) {
767     writeSymbolTableEntryForControlSection(
768         Csect, XCOFF::ReservedSectionNum::N_UNDEF, Csect.MCCsect->getStorageClass());
769   }
770 
771   for (const auto *Section : Sections) {
772     if (Section->Index == Section::UninitializedIndex)
773       // Nothing to write for this Section.
774       continue;
775 
776     for (const auto *Group : Section->Groups) {
777       if (Group->empty())
778         continue;
779 
780       const int16_t SectionIndex = Section->Index;
781       for (const auto &Csect : *Group) {
782         // Write out the control section first and then each symbol in it.
783         writeSymbolTableEntryForControlSection(
784             Csect, SectionIndex, Csect.MCCsect->getStorageClass());
785 
786         for (const auto &Sym : Csect.Syms)
787           writeSymbolTableEntryForCsectMemberLabel(
788               Sym, Csect, SectionIndex, Layout.getSymbolOffset(*(Sym.MCSym)));
789       }
790     }
791   }
792 }
793 
794 void XCOFFObjectWriter::finalizeSectionInfo() {
795   for (auto *Section : Sections) {
796     if (Section->Index == Section::UninitializedIndex)
797       // Nothing to record for this Section.
798       continue;
799 
800     for (const auto *Group : Section->Groups) {
801       if (Group->empty())
802         continue;
803 
804       for (auto &Csect : *Group) {
805         const size_t CsectRelocCount = Csect.Relocations.size();
806         if (CsectRelocCount >= XCOFF::RelocOverflow ||
807             Section->RelocationCount >= XCOFF::RelocOverflow - CsectRelocCount)
808           report_fatal_error(
809               "relocation entries overflowed; overflow section is "
810               "not implemented yet");
811 
812         Section->RelocationCount += CsectRelocCount;
813       }
814     }
815   }
816 
817   // Calculate the file offset to the relocation entries.
818   uint64_t RawPointer = RelocationEntryOffset;
819   for (auto Sec : Sections) {
820     if (Sec->Index == Section::UninitializedIndex || !Sec->RelocationCount)
821       continue;
822 
823     Sec->FileOffsetToRelocations = RawPointer;
824     const uint32_t RelocationSizeInSec =
825         Sec->RelocationCount * XCOFF::RelocationSerializationSize32;
826     RawPointer += RelocationSizeInSec;
827     if (RawPointer > UINT32_MAX)
828       report_fatal_error("Relocation data overflowed this object file.");
829   }
830 
831   // TODO Error check that the number of symbol table entries fits in 32-bits
832   // signed ...
833   if (SymbolTableEntryCount)
834     SymbolTableOffset = RawPointer;
835 }
836 
837 void XCOFFObjectWriter::assignAddressesAndIndices(const MCAsmLayout &Layout) {
838   // The first symbol table entry (at index 0) is for the file name.
839   uint32_t SymbolTableIndex = 1;
840 
841   // Calculate indices for undefined symbols.
842   for (auto &Csect : UndefinedCsects) {
843     Csect.Size = 0;
844     Csect.Address = 0;
845     Csect.SymbolTableIndex = SymbolTableIndex;
846     SymbolIndexMap[Csect.MCCsect->getQualNameSymbol()] = Csect.SymbolTableIndex;
847     // 1 main and 1 auxiliary symbol table entry for each contained symbol.
848     SymbolTableIndex += 2;
849   }
850 
851   // The address corrresponds to the address of sections and symbols in the
852   // object file. We place the shared address 0 immediately after the
853   // section header table.
854   uint32_t Address = 0;
855   // Section indices are 1-based in XCOFF.
856   int32_t SectionIndex = 1;
857   bool HasTDataSection = false;
858 
859   for (auto *Section : Sections) {
860     const bool IsEmpty =
861         llvm::all_of(Section->Groups,
862                      [](const CsectGroup *Group) { return Group->empty(); });
863     if (IsEmpty)
864       continue;
865 
866     if (SectionIndex > MaxSectionIndex)
867       report_fatal_error("Section index overflow!");
868     Section->Index = SectionIndex++;
869     SectionCount++;
870 
871     bool SectionAddressSet = false;
872     // Reset the starting address to 0 for TData section.
873     if (Section->Flags == XCOFF::STYP_TDATA) {
874       Address = 0;
875       HasTDataSection = true;
876     }
877     // Reset the starting address to 0 for TBSS section if the object file does
878     // not contain TData Section.
879     if ((Section->Flags == XCOFF::STYP_TBSS) && !HasTDataSection)
880       Address = 0;
881 
882     for (auto *Group : Section->Groups) {
883       if (Group->empty())
884         continue;
885 
886       for (auto &Csect : *Group) {
887         const MCSectionXCOFF *MCSec = Csect.MCCsect;
888         Csect.Address = alignTo(Address, MCSec->getAlignment());
889         Csect.Size = Layout.getSectionAddressSize(MCSec);
890         Address = Csect.Address + Csect.Size;
891         Csect.SymbolTableIndex = SymbolTableIndex;
892         SymbolIndexMap[MCSec->getQualNameSymbol()] = Csect.SymbolTableIndex;
893         // 1 main and 1 auxiliary symbol table entry for the csect.
894         SymbolTableIndex += 2;
895 
896         for (auto &Sym : Csect.Syms) {
897           Sym.SymbolTableIndex = SymbolTableIndex;
898           SymbolIndexMap[Sym.MCSym] = Sym.SymbolTableIndex;
899           // 1 main and 1 auxiliary symbol table entry for each contained
900           // symbol.
901           SymbolTableIndex += 2;
902         }
903       }
904 
905       if (!SectionAddressSet) {
906         Section->Address = Group->front().Address;
907         SectionAddressSet = true;
908       }
909     }
910 
911     // Make sure the address of the next section aligned to
912     // DefaultSectionAlign.
913     Address = alignTo(Address, DefaultSectionAlign);
914     Section->Size = Address - Section->Address;
915   }
916 
917   SymbolTableEntryCount = SymbolTableIndex;
918 
919   // Calculate the RawPointer value for each section.
920   uint64_t RawPointer = sizeof(XCOFF::FileHeader32) + auxiliaryHeaderSize() +
921                         SectionCount * sizeof(XCOFF::SectionHeader32);
922   for (auto *Sec : Sections) {
923     if (Sec->Index == Section::UninitializedIndex || Sec->IsVirtual)
924       continue;
925 
926     Sec->FileOffsetToData = RawPointer;
927     RawPointer += Sec->Size;
928     if (RawPointer > UINT32_MAX)
929       report_fatal_error("Section raw data overflowed this object file.");
930   }
931 
932   RelocationEntryOffset = RawPointer;
933 }
934 
935 // Takes the log base 2 of the alignment and shifts the result into the 5 most
936 // significant bits of a byte, then or's in the csect type into the least
937 // significant 3 bits.
938 uint8_t getEncodedType(const MCSectionXCOFF *Sec) {
939   unsigned Align = Sec->getAlignment();
940   assert(isPowerOf2_32(Align) && "Alignment must be a power of 2.");
941   unsigned Log2Align = Log2_32(Align);
942   // Result is a number in the range [0, 31] which fits in the 5 least
943   // significant bits. Shift this value into the 5 most significant bits, and
944   // bitwise-or in the csect type.
945   uint8_t EncodedAlign = Log2Align << 3;
946   return EncodedAlign | Sec->getCSectType();
947 }
948 
949 } // end anonymous namespace
950 
951 std::unique_ptr<MCObjectWriter>
952 llvm::createXCOFFObjectWriter(std::unique_ptr<MCXCOFFObjectTargetWriter> MOTW,
953                               raw_pwrite_stream &OS) {
954   return std::make_unique<XCOFFObjectWriter>(std::move(MOTW), OS);
955 }
956