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