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