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