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