1 //===-- XCOFFDumper.cpp - XCOFF dumping utility -----------------*- C++ -*-===//
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 an XCOFF specific dumper for llvm-readobj.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "ObjDumper.h"
14 #include "llvm-readobj.h"
15 #include "llvm/Object/XCOFFObjectFile.h"
16 #include "llvm/Support/FormattedStream.h"
17 #include "llvm/Support/ScopedPrinter.h"
18 
19 #include <stddef.h>
20 
21 using namespace llvm;
22 using namespace object;
23 
24 namespace {
25 
26 class XCOFFDumper : public ObjDumper {
27 
28 public:
29   XCOFFDumper(const XCOFFObjectFile &Obj, ScopedPrinter &Writer)
30       : ObjDumper(Writer, Obj.getFileName()), Obj(Obj) {}
31 
32   void printFileHeaders() override;
33   void printAuxiliaryHeader() override;
34   void printSectionHeaders() override;
35   void printRelocations() override;
36   void printSymbols() override;
37   void printDynamicSymbols() override;
38   void printUnwindInfo() override;
39   void printStackMap() const override;
40   void printNeededLibraries() override;
41   void printStringTable() override;
42 
43 private:
44   template <typename T> void printSectionHeaders(ArrayRef<T> Sections);
45   template <typename T> void printGenericSectionHeader(T &Sec) const;
46   template <typename T> void printOverflowSectionHeader(T &Sec) const;
47   void printFileAuxEnt(const XCOFFFileAuxEnt *AuxEntPtr);
48   void printCsectAuxEnt(XCOFFCsectAuxRef AuxEntRef);
49   void printSectAuxEntForStat(const XCOFFSectAuxEntForStat *AuxEntPtr);
50   void printSymbol(const SymbolRef &);
51   template <typename Shdr, typename RelTy>
52   void printRelocations(ArrayRef<Shdr> Sections);
53   void printAuxiliaryHeader(const XCOFFAuxiliaryHeader32 *AuxHeader);
54   void printAuxiliaryHeader(const XCOFFAuxiliaryHeader64 *AuxHeader);
55   const XCOFFObjectFile &Obj;
56 };
57 } // anonymous namespace
58 
59 void XCOFFDumper::printFileHeaders() {
60   DictScope DS(W, "FileHeader");
61   W.printHex("Magic", Obj.getMagic());
62   W.printNumber("NumberOfSections", Obj.getNumberOfSections());
63 
64   // Negative timestamp values are reserved for future use.
65   int32_t TimeStamp = Obj.getTimeStamp();
66   if (TimeStamp > 0) {
67     // This handling of the time stamp assumes that the host system's time_t is
68     // compatible with AIX time_t. If a platform is not compatible, the lit
69     // tests will let us know.
70     time_t TimeDate = TimeStamp;
71 
72     char FormattedTime[21] = {};
73     size_t BytesWritten =
74         strftime(FormattedTime, 21, "%Y-%m-%dT%H:%M:%SZ", gmtime(&TimeDate));
75     if (BytesWritten)
76       W.printHex("TimeStamp", FormattedTime, TimeStamp);
77     else
78       W.printHex("Timestamp", TimeStamp);
79   } else {
80     W.printHex("TimeStamp", TimeStamp == 0 ? "None" : "Reserved Value",
81                TimeStamp);
82   }
83 
84   // The number of symbol table entries is an unsigned value in 64-bit objects
85   // and a signed value (with negative values being 'reserved') in 32-bit
86   // objects.
87   if (Obj.is64Bit()) {
88     W.printHex("SymbolTableOffset", Obj.getSymbolTableOffset64());
89     W.printNumber("SymbolTableEntries", Obj.getNumberOfSymbolTableEntries64());
90   } else {
91     W.printHex("SymbolTableOffset", Obj.getSymbolTableOffset32());
92     int32_t SymTabEntries = Obj.getRawNumberOfSymbolTableEntries32();
93     if (SymTabEntries >= 0)
94       W.printNumber("SymbolTableEntries", SymTabEntries);
95     else
96       W.printHex("SymbolTableEntries", "Reserved Value", SymTabEntries);
97   }
98 
99   W.printHex("OptionalHeaderSize", Obj.getOptionalHeaderSize());
100   W.printHex("Flags", Obj.getFlags());
101 
102   // TODO FIXME Add support for the auxiliary header (if any) once
103   // XCOFFObjectFile has the necessary support.
104 }
105 
106 void XCOFFDumper::printAuxiliaryHeader() {
107   if (Obj.is64Bit())
108     printAuxiliaryHeader(Obj.auxiliaryHeader64());
109   else
110     printAuxiliaryHeader(Obj.auxiliaryHeader32());
111 }
112 
113 void XCOFFDumper::printSectionHeaders() {
114   if (Obj.is64Bit())
115     printSectionHeaders(Obj.sections64());
116   else
117     printSectionHeaders(Obj.sections32());
118 }
119 
120 void XCOFFDumper::printRelocations() {
121   if (Obj.is64Bit())
122     printRelocations<XCOFFSectionHeader64, XCOFFRelocation64>(Obj.sections64());
123   else
124     printRelocations<XCOFFSectionHeader32, XCOFFRelocation32>(Obj.sections32());
125 }
126 
127 const EnumEntry<XCOFF::RelocationType> RelocationTypeNameclass[] = {
128 #define ECase(X)                                                               \
129   { #X, XCOFF::X }
130     ECase(R_POS),    ECase(R_RL),     ECase(R_RLA),    ECase(R_NEG),
131     ECase(R_REL),    ECase(R_TOC),    ECase(R_TRL),    ECase(R_TRLA),
132     ECase(R_GL),     ECase(R_TCL),    ECase(R_REF),    ECase(R_BA),
133     ECase(R_BR),     ECase(R_RBA),    ECase(R_RBR),    ECase(R_TLS),
134     ECase(R_TLS_IE), ECase(R_TLS_LD), ECase(R_TLS_LE), ECase(R_TLSM),
135     ECase(R_TLSML),  ECase(R_TOCU),   ECase(R_TOCL)
136 #undef ECase
137 };
138 
139 template <typename Shdr, typename RelTy>
140 void XCOFFDumper::printRelocations(ArrayRef<Shdr> Sections) {
141   if (!opts::ExpandRelocs)
142     report_fatal_error("Unexpanded relocation output not implemented.");
143 
144   ListScope LS(W, "Relocations");
145   uint16_t Index = 0;
146   for (const Shdr &Sec : Sections) {
147     ++Index;
148     // Only the .text, .data, .tdata, and STYP_DWARF sections have relocation.
149     if (Sec.Flags != XCOFF::STYP_TEXT && Sec.Flags != XCOFF::STYP_DATA &&
150         Sec.Flags != XCOFF::STYP_TDATA && Sec.Flags != XCOFF::STYP_DWARF)
151       continue;
152     Expected<ArrayRef<RelTy>> ErrOrRelocations = Obj.relocations<Shdr, RelTy>(Sec);
153     if (Error E = ErrOrRelocations.takeError()) {
154       reportUniqueWarning(std::move(E));
155       continue;
156     }
157 
158     const ArrayRef<RelTy> Relocations = *ErrOrRelocations;
159     if (Relocations.empty())
160       continue;
161 
162     W.startLine() << "Section (index: " << Index << ") " << Sec.getName()
163                   << " {\n";
164     for (const RelTy Reloc : Relocations) {
165       Expected<StringRef> ErrOrSymbolName =
166           Obj.getSymbolNameByIndex(Reloc.SymbolIndex);
167       if (Error E = ErrOrSymbolName.takeError()) {
168         reportUniqueWarning(std::move(E));
169         continue;
170       }
171 
172       StringRef SymbolName = *ErrOrSymbolName;
173       DictScope RelocScope(W, "Relocation");
174       W.printHex("Virtual Address", Reloc.VirtualAddress);
175       W.printNumber("Symbol", SymbolName, Reloc.SymbolIndex);
176       W.printString("IsSigned", Reloc.isRelocationSigned() ? "Yes" : "No");
177       W.printNumber("FixupBitValue", Reloc.isFixupIndicated() ? 1 : 0);
178       W.printNumber("Length", Reloc.getRelocatedLength());
179       W.printEnum("Type", (uint8_t)Reloc.Type,
180                   makeArrayRef(RelocationTypeNameclass));
181     }
182     W.unindent();
183     W.startLine() << "}\n";
184   }
185 }
186 
187 const EnumEntry<XCOFF::CFileStringType> FileStringType[] = {
188 #define ECase(X)                                                               \
189   { #X, XCOFF::X }
190     ECase(XFT_FN), ECase(XFT_CT), ECase(XFT_CV), ECase(XFT_CD)
191 #undef ECase
192 };
193 
194 const EnumEntry<XCOFF::SymbolAuxType> SymAuxType[] = {
195 #define ECase(X)                                                               \
196   { #X, XCOFF::X }
197     ECase(AUX_EXCEPT), ECase(AUX_FCN), ECase(AUX_SYM), ECase(AUX_FILE),
198     ECase(AUX_CSECT),  ECase(AUX_SECT)
199 #undef ECase
200 };
201 
202 void XCOFFDumper::printFileAuxEnt(const XCOFFFileAuxEnt *AuxEntPtr) {
203   assert((!Obj.is64Bit() || AuxEntPtr->AuxType == XCOFF::AUX_FILE) &&
204          "Mismatched auxiliary type!");
205   StringRef FileName =
206       unwrapOrError(Obj.getFileName(), Obj.getCFileName(AuxEntPtr));
207   DictScope SymDs(W, "File Auxiliary Entry");
208   W.printNumber("Index",
209                 Obj.getSymbolIndex(reinterpret_cast<uintptr_t>(AuxEntPtr)));
210   W.printString("Name", FileName);
211   W.printEnum("Type", static_cast<uint8_t>(AuxEntPtr->Type),
212               makeArrayRef(FileStringType));
213   if (Obj.is64Bit()) {
214     W.printEnum("Auxiliary Type", static_cast<uint8_t>(AuxEntPtr->AuxType),
215                 makeArrayRef(SymAuxType));
216   }
217 }
218 
219 static const EnumEntry<XCOFF::StorageMappingClass> CsectStorageMappingClass[] =
220     {
221 #define ECase(X)                                                               \
222   { #X, XCOFF::X }
223         ECase(XMC_PR), ECase(XMC_RO), ECase(XMC_DB),   ECase(XMC_GL),
224         ECase(XMC_XO), ECase(XMC_SV), ECase(XMC_SV64), ECase(XMC_SV3264),
225         ECase(XMC_TI), ECase(XMC_TB), ECase(XMC_RW),   ECase(XMC_TC0),
226         ECase(XMC_TC), ECase(XMC_TD), ECase(XMC_DS),   ECase(XMC_UA),
227         ECase(XMC_BS), ECase(XMC_UC), ECase(XMC_TL),   ECase(XMC_UL),
228         ECase(XMC_TE)
229 #undef ECase
230 };
231 
232 const EnumEntry<XCOFF::SymbolType> CsectSymbolTypeClass[] = {
233 #define ECase(X)                                                               \
234   { #X, XCOFF::X }
235     ECase(XTY_ER), ECase(XTY_SD), ECase(XTY_LD), ECase(XTY_CM)
236 #undef ECase
237 };
238 
239 void XCOFFDumper::printCsectAuxEnt(XCOFFCsectAuxRef AuxEntRef) {
240   assert((!Obj.is64Bit() || AuxEntRef.getAuxType64() == XCOFF::AUX_CSECT) &&
241          "Mismatched auxiliary type!");
242 
243   DictScope SymDs(W, "CSECT Auxiliary Entry");
244   W.printNumber("Index", Obj.getSymbolIndex(AuxEntRef.getEntryAddress()));
245   W.printNumber(AuxEntRef.isLabel() ? "ContainingCsectSymbolIndex"
246                                     : "SectionLen",
247                 AuxEntRef.getSectionOrLength());
248   W.printHex("ParameterHashIndex", AuxEntRef.getParameterHashIndex());
249   W.printHex("TypeChkSectNum", AuxEntRef.getTypeChkSectNum());
250   // Print out symbol alignment and type.
251   W.printNumber("SymbolAlignmentLog2", AuxEntRef.getAlignmentLog2());
252   W.printEnum("SymbolType", AuxEntRef.getSymbolType(),
253               makeArrayRef(CsectSymbolTypeClass));
254   W.printEnum("StorageMappingClass",
255               static_cast<uint8_t>(AuxEntRef.getStorageMappingClass()),
256               makeArrayRef(CsectStorageMappingClass));
257 
258   if (Obj.is64Bit()) {
259     W.printEnum("Auxiliary Type", static_cast<uint8_t>(XCOFF::AUX_CSECT),
260                 makeArrayRef(SymAuxType));
261   } else {
262     W.printHex("StabInfoIndex", AuxEntRef.getStabInfoIndex32());
263     W.printHex("StabSectNum", AuxEntRef.getStabSectNum32());
264   }
265 }
266 
267 void XCOFFDumper::printSectAuxEntForStat(
268     const XCOFFSectAuxEntForStat *AuxEntPtr) {
269   assert(!Obj.is64Bit() && "32-bit interface called on 64-bit object file.");
270 
271   DictScope SymDs(W, "Sect Auxiliary Entry For Stat");
272   W.printNumber("Index",
273                 Obj.getSymbolIndex(reinterpret_cast<uintptr_t>(AuxEntPtr)));
274   W.printNumber("SectionLength", AuxEntPtr->SectionLength);
275 
276   // Unlike the corresponding fields in the section header, NumberOfRelocEnt
277   // and NumberOfLineNum do not handle values greater than 65535.
278   W.printNumber("NumberOfRelocEnt", AuxEntPtr->NumberOfRelocEnt);
279   W.printNumber("NumberOfLineNum", AuxEntPtr->NumberOfLineNum);
280 }
281 
282 const EnumEntry<XCOFF::StorageClass> SymStorageClass[] = {
283 #define ECase(X)                                                               \
284   { #X, XCOFF::X }
285     ECase(C_NULL),  ECase(C_AUTO),    ECase(C_EXT),     ECase(C_STAT),
286     ECase(C_REG),   ECase(C_EXTDEF),  ECase(C_LABEL),   ECase(C_ULABEL),
287     ECase(C_MOS),   ECase(C_ARG),     ECase(C_STRTAG),  ECase(C_MOU),
288     ECase(C_UNTAG), ECase(C_TPDEF),   ECase(C_USTATIC), ECase(C_ENTAG),
289     ECase(C_MOE),   ECase(C_REGPARM), ECase(C_FIELD),   ECase(C_BLOCK),
290     ECase(C_FCN),   ECase(C_EOS),     ECase(C_FILE),    ECase(C_LINE),
291     ECase(C_ALIAS), ECase(C_HIDDEN),  ECase(C_HIDEXT),  ECase(C_BINCL),
292     ECase(C_EINCL), ECase(C_INFO),    ECase(C_WEAKEXT), ECase(C_DWARF),
293     ECase(C_GSYM),  ECase(C_LSYM),    ECase(C_PSYM),    ECase(C_RSYM),
294     ECase(C_RPSYM), ECase(C_STSYM),   ECase(C_TCSYM),   ECase(C_BCOMM),
295     ECase(C_ECOML), ECase(C_ECOMM),   ECase(C_DECL),    ECase(C_ENTRY),
296     ECase(C_FUN),   ECase(C_BSTAT),   ECase(C_ESTAT),   ECase(C_GTLS),
297     ECase(C_STTLS), ECase(C_EFCN)
298 #undef ECase
299 };
300 
301 static StringRef GetSymbolValueName(XCOFF::StorageClass SC) {
302   switch (SC) {
303   case XCOFF::C_EXT:
304   case XCOFF::C_WEAKEXT:
305   case XCOFF::C_HIDEXT:
306   case XCOFF::C_STAT:
307     return "Value (RelocatableAddress)";
308   case XCOFF::C_FILE:
309     return "Value (SymbolTableIndex)";
310   case XCOFF::C_FCN:
311   case XCOFF::C_BLOCK:
312   case XCOFF::C_FUN:
313   case XCOFF::C_STSYM:
314   case XCOFF::C_BINCL:
315   case XCOFF::C_EINCL:
316   case XCOFF::C_INFO:
317   case XCOFF::C_BSTAT:
318   case XCOFF::C_LSYM:
319   case XCOFF::C_PSYM:
320   case XCOFF::C_RPSYM:
321   case XCOFF::C_RSYM:
322   case XCOFF::C_ECOML:
323   case XCOFF::C_DWARF:
324     assert(false && "This StorageClass for the symbol is not yet implemented.");
325     return "";
326   default:
327     return "Value";
328   }
329 }
330 
331 const EnumEntry<XCOFF::CFileLangId> CFileLangIdClass[] = {
332 #define ECase(X)                                                               \
333   { #X, XCOFF::X }
334     ECase(TB_C), ECase(TB_CPLUSPLUS)
335 #undef ECase
336 };
337 
338 const EnumEntry<XCOFF::CFileCpuId> CFileCpuIdClass[] = {
339 #define ECase(X)                                                               \
340   { #X, XCOFF::X }
341     ECase(TCPU_PPC64), ECase(TCPU_COM), ECase(TCPU_970)
342 #undef ECase
343 };
344 
345 void XCOFFDumper::printSymbol(const SymbolRef &S) {
346   DataRefImpl SymbolDRI = S.getRawDataRefImpl();
347   XCOFFSymbolRef SymbolEntRef = Obj.toSymbolRef(SymbolDRI);
348 
349   uint8_t NumberOfAuxEntries = SymbolEntRef.getNumberOfAuxEntries();
350 
351   DictScope SymDs(W, "Symbol");
352 
353   StringRef SymbolName =
354       unwrapOrError(Obj.getFileName(), SymbolEntRef.getName());
355 
356   W.printNumber("Index", Obj.getSymbolIndex(SymbolEntRef.getEntryAddress()));
357   W.printString("Name", SymbolName);
358   W.printHex(GetSymbolValueName(SymbolEntRef.getStorageClass()),
359              SymbolEntRef.getValue());
360 
361   StringRef SectionName =
362       unwrapOrError(Obj.getFileName(), Obj.getSymbolSectionName(SymbolEntRef));
363 
364   W.printString("Section", SectionName);
365   if (SymbolEntRef.getStorageClass() == XCOFF::C_FILE) {
366     W.printEnum("Source Language ID", SymbolEntRef.getLanguageIdForCFile(),
367                 makeArrayRef(CFileLangIdClass));
368     W.printEnum("CPU Version ID", SymbolEntRef.getCPUTypeIddForCFile(),
369                 makeArrayRef(CFileCpuIdClass));
370   } else
371     W.printHex("Type", SymbolEntRef.getSymbolType());
372 
373   W.printEnum("StorageClass",
374               static_cast<uint8_t>(SymbolEntRef.getStorageClass()),
375               makeArrayRef(SymStorageClass));
376   W.printNumber("NumberOfAuxEntries", NumberOfAuxEntries);
377 
378   if (NumberOfAuxEntries == 0)
379     return;
380 
381   switch (SymbolEntRef.getStorageClass()) {
382   case XCOFF::C_FILE:
383     // If the symbol is C_FILE and has auxiliary entries...
384     for (int I = 1; I <= NumberOfAuxEntries; I++) {
385       uintptr_t AuxAddress = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
386           SymbolEntRef.getEntryAddress(), I);
387 
388       if (Obj.is64Bit() &&
389           *Obj.getSymbolAuxType(AuxAddress) != XCOFF::SymbolAuxType::AUX_FILE) {
390         W.startLine() << "!Unexpected raw auxiliary entry data:\n";
391         W.startLine() << format_bytes(
392                              ArrayRef<uint8_t>(
393                                  reinterpret_cast<const uint8_t *>(AuxAddress),
394                                  XCOFF::SymbolTableEntrySize),
395                              0, XCOFF::SymbolTableEntrySize)
396                       << "\n";
397         continue;
398       }
399 
400       const XCOFFFileAuxEnt *FileAuxEntPtr =
401           reinterpret_cast<const XCOFFFileAuxEnt *>(AuxAddress);
402 #ifndef NDEBUG
403       Obj.checkSymbolEntryPointer(reinterpret_cast<uintptr_t>(FileAuxEntPtr));
404 #endif
405       printFileAuxEnt(FileAuxEntPtr);
406     }
407     break;
408   case XCOFF::C_EXT:
409   case XCOFF::C_WEAKEXT:
410   case XCOFF::C_HIDEXT: {
411     // If the symbol is for a function, and it has more than 1 auxiliary entry,
412     // then one of them must be function auxiliary entry which we do not
413     // support yet.
414     if (SymbolEntRef.isFunction() && NumberOfAuxEntries >= 2)
415       report_fatal_error("Function auxiliary entry printing is unimplemented.");
416 
417     // If there is more than 1 auxiliary entry, instead of printing out
418     // error information, print out the raw Auxiliary entry.
419     // For 32-bit object, print from first to the last - 1. The last one must be
420     // a CSECT Auxiliary Entry.
421     // For 64-bit object, print from first to last and skips if SymbolAuxType is
422     // AUX_CSECT.
423     for (int I = 1; I <= NumberOfAuxEntries; I++) {
424       if (I == NumberOfAuxEntries && !Obj.is64Bit())
425         break;
426 
427       uintptr_t AuxAddress = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
428           SymbolEntRef.getEntryAddress(), I);
429       if (Obj.is64Bit() &&
430           *Obj.getSymbolAuxType(AuxAddress) == XCOFF::SymbolAuxType::AUX_CSECT)
431         continue;
432 
433       W.startLine() << "!Unexpected raw auxiliary entry data:\n";
434       W.startLine() << format_bytes(
435           ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(AuxAddress),
436                             XCOFF::SymbolTableEntrySize));
437     }
438 
439     auto ErrOrCsectAuxRef = SymbolEntRef.getXCOFFCsectAuxRef();
440     if (!ErrOrCsectAuxRef)
441       reportUniqueWarning(ErrOrCsectAuxRef.takeError());
442     else
443       printCsectAuxEnt(*ErrOrCsectAuxRef);
444 
445     break;
446   }
447   case XCOFF::C_STAT:
448     if (NumberOfAuxEntries > 1)
449       report_fatal_error(
450           "C_STAT symbol should not have more than 1 auxiliary entry.");
451 
452     const XCOFFSectAuxEntForStat *StatAuxEntPtr;
453     StatAuxEntPtr = reinterpret_cast<const XCOFFSectAuxEntForStat *>(
454         XCOFFObjectFile::getAdvancedSymbolEntryAddress(
455             SymbolEntRef.getEntryAddress(), 1));
456 #ifndef NDEBUG
457     Obj.checkSymbolEntryPointer(reinterpret_cast<uintptr_t>(StatAuxEntPtr));
458 #endif
459     printSectAuxEntForStat(StatAuxEntPtr);
460     break;
461   case XCOFF::C_DWARF:
462   case XCOFF::C_BLOCK:
463   case XCOFF::C_FCN:
464     report_fatal_error("Symbol table entry printing for this storage class "
465                        "type is unimplemented.");
466     break;
467   default:
468     for (int i = 1; i <= NumberOfAuxEntries; i++) {
469       W.startLine() << "!Unexpected raw auxiliary entry data:\n";
470       W.startLine() << format_bytes(
471           ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(
472                                 XCOFFObjectFile::getAdvancedSymbolEntryAddress(
473                                     SymbolEntRef.getEntryAddress(), i)),
474                             XCOFF::SymbolTableEntrySize));
475     }
476     break;
477   }
478 }
479 
480 void XCOFFDumper::printSymbols() {
481   ListScope Group(W, "Symbols");
482   for (const SymbolRef &S : Obj.symbols())
483     printSymbol(S);
484 }
485 
486 void XCOFFDumper::printStringTable() {
487   DictScope DS(W, "StringTable");
488   StringRef StrTable = Obj.getStringTable();
489   uint32_t StrTabSize = StrTable.size();
490   W.printNumber("Length", StrTabSize);
491   // Print strings from the fifth byte, since the first four bytes contain the
492   // length (in bytes) of the string table (including the length field).
493   if (StrTabSize > 4)
494     printAsStringList(StrTable, 4);
495 }
496 
497 void XCOFFDumper::printDynamicSymbols() {
498   llvm_unreachable("Unimplemented functionality for XCOFFDumper");
499 }
500 
501 void XCOFFDumper::printUnwindInfo() {
502   llvm_unreachable("Unimplemented functionality for XCOFFDumper");
503 }
504 
505 void XCOFFDumper::printStackMap() const {
506   llvm_unreachable("Unimplemented functionality for XCOFFDumper");
507 }
508 
509 void XCOFFDumper::printNeededLibraries() {
510   ListScope D(W, "NeededLibraries");
511   auto ImportFilesOrError = Obj.getImportFileTable();
512   if (!ImportFilesOrError) {
513     reportUniqueWarning(ImportFilesOrError.takeError());
514     return;
515   }
516 
517   StringRef ImportFileTable = ImportFilesOrError.get();
518   const char *CurrentStr = ImportFileTable.data();
519   const char *TableEnd = ImportFileTable.end();
520   // Default column width for names is 13 even if no names are that long.
521   size_t BaseWidth = 13;
522 
523   // Get the max width of BASE columns.
524   for (size_t StrIndex = 0; CurrentStr < TableEnd; ++StrIndex) {
525     size_t CurrentLen = strlen(CurrentStr);
526     CurrentStr += strlen(CurrentStr) + 1;
527     if (StrIndex % 3 == 1)
528       BaseWidth = std::max(BaseWidth, CurrentLen);
529   }
530 
531   auto &OS = static_cast<formatted_raw_ostream &>(W.startLine());
532   // Each entry consists of 3 strings: the path_name, base_name and
533   // archive_member_name. The first entry is a default LIBPATH value and other
534   // entries have no path_name. We just dump the base_name and
535   // archive_member_name here.
536   OS << left_justify("BASE", BaseWidth)  << " MEMBER\n";
537   CurrentStr = ImportFileTable.data();
538   for (size_t StrIndex = 0; CurrentStr < TableEnd;
539        ++StrIndex, CurrentStr += strlen(CurrentStr) + 1) {
540     if (StrIndex >= 3 && StrIndex % 3 != 0) {
541       if (StrIndex % 3 == 1)
542         OS << "  " << left_justify(CurrentStr, BaseWidth) << " ";
543       else
544         OS << CurrentStr << "\n";
545     }
546   }
547 }
548 
549 const EnumEntry<XCOFF::SectionTypeFlags> SectionTypeFlagsNames[] = {
550 #define ECase(X)                                                               \
551   { #X, XCOFF::X }
552     ECase(STYP_PAD),    ECase(STYP_DWARF), ECase(STYP_TEXT),
553     ECase(STYP_DATA),   ECase(STYP_BSS),   ECase(STYP_EXCEPT),
554     ECase(STYP_INFO),   ECase(STYP_TDATA), ECase(STYP_TBSS),
555     ECase(STYP_LOADER), ECase(STYP_DEBUG), ECase(STYP_TYPCHK),
556     ECase(STYP_OVRFLO)
557 #undef ECase
558 };
559 
560 template <typename T>
561 void XCOFFDumper::printOverflowSectionHeader(T &Sec) const {
562   if (Obj.is64Bit()) {
563     reportWarning(make_error<StringError>("An 64-bit XCOFF object file may not "
564                                           "contain an overflow section header.",
565                                           object_error::parse_failed),
566                   Obj.getFileName());
567   }
568 
569   W.printString("Name", Sec.getName());
570   W.printNumber("NumberOfRelocations", Sec.PhysicalAddress);
571   W.printNumber("NumberOfLineNumbers", Sec.VirtualAddress);
572   W.printHex("Size", Sec.SectionSize);
573   W.printHex("RawDataOffset", Sec.FileOffsetToRawData);
574   W.printHex("RelocationPointer", Sec.FileOffsetToRelocationInfo);
575   W.printHex("LineNumberPointer", Sec.FileOffsetToLineNumberInfo);
576   W.printNumber("IndexOfSectionOverflowed", Sec.NumberOfRelocations);
577   W.printNumber("IndexOfSectionOverflowed", Sec.NumberOfLineNumbers);
578 }
579 
580 template <typename T>
581 void XCOFFDumper::printGenericSectionHeader(T &Sec) const {
582   W.printString("Name", Sec.getName());
583   W.printHex("PhysicalAddress", Sec.PhysicalAddress);
584   W.printHex("VirtualAddress", Sec.VirtualAddress);
585   W.printHex("Size", Sec.SectionSize);
586   W.printHex("RawDataOffset", Sec.FileOffsetToRawData);
587   W.printHex("RelocationPointer", Sec.FileOffsetToRelocationInfo);
588   W.printHex("LineNumberPointer", Sec.FileOffsetToLineNumberInfo);
589   W.printNumber("NumberOfRelocations", Sec.NumberOfRelocations);
590   W.printNumber("NumberOfLineNumbers", Sec.NumberOfLineNumbers);
591 }
592 
593 void XCOFFDumper::printAuxiliaryHeader(
594     const XCOFFAuxiliaryHeader32 *AuxHeader) {
595   if (AuxHeader == nullptr)
596     return;
597   uint16_t AuxSize = Obj.getOptionalHeaderSize();
598   uint16_t PartialFieldOffset = AuxSize;
599   const char *PartialFieldName = nullptr;
600 
601   DictScope DS(W, "AuxiliaryHeader");
602 
603 #define PrintAuxMember32(H, S, T)                                              \
604   if (offsetof(XCOFFAuxiliaryHeader32, T) +                                    \
605           sizeof(XCOFFAuxiliaryHeader32::T) <=                                 \
606       AuxSize)                                                                 \
607     W.print##H(S, AuxHeader->T);                                               \
608   else if (offsetof(XCOFFAuxiliaryHeader32, T) < AuxSize) {                    \
609     PartialFieldOffset = offsetof(XCOFFAuxiliaryHeader32, T);                  \
610     PartialFieldName = S;                                                      \
611   }
612 
613   PrintAuxMember32(Hex, "Magic", AuxMagic);
614   PrintAuxMember32(Hex, "Version", Version);
615   PrintAuxMember32(Hex, "Size of .text section", TextSize);
616   PrintAuxMember32(Hex, "Size of .data section", InitDataSize);
617   PrintAuxMember32(Hex, "Size of .bss section", BssDataSize);
618   PrintAuxMember32(Hex, "Entry point address", EntryPointAddr);
619   PrintAuxMember32(Hex, ".text section start address", TextStartAddr);
620   PrintAuxMember32(Hex, ".data section start address", DataStartAddr);
621   PrintAuxMember32(Hex, "TOC anchor address", TOCAnchorAddr);
622   PrintAuxMember32(Number, "Section number of entryPoint", SecNumOfEntryPoint);
623   PrintAuxMember32(Number, "Section number of .text", SecNumOfText);
624   PrintAuxMember32(Number, "Section number of .data", SecNumOfData);
625   PrintAuxMember32(Number, "Section number of TOC", SecNumOfTOC);
626   PrintAuxMember32(Number, "Section number of loader data", SecNumOfLoader);
627   PrintAuxMember32(Number, "Section number of .bss", SecNumOfBSS);
628   PrintAuxMember32(Hex, "Maxium alignment of .text", MaxAlignOfText);
629   PrintAuxMember32(Hex, "Maxium alignment of .data", MaxAlignOfData);
630   PrintAuxMember32(Hex, "Module type", ModuleType);
631   PrintAuxMember32(Hex, "CPU type of objects", CpuFlag);
632   PrintAuxMember32(Hex, "(Reserved)", CpuType);
633   PrintAuxMember32(Hex, "Maximum stack size", MaxStackSize);
634   PrintAuxMember32(Hex, "Maximum data size", MaxDataSize);
635   PrintAuxMember32(Hex, "Reserved for debugger", ReservedForDebugger);
636   PrintAuxMember32(Hex, "Text page size", TextPageSize);
637   PrintAuxMember32(Hex, "Data page size", DataPageSize);
638   PrintAuxMember32(Hex, "Stack page size", StackPageSize);
639   if (offsetof(XCOFFAuxiliaryHeader32, FlagAndTDataAlignment) +
640           sizeof(XCOFFAuxiliaryHeader32::FlagAndTDataAlignment) <=
641       AuxSize) {
642     W.printHex("Flag", AuxHeader->getFlag());
643     W.printHex("Alignment of thread-local storage",
644                AuxHeader->getTDataAlignment());
645   }
646 
647   PrintAuxMember32(Number, "Section number for .tdata", SecNumOfTData);
648   PrintAuxMember32(Number, "Section number for .tbss", SecNumOfTBSS);
649 
650   // Deal with error.
651   if (PartialFieldOffset < AuxSize) {
652     std::string ErrInfo;
653     llvm::raw_string_ostream StringOS(ErrInfo);
654     StringOS << "Only partial field for " << PartialFieldName << " at offset ("
655              << PartialFieldOffset << ").";
656     StringOS.flush();
657     reportWarning(
658         make_error<GenericBinaryError>(ErrInfo, object_error::parse_failed),
659         "-");
660     W.printBinary(
661         "Raw data", "",
662         ArrayRef<uint8_t>((const uint8_t *)(AuxHeader) + PartialFieldOffset,
663                           AuxSize - PartialFieldOffset));
664   } else if (sizeof(XCOFFAuxiliaryHeader32) < AuxSize) {
665     reportWarning(make_error<GenericBinaryError>(
666                       "There are extra data beyond auxiliary header",
667                       object_error::parse_failed),
668                   "-");
669     W.printBinary("Extra raw data", "",
670                   ArrayRef<uint8_t>((const uint8_t *)(AuxHeader) +
671                                         sizeof(XCOFFAuxiliaryHeader32),
672                                     AuxSize - sizeof(XCOFFAuxiliaryHeader32)));
673   }
674 
675 #undef PrintAuxMember32
676 }
677 
678 void XCOFFDumper::printAuxiliaryHeader(
679     const XCOFFAuxiliaryHeader64 *AuxHeader) {
680   if (AuxHeader == nullptr)
681     return;
682   uint16_t AuxSize = Obj.getOptionalHeaderSize();
683   uint16_t PartialFieldOffset = AuxSize;
684   const char *PartialFieldName = nullptr;
685 
686   DictScope DS(W, "AuxiliaryHeader");
687 
688 #define PrintAuxMember64(H, S, T)                                              \
689   if (offsetof(XCOFFAuxiliaryHeader64, T) +                                    \
690           sizeof(XCOFFAuxiliaryHeader64::T) <=                                 \
691       AuxSize)                                                                 \
692     W.print##H(S, AuxHeader->T);                                               \
693   else if (offsetof(XCOFFAuxiliaryHeader64, T) < AuxSize) {                    \
694     PartialFieldOffset = offsetof(XCOFFAuxiliaryHeader64, T);                  \
695     PartialFieldName = S;                                                      \
696   }
697 
698   PrintAuxMember64(Hex, "Magic", AuxMagic);
699   PrintAuxMember64(Hex, "Version", Version);
700   PrintAuxMember64(Hex, "Reserved for debugger", ReservedForDebugger);
701   PrintAuxMember64(Hex, ".text section start address", TextStartAddr);
702   PrintAuxMember64(Hex, ".data section start address", DataStartAddr);
703   PrintAuxMember64(Hex, "TOC anchor address", TOCAnchorAddr);
704   PrintAuxMember64(Number, "Section number of entryPoint", SecNumOfEntryPoint);
705   PrintAuxMember64(Number, "Section number of .text", SecNumOfText);
706   PrintAuxMember64(Number, "Section number of .data", SecNumOfData);
707   PrintAuxMember64(Number, "Section number of TOC", SecNumOfTOC);
708   PrintAuxMember64(Number, "Section number of loader data", SecNumOfLoader);
709   PrintAuxMember64(Number, "Section number of .bss", SecNumOfBSS);
710   PrintAuxMember64(Hex, "Maxium alignment of .text", MaxAlignOfText);
711   PrintAuxMember64(Hex, "Maxium alignment of .data", MaxAlignOfData);
712   PrintAuxMember64(Hex, "Module type", ModuleType);
713   PrintAuxMember64(Hex, "CPU type of objects", CpuFlag);
714   PrintAuxMember64(Hex, "(Reserved)", CpuType);
715   PrintAuxMember64(Hex, "Text page size", TextPageSize);
716   PrintAuxMember64(Hex, "Data page size", DataPageSize);
717   PrintAuxMember64(Hex, "Stack page size", StackPageSize);
718   if (offsetof(XCOFFAuxiliaryHeader64, FlagAndTDataAlignment) +
719           sizeof(XCOFFAuxiliaryHeader64::FlagAndTDataAlignment) <=
720       AuxSize) {
721     W.printHex("Flag", AuxHeader->getFlag());
722     W.printHex("Alignment of thread-local storage",
723                AuxHeader->getTDataAlignment());
724   }
725   PrintAuxMember64(Hex, "Size of .text section", TextSize);
726   PrintAuxMember64(Hex, "Size of .data section", InitDataSize);
727   PrintAuxMember64(Hex, "Size of .bss section", BssDataSize);
728   PrintAuxMember64(Hex, "Entry point address", EntryPointAddr);
729   PrintAuxMember64(Hex, "Maximum stack size", MaxStackSize);
730   PrintAuxMember64(Hex, "Maximum data size", MaxDataSize);
731   PrintAuxMember64(Number, "Section number for .tdata", SecNumOfTData);
732   PrintAuxMember64(Number, "Section number for .tbss", SecNumOfTBSS);
733   PrintAuxMember64(Hex, "Additional flags 64-bit XCOFF", XCOFF64Flag);
734 
735   if (PartialFieldOffset < AuxSize) {
736     std::string ErrInfo;
737     llvm::raw_string_ostream StringOS(ErrInfo);
738     StringOS << "Only partial field for " << PartialFieldName << " at offset ("
739              << PartialFieldOffset << ").";
740     StringOS.flush();
741     reportWarning(
742         make_error<GenericBinaryError>(ErrInfo, object_error::parse_failed),
743         "-");
744     ;
745     W.printBinary(
746         "Raw data", "",
747         ArrayRef<uint8_t>((const uint8_t *)(AuxHeader) + PartialFieldOffset,
748                           AuxSize - PartialFieldOffset));
749   } else if (sizeof(XCOFFAuxiliaryHeader64) < AuxSize) {
750     reportWarning(make_error<GenericBinaryError>(
751                       "There are extra data beyond auxiliary header",
752                       object_error::parse_failed),
753                   "-");
754     W.printBinary("Extra raw data", "",
755                   ArrayRef<uint8_t>((const uint8_t *)(AuxHeader) +
756                                         sizeof(XCOFFAuxiliaryHeader64),
757                                     AuxSize - sizeof(XCOFFAuxiliaryHeader64)));
758   }
759 
760 #undef PrintAuxMember64
761 }
762 
763 template <typename T>
764 void XCOFFDumper::printSectionHeaders(ArrayRef<T> Sections) {
765   ListScope Group(W, "Sections");
766 
767   uint16_t Index = 1;
768   for (const T &Sec : Sections) {
769     DictScope SecDS(W, "Section");
770 
771     W.printNumber("Index", Index++);
772     uint16_t SectionType = Sec.getSectionType();
773     switch (SectionType) {
774     case XCOFF::STYP_OVRFLO:
775       printOverflowSectionHeader(Sec);
776       break;
777     case XCOFF::STYP_LOADER:
778     case XCOFF::STYP_EXCEPT:
779     case XCOFF::STYP_TYPCHK:
780       // TODO The interpretation of loader, exception and type check section
781       // headers are different from that of generic section headers. We will
782       // implement them later. We interpret them as generic section headers for
783       // now.
784     default:
785       printGenericSectionHeader(Sec);
786       break;
787     }
788     if (Sec.isReservedSectionType())
789       W.printHex("Flags", "Reserved", SectionType);
790     else
791       W.printEnum("Type", SectionType, makeArrayRef(SectionTypeFlagsNames));
792   }
793 
794   if (opts::SectionRelocations)
795     report_fatal_error("Dumping section relocations is unimplemented");
796 
797   if (opts::SectionSymbols)
798     report_fatal_error("Dumping symbols is unimplemented");
799 
800   if (opts::SectionData)
801     report_fatal_error("Dumping section data is unimplemented");
802 }
803 
804 namespace llvm {
805 std::unique_ptr<ObjDumper>
806 createXCOFFDumper(const object::XCOFFObjectFile &XObj, ScopedPrinter &Writer) {
807   return std::make_unique<XCOFFDumper>(XObj, Writer);
808 }
809 } // namespace llvm
810