xref: /llvm-project/llvm/lib/Object/XCOFFObjectFile.cpp (revision 0a4c946abcfaae3601c49a55e29944287f867b7f)
1 //===--- XCOFFObjectFile.cpp - XCOFF object file implementation -----------===//
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 defines the XCOFFObjectFile class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Object/XCOFFObjectFile.h"
14 #include "llvm/ADT/StringSwitch.h"
15 #include "llvm/MC/SubtargetFeature.h"
16 #include "llvm/Support/DataExtractor.h"
17 #include <cstddef>
18 #include <cstring>
19 
20 namespace llvm {
21 
22 using namespace XCOFF;
23 
24 namespace object {
25 
26 static const uint8_t FunctionSym = 0x20;
27 static const uint16_t NoRelMask = 0x0001;
28 static const size_t SymbolAuxTypeOffset = 17;
29 
30 // Checks that [Ptr, Ptr + Size) bytes fall inside the memory buffer
31 // 'M'. Returns a pointer to the underlying object on success.
32 template <typename T>
33 static Expected<const T *> getObject(MemoryBufferRef M, const void *Ptr,
34                                      const uint64_t Size = sizeof(T)) {
35   uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
36   if (Error E = Binary::checkOffset(M, Addr, Size))
37     return std::move(E);
38   return reinterpret_cast<const T *>(Addr);
39 }
40 
41 static uintptr_t getWithOffset(uintptr_t Base, ptrdiff_t Offset) {
42   return reinterpret_cast<uintptr_t>(reinterpret_cast<const char *>(Base) +
43                                      Offset);
44 }
45 
46 template <typename T> static const T *viewAs(uintptr_t in) {
47   return reinterpret_cast<const T *>(in);
48 }
49 
50 static StringRef generateXCOFFFixedNameStringRef(const char *Name) {
51   auto NulCharPtr =
52       static_cast<const char *>(memchr(Name, '\0', XCOFF::NameSize));
53   return NulCharPtr ? StringRef(Name, NulCharPtr - Name)
54                     : StringRef(Name, XCOFF::NameSize);
55 }
56 
57 template <typename T> StringRef XCOFFSectionHeader<T>::getName() const {
58   const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
59   return generateXCOFFFixedNameStringRef(DerivedXCOFFSectionHeader.Name);
60 }
61 
62 template <typename T> uint16_t XCOFFSectionHeader<T>::getSectionType() const {
63   const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
64   return DerivedXCOFFSectionHeader.Flags & SectionFlagsTypeMask;
65 }
66 
67 template <typename T>
68 bool XCOFFSectionHeader<T>::isReservedSectionType() const {
69   return getSectionType() & SectionFlagsReservedMask;
70 }
71 
72 template <typename AddressType>
73 bool XCOFFRelocation<AddressType>::isRelocationSigned() const {
74   return Info & XR_SIGN_INDICATOR_MASK;
75 }
76 
77 template <typename AddressType>
78 bool XCOFFRelocation<AddressType>::isFixupIndicated() const {
79   return Info & XR_FIXUP_INDICATOR_MASK;
80 }
81 
82 template <typename AddressType>
83 uint8_t XCOFFRelocation<AddressType>::getRelocatedLength() const {
84   // The relocation encodes the bit length being relocated minus 1. Add back
85   // the 1 to get the actual length being relocated.
86   return (Info & XR_BIASED_LENGTH_MASK) + 1;
87 }
88 
89 template struct ExceptionSectionEntry<support::ubig32_t>;
90 template struct ExceptionSectionEntry<support::ubig64_t>;
91 
92 uintptr_t
93 XCOFFObjectFile::getAdvancedSymbolEntryAddress(uintptr_t CurrentAddress,
94                                                uint32_t Distance) {
95   return getWithOffset(CurrentAddress, Distance * XCOFF::SymbolTableEntrySize);
96 }
97 
98 const XCOFF::SymbolAuxType *
99 XCOFFObjectFile::getSymbolAuxType(uintptr_t AuxEntryAddress) const {
100   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
101   return viewAs<XCOFF::SymbolAuxType>(
102       getWithOffset(AuxEntryAddress, SymbolAuxTypeOffset));
103 }
104 
105 void XCOFFObjectFile::checkSectionAddress(uintptr_t Addr,
106                                           uintptr_t TableAddress) const {
107   if (Addr < TableAddress)
108     report_fatal_error("Section header outside of section header table.");
109 
110   uintptr_t Offset = Addr - TableAddress;
111   if (Offset >= getSectionHeaderSize() * getNumberOfSections())
112     report_fatal_error("Section header outside of section header table.");
113 
114   if (Offset % getSectionHeaderSize() != 0)
115     report_fatal_error(
116         "Section header pointer does not point to a valid section header.");
117 }
118 
119 const XCOFFSectionHeader32 *
120 XCOFFObjectFile::toSection32(DataRefImpl Ref) const {
121   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
122 #ifndef NDEBUG
123   checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
124 #endif
125   return viewAs<XCOFFSectionHeader32>(Ref.p);
126 }
127 
128 const XCOFFSectionHeader64 *
129 XCOFFObjectFile::toSection64(DataRefImpl Ref) const {
130   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
131 #ifndef NDEBUG
132   checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
133 #endif
134   return viewAs<XCOFFSectionHeader64>(Ref.p);
135 }
136 
137 XCOFFSymbolRef XCOFFObjectFile::toSymbolRef(DataRefImpl Ref) const {
138   assert(Ref.p != 0 && "Symbol table pointer can not be nullptr!");
139 #ifndef NDEBUG
140   checkSymbolEntryPointer(Ref.p);
141 #endif
142   return XCOFFSymbolRef(Ref, this);
143 }
144 
145 const XCOFFFileHeader32 *XCOFFObjectFile::fileHeader32() const {
146   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
147   return static_cast<const XCOFFFileHeader32 *>(FileHeader);
148 }
149 
150 const XCOFFFileHeader64 *XCOFFObjectFile::fileHeader64() const {
151   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
152   return static_cast<const XCOFFFileHeader64 *>(FileHeader);
153 }
154 
155 const XCOFFAuxiliaryHeader32 *XCOFFObjectFile::auxiliaryHeader32() const {
156   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
157   return static_cast<const XCOFFAuxiliaryHeader32 *>(AuxiliaryHeader);
158 }
159 
160 const XCOFFAuxiliaryHeader64 *XCOFFObjectFile::auxiliaryHeader64() const {
161   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
162   return static_cast<const XCOFFAuxiliaryHeader64 *>(AuxiliaryHeader);
163 }
164 
165 template <typename T> const T *XCOFFObjectFile::sectionHeaderTable() const {
166   return static_cast<const T *>(SectionHeaderTable);
167 }
168 
169 const XCOFFSectionHeader32 *
170 XCOFFObjectFile::sectionHeaderTable32() const {
171   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
172   return static_cast<const XCOFFSectionHeader32 *>(SectionHeaderTable);
173 }
174 
175 const XCOFFSectionHeader64 *
176 XCOFFObjectFile::sectionHeaderTable64() const {
177   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
178   return static_cast<const XCOFFSectionHeader64 *>(SectionHeaderTable);
179 }
180 
181 void XCOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
182   uintptr_t NextSymbolAddr = getAdvancedSymbolEntryAddress(
183       Symb.p, toSymbolRef(Symb).getNumberOfAuxEntries() + 1);
184 #ifndef NDEBUG
185   // This function is used by basic_symbol_iterator, which allows to
186   // point to the end-of-symbol-table address.
187   if (NextSymbolAddr != getEndOfSymbolTableAddress())
188     checkSymbolEntryPointer(NextSymbolAddr);
189 #endif
190   Symb.p = NextSymbolAddr;
191 }
192 
193 Expected<StringRef>
194 XCOFFObjectFile::getStringTableEntry(uint32_t Offset) const {
195   // The byte offset is relative to the start of the string table.
196   // A byte offset value of 0 is a null or zero-length symbol
197   // name. A byte offset in the range 1 to 3 (inclusive) points into the length
198   // field; as a soft-error recovery mechanism, we treat such cases as having an
199   // offset of 0.
200   if (Offset < 4)
201     return StringRef(nullptr, 0);
202 
203   if (StringTable.Data != nullptr && StringTable.Size > Offset)
204     return (StringTable.Data + Offset);
205 
206   return createError("entry with offset 0x" + Twine::utohexstr(Offset) +
207                      " in a string table with size 0x" +
208                      Twine::utohexstr(StringTable.Size) + " is invalid");
209 }
210 
211 StringRef XCOFFObjectFile::getStringTable() const {
212   // If the size is less than or equal to 4, then the string table contains no
213   // string data.
214   return StringRef(StringTable.Data,
215                    StringTable.Size <= 4 ? 0 : StringTable.Size);
216 }
217 
218 Expected<StringRef>
219 XCOFFObjectFile::getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const {
220   if (CFileEntPtr->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
221     return generateXCOFFFixedNameStringRef(CFileEntPtr->Name);
222   return getStringTableEntry(CFileEntPtr->NameInStrTbl.Offset);
223 }
224 
225 Expected<StringRef> XCOFFObjectFile::getSymbolName(DataRefImpl Symb) const {
226   return toSymbolRef(Symb).getName();
227 }
228 
229 Expected<uint64_t> XCOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const {
230   return toSymbolRef(Symb).getValue();
231 }
232 
233 uint64_t XCOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
234   return toSymbolRef(Symb).getValue();
235 }
236 
237 uint32_t XCOFFObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
238   uint64_t Result = 0;
239   XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
240   if (XCOFFSym.isCsectSymbol()) {
241     Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
242         XCOFFSym.getXCOFFCsectAuxRef();
243     if (!CsectAuxRefOrError)
244       // TODO: report the error up the stack.
245       consumeError(CsectAuxRefOrError.takeError());
246     else
247       Result = 1ULL << CsectAuxRefOrError.get().getAlignmentLog2();
248   }
249   return Result;
250 }
251 
252 uint64_t XCOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
253   uint64_t Result = 0;
254   XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
255   if (XCOFFSym.isCsectSymbol()) {
256     Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
257         XCOFFSym.getXCOFFCsectAuxRef();
258     if (!CsectAuxRefOrError)
259       // TODO: report the error up the stack.
260       consumeError(CsectAuxRefOrError.takeError());
261     else {
262       XCOFFCsectAuxRef CsectAuxRef = CsectAuxRefOrError.get();
263       assert(CsectAuxRef.getSymbolType() == XCOFF::XTY_CM);
264       Result = CsectAuxRef.getSectionOrLength();
265     }
266   }
267   return Result;
268 }
269 
270 Expected<SymbolRef::Type>
271 XCOFFObjectFile::getSymbolType(DataRefImpl Symb) const {
272   XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
273 
274   if (XCOFFSym.isFunction())
275     return SymbolRef::ST_Function;
276 
277   if (XCOFF::C_FILE == XCOFFSym.getStorageClass())
278     return SymbolRef::ST_File;
279 
280   int16_t SecNum = XCOFFSym.getSectionNumber();
281   if (SecNum <= 0)
282     return SymbolRef::ST_Other;
283 
284   Expected<DataRefImpl> SecDRIOrErr =
285       getSectionByNum(XCOFFSym.getSectionNumber());
286 
287   if (!SecDRIOrErr)
288     return SecDRIOrErr.takeError();
289 
290   DataRefImpl SecDRI = SecDRIOrErr.get();
291 
292   Expected<StringRef> SymNameOrError = XCOFFSym.getName();
293   if (SymNameOrError) {
294     // The "TOC" symbol is treated as SymbolRef::ST_Other.
295     if (SymNameOrError.get() == "TOC")
296       return SymbolRef::ST_Other;
297 
298     // The symbol for a section name is treated as SymbolRef::ST_Other.
299     StringRef SecName;
300     if (is64Bit())
301       SecName = XCOFFObjectFile::toSection64(SecDRIOrErr.get())->getName();
302     else
303       SecName = XCOFFObjectFile::toSection32(SecDRIOrErr.get())->getName();
304 
305     if (SecName == SymNameOrError.get())
306       return SymbolRef::ST_Other;
307   } else
308     return SymNameOrError.takeError();
309 
310   if (isSectionData(SecDRI) || isSectionBSS(SecDRI))
311     return SymbolRef::ST_Data;
312 
313   if (isDebugSection(SecDRI))
314     return SymbolRef::ST_Debug;
315 
316   return SymbolRef::ST_Other;
317 }
318 
319 Expected<section_iterator>
320 XCOFFObjectFile::getSymbolSection(DataRefImpl Symb) const {
321   const int16_t SectNum = toSymbolRef(Symb).getSectionNumber();
322 
323   if (isReservedSectionNumber(SectNum))
324     return section_end();
325 
326   Expected<DataRefImpl> ExpSec = getSectionByNum(SectNum);
327   if (!ExpSec)
328     return ExpSec.takeError();
329 
330   return section_iterator(SectionRef(ExpSec.get(), this));
331 }
332 
333 void XCOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const {
334   const char *Ptr = reinterpret_cast<const char *>(Sec.p);
335   Sec.p = reinterpret_cast<uintptr_t>(Ptr + getSectionHeaderSize());
336 }
337 
338 Expected<StringRef> XCOFFObjectFile::getSectionName(DataRefImpl Sec) const {
339   return generateXCOFFFixedNameStringRef(getSectionNameInternal(Sec));
340 }
341 
342 uint64_t XCOFFObjectFile::getSectionAddress(DataRefImpl Sec) const {
343   // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
344   // with MSVC.
345   if (is64Bit())
346     return toSection64(Sec)->VirtualAddress;
347 
348   return toSection32(Sec)->VirtualAddress;
349 }
350 
351 uint64_t XCOFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
352   // Section numbers in XCOFF are numbered beginning at 1. A section number of
353   // zero is used to indicate that a symbol is being imported or is undefined.
354   if (is64Bit())
355     return toSection64(Sec) - sectionHeaderTable64() + 1;
356   else
357     return toSection32(Sec) - sectionHeaderTable32() + 1;
358 }
359 
360 uint64_t XCOFFObjectFile::getSectionSize(DataRefImpl Sec) const {
361   // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
362   // with MSVC.
363   if (is64Bit())
364     return toSection64(Sec)->SectionSize;
365 
366   return toSection32(Sec)->SectionSize;
367 }
368 
369 Expected<ArrayRef<uint8_t>>
370 XCOFFObjectFile::getSectionContents(DataRefImpl Sec) const {
371   if (isSectionVirtual(Sec))
372     return ArrayRef<uint8_t>();
373 
374   uint64_t OffsetToRaw;
375   if (is64Bit())
376     OffsetToRaw = toSection64(Sec)->FileOffsetToRawData;
377   else
378     OffsetToRaw = toSection32(Sec)->FileOffsetToRawData;
379 
380   const uint8_t * ContentStart = base() + OffsetToRaw;
381   uint64_t SectionSize = getSectionSize(Sec);
382   if (Error E = Binary::checkOffset(
383           Data, reinterpret_cast<uintptr_t>(ContentStart), SectionSize))
384     return createError(
385         toString(std::move(E)) + ": section data with offset 0x" +
386         Twine::utohexstr(OffsetToRaw) + " and size 0x" +
387         Twine::utohexstr(SectionSize) + " goes past the end of the file");
388 
389   return makeArrayRef(ContentStart,SectionSize);
390 }
391 
392 uint64_t XCOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const {
393   uint64_t Result = 0;
394   llvm_unreachable("Not yet implemented!");
395   return Result;
396 }
397 
398 uint64_t XCOFFObjectFile::getSectionFileOffsetToRawData(DataRefImpl Sec) const {
399   if (is64Bit())
400     return toSection64(Sec)->FileOffsetToRawData;
401 
402   return toSection32(Sec)->FileOffsetToRawData;
403 }
404 
405 Expected<uintptr_t> XCOFFObjectFile::getLoaderSectionAddress() const {
406   uint64_t OffsetToLoaderSection = 0;
407   uint64_t SizeOfLoaderSection = 0;
408 
409   if (is64Bit()) {
410     for (const auto &Sec64 : sections64())
411       if (Sec64.getSectionType() == XCOFF::STYP_LOADER) {
412         OffsetToLoaderSection = Sec64.FileOffsetToRawData;
413         SizeOfLoaderSection = Sec64.SectionSize;
414         break;
415       }
416   } else {
417     for (const auto &Sec32 : sections32())
418       if (Sec32.getSectionType() == XCOFF::STYP_LOADER) {
419         OffsetToLoaderSection = Sec32.FileOffsetToRawData;
420         SizeOfLoaderSection = Sec32.SectionSize;
421         break;
422       }
423   }
424 
425   // No loader section is not an error.
426   if (!SizeOfLoaderSection)
427     return 0;
428 
429   uintptr_t LoderSectionStart =
430       reinterpret_cast<uintptr_t>(base() + OffsetToLoaderSection);
431   if (Error E =
432           Binary::checkOffset(Data, LoderSectionStart, SizeOfLoaderSection))
433     return createError(toString(std::move(E)) +
434                        ": loader section with offset 0x" +
435                        Twine::utohexstr(OffsetToLoaderSection) +
436                        " and size 0x" + Twine::utohexstr(SizeOfLoaderSection) +
437                        " goes past the end of the file");
438 
439   return LoderSectionStart;
440 }
441 
442 Expected<uintptr_t> XCOFFObjectFile::getSectionFileOffsetToRawData(
443     XCOFF::SectionTypeFlags SectType) const {
444   DataRefImpl DRI = getSectionByType(SectType);
445 
446   if (DRI.p == 0) // No section is not an error.
447     return 0;
448 
449   uint64_t SectionOffset = getSectionFileOffsetToRawData(DRI);
450   uint64_t SizeOfSection = getSectionSize(DRI);
451 
452   uintptr_t SectionStart = reinterpret_cast<uintptr_t>(base() + SectionOffset);
453   if (Error E = Binary::checkOffset(Data, SectionStart, SizeOfSection)) {
454     SmallString<32> UnknownType;
455     Twine(("<Unknown:") + Twine::utohexstr(SectType) + ">")
456         .toVector(UnknownType);
457     const char *SectionName = UnknownType.c_str();
458 
459     switch (SectType) {
460 #define ECASE(Value, String)                                                   \
461   case XCOFF::Value:                                                           \
462     SectionName = String;                                                      \
463     break
464 
465       ECASE(STYP_PAD, "pad");
466       ECASE(STYP_DWARF, "dwarf");
467       ECASE(STYP_TEXT, "text");
468       ECASE(STYP_DATA, "data");
469       ECASE(STYP_BSS, "bss");
470       ECASE(STYP_EXCEPT, "expect");
471       ECASE(STYP_INFO, "info");
472       ECASE(STYP_TDATA, "tdata");
473       ECASE(STYP_TBSS, "tbss");
474       ECASE(STYP_LOADER, "loader");
475       ECASE(STYP_DEBUG, "debug");
476       ECASE(STYP_TYPCHK, "typchk");
477       ECASE(STYP_OVRFLO, "ovrflo");
478 #undef ECASE
479     }
480     return createError(toString(std::move(E)) + ": " + SectionName +
481                        " section with offset 0x" +
482                        Twine::utohexstr(SectionOffset) + " and size 0x" +
483                        Twine::utohexstr(SizeOfSection) +
484                        " goes past the end of the file");
485   }
486   return SectionStart;
487 }
488 
489 bool XCOFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
490   return false;
491 }
492 
493 bool XCOFFObjectFile::isSectionText(DataRefImpl Sec) const {
494   return getSectionFlags(Sec) & XCOFF::STYP_TEXT;
495 }
496 
497 bool XCOFFObjectFile::isSectionData(DataRefImpl Sec) const {
498   uint32_t Flags = getSectionFlags(Sec);
499   return Flags & (XCOFF::STYP_DATA | XCOFF::STYP_TDATA);
500 }
501 
502 bool XCOFFObjectFile::isSectionBSS(DataRefImpl Sec) const {
503   uint32_t Flags = getSectionFlags(Sec);
504   return Flags & (XCOFF::STYP_BSS | XCOFF::STYP_TBSS);
505 }
506 
507 bool XCOFFObjectFile::isDebugSection(DataRefImpl Sec) const {
508   uint32_t Flags = getSectionFlags(Sec);
509   return Flags & (XCOFF::STYP_DEBUG | XCOFF::STYP_DWARF);
510 }
511 
512 bool XCOFFObjectFile::isSectionVirtual(DataRefImpl Sec) const {
513   return is64Bit() ? toSection64(Sec)->FileOffsetToRawData == 0
514                    : toSection32(Sec)->FileOffsetToRawData == 0;
515 }
516 
517 relocation_iterator XCOFFObjectFile::section_rel_begin(DataRefImpl Sec) const {
518   DataRefImpl Ret;
519   if (is64Bit()) {
520     const XCOFFSectionHeader64 *SectionEntPtr = toSection64(Sec);
521     auto RelocationsOrErr =
522         relocations<XCOFFSectionHeader64, XCOFFRelocation64>(*SectionEntPtr);
523     if (Error E = RelocationsOrErr.takeError()) {
524       // TODO: report the error up the stack.
525       consumeError(std::move(E));
526       return relocation_iterator(RelocationRef());
527     }
528     Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin());
529   } else {
530     const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
531     auto RelocationsOrErr =
532         relocations<XCOFFSectionHeader32, XCOFFRelocation32>(*SectionEntPtr);
533     if (Error E = RelocationsOrErr.takeError()) {
534       // TODO: report the error up the stack.
535       consumeError(std::move(E));
536       return relocation_iterator(RelocationRef());
537     }
538     Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin());
539   }
540   return relocation_iterator(RelocationRef(Ret, this));
541 }
542 
543 relocation_iterator XCOFFObjectFile::section_rel_end(DataRefImpl Sec) const {
544   DataRefImpl Ret;
545   if (is64Bit()) {
546     const XCOFFSectionHeader64 *SectionEntPtr = toSection64(Sec);
547     auto RelocationsOrErr =
548         relocations<XCOFFSectionHeader64, XCOFFRelocation64>(*SectionEntPtr);
549     if (Error E = RelocationsOrErr.takeError()) {
550       // TODO: report the error up the stack.
551       consumeError(std::move(E));
552       return relocation_iterator(RelocationRef());
553     }
554     Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end());
555   } else {
556     const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
557     auto RelocationsOrErr =
558         relocations<XCOFFSectionHeader32, XCOFFRelocation32>(*SectionEntPtr);
559     if (Error E = RelocationsOrErr.takeError()) {
560       // TODO: report the error up the stack.
561       consumeError(std::move(E));
562       return relocation_iterator(RelocationRef());
563     }
564     Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end());
565   }
566   return relocation_iterator(RelocationRef(Ret, this));
567 }
568 
569 void XCOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
570   if (is64Bit())
571     Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation64>(Rel.p) + 1);
572   else
573     Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation32>(Rel.p) + 1);
574 }
575 
576 uint64_t XCOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
577   if (is64Bit()) {
578     const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
579     const XCOFFSectionHeader64 *Sec64 = sectionHeaderTable64();
580     const uint64_t RelocAddress = Reloc->VirtualAddress;
581     const uint16_t NumberOfSections = getNumberOfSections();
582     for (uint16_t I = 0; I < NumberOfSections; ++I) {
583       // Find which section this relocation belongs to, and get the
584       // relocation offset relative to the start of the section.
585       if (Sec64->VirtualAddress <= RelocAddress &&
586           RelocAddress < Sec64->VirtualAddress + Sec64->SectionSize) {
587         return RelocAddress - Sec64->VirtualAddress;
588       }
589       ++Sec64;
590     }
591   } else {
592     const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
593     const XCOFFSectionHeader32 *Sec32 = sectionHeaderTable32();
594     const uint32_t RelocAddress = Reloc->VirtualAddress;
595     const uint16_t NumberOfSections = getNumberOfSections();
596     for (uint16_t I = 0; I < NumberOfSections; ++I) {
597       // Find which section this relocation belongs to, and get the
598       // relocation offset relative to the start of the section.
599       if (Sec32->VirtualAddress <= RelocAddress &&
600           RelocAddress < Sec32->VirtualAddress + Sec32->SectionSize) {
601         return RelocAddress - Sec32->VirtualAddress;
602       }
603       ++Sec32;
604     }
605   }
606   return InvalidRelocOffset;
607 }
608 
609 symbol_iterator XCOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
610   uint32_t Index;
611   if (is64Bit()) {
612     const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
613     Index = Reloc->SymbolIndex;
614 
615     if (Index >= getNumberOfSymbolTableEntries64())
616       return symbol_end();
617   } else {
618     const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
619     Index = Reloc->SymbolIndex;
620 
621     if (Index >= getLogicalNumberOfSymbolTableEntries32())
622       return symbol_end();
623   }
624   DataRefImpl SymDRI;
625   SymDRI.p = getSymbolEntryAddressByIndex(Index);
626   return symbol_iterator(SymbolRef(SymDRI, this));
627 }
628 
629 uint64_t XCOFFObjectFile::getRelocationType(DataRefImpl Rel) const {
630   if (is64Bit())
631     return viewAs<XCOFFRelocation64>(Rel.p)->Type;
632   return viewAs<XCOFFRelocation32>(Rel.p)->Type;
633 }
634 
635 void XCOFFObjectFile::getRelocationTypeName(
636     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
637   StringRef Res;
638   if (is64Bit()) {
639     const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
640     Res = XCOFF::getRelocationTypeString(Reloc->Type);
641   } else {
642     const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
643     Res = XCOFF::getRelocationTypeString(Reloc->Type);
644   }
645   Result.append(Res.begin(), Res.end());
646 }
647 
648 Expected<uint32_t> XCOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const {
649   XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
650   uint32_t Result = SymbolRef::SF_None;
651 
652   if (XCOFFSym.getSectionNumber() == XCOFF::N_ABS)
653     Result |= SymbolRef::SF_Absolute;
654 
655   XCOFF::StorageClass SC = XCOFFSym.getStorageClass();
656   if (XCOFF::C_EXT == SC || XCOFF::C_WEAKEXT == SC)
657     Result |= SymbolRef::SF_Global;
658 
659   if (XCOFF::C_WEAKEXT == SC)
660     Result |= SymbolRef::SF_Weak;
661 
662   if (XCOFFSym.isCsectSymbol()) {
663     Expected<XCOFFCsectAuxRef> CsectAuxEntOrErr =
664         XCOFFSym.getXCOFFCsectAuxRef();
665     if (CsectAuxEntOrErr) {
666       if (CsectAuxEntOrErr.get().getSymbolType() == XCOFF::XTY_CM)
667         Result |= SymbolRef::SF_Common;
668     } else
669       return CsectAuxEntOrErr.takeError();
670   }
671 
672   if (XCOFFSym.getSectionNumber() == XCOFF::N_UNDEF)
673     Result |= SymbolRef::SF_Undefined;
674 
675   // There is no visibility in old 32 bit XCOFF object file interpret.
676   if (is64Bit() || (auxiliaryHeader32() && (auxiliaryHeader32()->getVersion() ==
677                                             NEW_XCOFF_INTERPRET))) {
678     uint16_t SymType = XCOFFSym.getSymbolType();
679     if ((SymType & VISIBILITY_MASK) == SYM_V_HIDDEN)
680       Result |= SymbolRef::SF_Hidden;
681 
682     if ((SymType & VISIBILITY_MASK) == SYM_V_EXPORTED)
683       Result |= SymbolRef::SF_Exported;
684   }
685   return Result;
686 }
687 
688 basic_symbol_iterator XCOFFObjectFile::symbol_begin() const {
689   DataRefImpl SymDRI;
690   SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr);
691   return basic_symbol_iterator(SymbolRef(SymDRI, this));
692 }
693 
694 basic_symbol_iterator XCOFFObjectFile::symbol_end() const {
695   DataRefImpl SymDRI;
696   const uint32_t NumberOfSymbolTableEntries = getNumberOfSymbolTableEntries();
697   SymDRI.p = getSymbolEntryAddressByIndex(NumberOfSymbolTableEntries);
698   return basic_symbol_iterator(SymbolRef(SymDRI, this));
699 }
700 
701 section_iterator XCOFFObjectFile::section_begin() const {
702   DataRefImpl DRI;
703   DRI.p = getSectionHeaderTableAddress();
704   return section_iterator(SectionRef(DRI, this));
705 }
706 
707 section_iterator XCOFFObjectFile::section_end() const {
708   DataRefImpl DRI;
709   DRI.p = getWithOffset(getSectionHeaderTableAddress(),
710                         getNumberOfSections() * getSectionHeaderSize());
711   return section_iterator(SectionRef(DRI, this));
712 }
713 
714 uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; }
715 
716 StringRef XCOFFObjectFile::getFileFormatName() const {
717   return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000";
718 }
719 
720 Triple::ArchType XCOFFObjectFile::getArch() const {
721   return is64Bit() ? Triple::ppc64 : Triple::ppc;
722 }
723 
724 SubtargetFeatures XCOFFObjectFile::getFeatures() const {
725   return SubtargetFeatures();
726 }
727 
728 bool XCOFFObjectFile::isRelocatableObject() const {
729   if (is64Bit())
730     return !(fileHeader64()->Flags & NoRelMask);
731   return !(fileHeader32()->Flags & NoRelMask);
732 }
733 
734 Expected<uint64_t> XCOFFObjectFile::getStartAddress() const {
735   // TODO FIXME Should get from auxiliary_header->o_entry when support for the
736   // auxiliary_header is added.
737   return 0;
738 }
739 
740 StringRef XCOFFObjectFile::mapDebugSectionName(StringRef Name) const {
741   return StringSwitch<StringRef>(Name)
742       .Case("dwinfo", "debug_info")
743       .Case("dwline", "debug_line")
744       .Case("dwpbnms", "debug_pubnames")
745       .Case("dwpbtyp", "debug_pubtypes")
746       .Case("dwarnge", "debug_aranges")
747       .Case("dwabrev", "debug_abbrev")
748       .Case("dwstr", "debug_str")
749       .Case("dwrnges", "debug_ranges")
750       .Case("dwloc", "debug_loc")
751       .Case("dwframe", "debug_frame")
752       .Case("dwmac", "debug_macinfo")
753       .Default(Name);
754 }
755 
756 size_t XCOFFObjectFile::getFileHeaderSize() const {
757   return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32);
758 }
759 
760 size_t XCOFFObjectFile::getSectionHeaderSize() const {
761   return is64Bit() ? sizeof(XCOFFSectionHeader64) :
762                      sizeof(XCOFFSectionHeader32);
763 }
764 
765 bool XCOFFObjectFile::is64Bit() const {
766   return Binary::ID_XCOFF64 == getType();
767 }
768 
769 Expected<StringRef> XCOFFObjectFile::getRawData(const char *Start,
770                                                 uint64_t Size,
771                                                 StringRef Name) const {
772   uintptr_t StartPtr = reinterpret_cast<uintptr_t>(Start);
773   // TODO: this path is untested.
774   if (Error E = Binary::checkOffset(Data, StartPtr, Size))
775     return createError(toString(std::move(E)) + ": " + Name.data() +
776                        " data with offset 0x" + Twine::utohexstr(StartPtr) +
777                        " and size 0x" + Twine::utohexstr(Size) +
778                        " goes past the end of the file");
779   return StringRef(Start, Size);
780 }
781 
782 uint16_t XCOFFObjectFile::getMagic() const {
783   return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic;
784 }
785 
786 Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const {
787   if (Num <= 0 || Num > getNumberOfSections())
788     return createStringError(object_error::invalid_section_index,
789                              "the section index (" + Twine(Num) +
790                                  ") is invalid");
791 
792   DataRefImpl DRI;
793   DRI.p = getWithOffset(getSectionHeaderTableAddress(),
794                         getSectionHeaderSize() * (Num - 1));
795   return DRI;
796 }
797 
798 DataRefImpl
799 XCOFFObjectFile::getSectionByType(XCOFF::SectionTypeFlags SectType) const {
800   DataRefImpl DRI;
801   auto GetSectionAddr = [&](const auto &Sections) -> uintptr_t {
802     for (const auto &Sec : Sections)
803       if (Sec.getSectionType() == SectType)
804         return reinterpret_cast<uintptr_t>(&Sec);
805     return 0ul;
806   };
807   if (is64Bit())
808     DRI.p = GetSectionAddr(sections64());
809   else
810     DRI.p = GetSectionAddr(sections32());
811   return DRI;
812 }
813 
814 Expected<StringRef>
815 XCOFFObjectFile::getSymbolSectionName(XCOFFSymbolRef SymEntPtr) const {
816   const int16_t SectionNum = SymEntPtr.getSectionNumber();
817 
818   switch (SectionNum) {
819   case XCOFF::N_DEBUG:
820     return "N_DEBUG";
821   case XCOFF::N_ABS:
822     return "N_ABS";
823   case XCOFF::N_UNDEF:
824     return "N_UNDEF";
825   default:
826     Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum);
827     if (SecRef)
828       return generateXCOFFFixedNameStringRef(
829           getSectionNameInternal(SecRef.get()));
830     return SecRef.takeError();
831   }
832 }
833 
834 unsigned XCOFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
835   XCOFFSymbolRef XCOFFSymRef(Sym.getRawDataRefImpl(), this);
836   return XCOFFSymRef.getSectionNumber();
837 }
838 
839 bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) {
840   return (SectionNumber <= 0 && SectionNumber >= -2);
841 }
842 
843 uint16_t XCOFFObjectFile::getNumberOfSections() const {
844   return is64Bit() ? fileHeader64()->NumberOfSections
845                    : fileHeader32()->NumberOfSections;
846 }
847 
848 int32_t XCOFFObjectFile::getTimeStamp() const {
849   return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp;
850 }
851 
852 uint16_t XCOFFObjectFile::getOptionalHeaderSize() const {
853   return is64Bit() ? fileHeader64()->AuxHeaderSize
854                    : fileHeader32()->AuxHeaderSize;
855 }
856 
857 uint32_t XCOFFObjectFile::getSymbolTableOffset32() const {
858   return fileHeader32()->SymbolTableOffset;
859 }
860 
861 int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const {
862   // As far as symbol table size is concerned, if this field is negative it is
863   // to be treated as a 0. However since this field is also used for printing we
864   // don't want to truncate any negative values.
865   return fileHeader32()->NumberOfSymTableEntries;
866 }
867 
868 uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const {
869   return (fileHeader32()->NumberOfSymTableEntries >= 0
870               ? fileHeader32()->NumberOfSymTableEntries
871               : 0);
872 }
873 
874 uint64_t XCOFFObjectFile::getSymbolTableOffset64() const {
875   return fileHeader64()->SymbolTableOffset;
876 }
877 
878 uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const {
879   return fileHeader64()->NumberOfSymTableEntries;
880 }
881 
882 uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries() const {
883   return is64Bit() ? getNumberOfSymbolTableEntries64()
884                    : getLogicalNumberOfSymbolTableEntries32();
885 }
886 
887 uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const {
888   const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
889   return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr),
890                        XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries);
891 }
892 
893 void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const {
894   if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr))
895     report_fatal_error("Symbol table entry is outside of symbol table.");
896 
897   if (SymbolEntPtr >= getEndOfSymbolTableAddress())
898     report_fatal_error("Symbol table entry is outside of symbol table.");
899 
900   ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) -
901                      reinterpret_cast<const char *>(SymbolTblPtr);
902 
903   if (Offset % XCOFF::SymbolTableEntrySize != 0)
904     report_fatal_error(
905         "Symbol table entry position is not valid inside of symbol table.");
906 }
907 
908 uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const {
909   return (reinterpret_cast<const char *>(SymbolEntPtr) -
910           reinterpret_cast<const char *>(SymbolTblPtr)) /
911          XCOFF::SymbolTableEntrySize;
912 }
913 
914 uint64_t XCOFFObjectFile::getSymbolSize(DataRefImpl Symb) const {
915   uint64_t Result = 0;
916   XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
917   if (XCOFFSym.isCsectSymbol()) {
918     Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
919         XCOFFSym.getXCOFFCsectAuxRef();
920     if (!CsectAuxRefOrError)
921       // TODO: report the error up the stack.
922       consumeError(CsectAuxRefOrError.takeError());
923     else {
924       XCOFFCsectAuxRef CsectAuxRef = CsectAuxRefOrError.get();
925       uint8_t SymType = CsectAuxRef.getSymbolType();
926       if (SymType == XCOFF::XTY_SD || SymType == XCOFF::XTY_CM)
927         Result = CsectAuxRef.getSectionOrLength();
928     }
929   }
930   return Result;
931 }
932 
933 uintptr_t XCOFFObjectFile::getSymbolEntryAddressByIndex(uint32_t Index) const {
934   return getAdvancedSymbolEntryAddress(
935       reinterpret_cast<uintptr_t>(getPointerToSymbolTable()), Index);
936 }
937 
938 Expected<StringRef>
939 XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const {
940   const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
941 
942   if (Index >= NumberOfSymTableEntries)
943     return createError("symbol index " + Twine(Index) +
944                        " exceeds symbol count " +
945                        Twine(NumberOfSymTableEntries));
946 
947   DataRefImpl SymDRI;
948   SymDRI.p = getSymbolEntryAddressByIndex(Index);
949   return getSymbolName(SymDRI);
950 }
951 
952 uint16_t XCOFFObjectFile::getFlags() const {
953   return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags;
954 }
955 
956 const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const {
957   return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name;
958 }
959 
960 uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const {
961   return reinterpret_cast<uintptr_t>(SectionHeaderTable);
962 }
963 
964 int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const {
965   return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags;
966 }
967 
968 XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object)
969     : ObjectFile(Type, Object) {
970   assert(Type == Binary::ID_XCOFF32 || Type == Binary::ID_XCOFF64);
971 }
972 
973 ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const {
974   assert(is64Bit() && "64-bit interface called for non 64-bit file.");
975   const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64();
976   return ArrayRef<XCOFFSectionHeader64>(TablePtr,
977                                         TablePtr + getNumberOfSections());
978 }
979 
980 ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const {
981   assert(!is64Bit() && "32-bit interface called for non 32-bit file.");
982   const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32();
983   return ArrayRef<XCOFFSectionHeader32>(TablePtr,
984                                         TablePtr + getNumberOfSections());
985 }
986 
987 // In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO
988 // section header contains the actual count of relocation entries in the s_paddr
989 // field. STYP_OVRFLO headers contain the section index of their corresponding
990 // sections as their raw "NumberOfRelocations" field value.
991 template <typename T>
992 Expected<uint32_t> XCOFFObjectFile::getNumberOfRelocationEntries(
993     const XCOFFSectionHeader<T> &Sec) const {
994   const T &Section = static_cast<const T &>(Sec);
995   if (is64Bit())
996     return Section.NumberOfRelocations;
997 
998   uint16_t SectionIndex = &Section - sectionHeaderTable<T>() + 1;
999   if (Section.NumberOfRelocations < XCOFF::RelocOverflow)
1000     return Section.NumberOfRelocations;
1001   for (const auto &Sec : sections32()) {
1002     if (Sec.Flags == XCOFF::STYP_OVRFLO &&
1003         Sec.NumberOfRelocations == SectionIndex)
1004       return Sec.PhysicalAddress;
1005   }
1006   return errorCodeToError(object_error::parse_failed);
1007 }
1008 
1009 template <typename Shdr, typename Reloc>
1010 Expected<ArrayRef<Reloc>> XCOFFObjectFile::relocations(const Shdr &Sec) const {
1011   uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader),
1012                                       Sec.FileOffsetToRelocationInfo);
1013   auto NumRelocEntriesOrErr = getNumberOfRelocationEntries(Sec);
1014   if (Error E = NumRelocEntriesOrErr.takeError())
1015     return std::move(E);
1016 
1017   uint32_t NumRelocEntries = NumRelocEntriesOrErr.get();
1018   static_assert((sizeof(Reloc) == XCOFF::RelocationSerializationSize64 ||
1019                  sizeof(Reloc) == XCOFF::RelocationSerializationSize32),
1020                 "Relocation structure is incorrect");
1021   auto RelocationOrErr =
1022       getObject<Reloc>(Data, reinterpret_cast<void *>(RelocAddr),
1023                        NumRelocEntries * sizeof(Reloc));
1024   if (!RelocationOrErr)
1025     return createError(
1026         toString(RelocationOrErr.takeError()) + ": relocations with offset 0x" +
1027         Twine::utohexstr(Sec.FileOffsetToRelocationInfo) + " and size 0x" +
1028         Twine::utohexstr(NumRelocEntries * sizeof(Reloc)) +
1029         " go past the end of the file");
1030 
1031   const Reloc *StartReloc = RelocationOrErr.get();
1032 
1033   return ArrayRef<Reloc>(StartReloc, StartReloc + NumRelocEntries);
1034 }
1035 
1036 template <typename ExceptEnt>
1037 Expected<ArrayRef<ExceptEnt>> XCOFFObjectFile::getExceptionEntries() const {
1038   assert(is64Bit() && sizeof(ExceptEnt) == sizeof(ExceptionSectionEntry64) ||
1039          !is64Bit() && sizeof(ExceptEnt) == sizeof(ExceptionSectionEntry32));
1040 
1041   Expected<uintptr_t> ExceptionSectOrErr =
1042       getSectionFileOffsetToRawData(XCOFF::STYP_EXCEPT);
1043   if (!ExceptionSectOrErr)
1044     return ExceptionSectOrErr.takeError();
1045 
1046   DataRefImpl DRI = getSectionByType(XCOFF::STYP_EXCEPT);
1047   if (DRI.p == 0)
1048     return ArrayRef<ExceptEnt>();
1049 
1050   ExceptEnt *ExceptEntStart =
1051       reinterpret_cast<ExceptEnt *>(*ExceptionSectOrErr);
1052   return ArrayRef<ExceptEnt>(
1053       ExceptEntStart, ExceptEntStart + getSectionSize(DRI) / sizeof(ExceptEnt));
1054 }
1055 
1056 template Expected<ArrayRef<ExceptionSectionEntry32>>
1057 XCOFFObjectFile::getExceptionEntries() const;
1058 template Expected<ArrayRef<ExceptionSectionEntry64>>
1059 XCOFFObjectFile::getExceptionEntries() const;
1060 
1061 Expected<XCOFFStringTable>
1062 XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) {
1063   // If there is a string table, then the buffer must contain at least 4 bytes
1064   // for the string table's size. Not having a string table is not an error.
1065   if (Error E = Binary::checkOffset(
1066           Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4)) {
1067     consumeError(std::move(E));
1068     return XCOFFStringTable{0, nullptr};
1069   }
1070 
1071   // Read the size out of the buffer.
1072   uint32_t Size = support::endian::read32be(Obj->base() + Offset);
1073 
1074   // If the size is less then 4, then the string table is just a size and no
1075   // string data.
1076   if (Size <= 4)
1077     return XCOFFStringTable{4, nullptr};
1078 
1079   auto StringTableOrErr =
1080       getObject<char>(Obj->Data, Obj->base() + Offset, Size);
1081   if (!StringTableOrErr)
1082     return createError(toString(StringTableOrErr.takeError()) +
1083                        ": string table with offset 0x" +
1084                        Twine::utohexstr(Offset) + " and size 0x" +
1085                        Twine::utohexstr(Size) +
1086                        " goes past the end of the file");
1087 
1088   const char *StringTablePtr = StringTableOrErr.get();
1089   if (StringTablePtr[Size - 1] != '\0')
1090     return errorCodeToError(object_error::string_table_non_null_end);
1091 
1092   return XCOFFStringTable{Size, StringTablePtr};
1093 }
1094 
1095 // This function returns the import file table. Each entry in the import file
1096 // table consists of: "path_name\0base_name\0archive_member_name\0".
1097 Expected<StringRef> XCOFFObjectFile::getImportFileTable() const {
1098   Expected<uintptr_t> LoaderSectionAddrOrError = getLoaderSectionAddress();
1099   if (!LoaderSectionAddrOrError)
1100     return LoaderSectionAddrOrError.takeError();
1101 
1102   uintptr_t LoaderSectionAddr = LoaderSectionAddrOrError.get();
1103   if (!LoaderSectionAddr)
1104     return StringRef();
1105 
1106   uint64_t OffsetToImportFileTable = 0;
1107   uint64_t LengthOfImportFileTable = 0;
1108   if (is64Bit()) {
1109     const LoaderSectionHeader64 *LoaderSec64 =
1110         viewAs<LoaderSectionHeader64>(LoaderSectionAddr);
1111     OffsetToImportFileTable = LoaderSec64->OffsetToImpid;
1112     LengthOfImportFileTable = LoaderSec64->LengthOfImpidStrTbl;
1113   } else {
1114     const LoaderSectionHeader32 *LoaderSec32 =
1115         viewAs<LoaderSectionHeader32>(LoaderSectionAddr);
1116     OffsetToImportFileTable = LoaderSec32->OffsetToImpid;
1117     LengthOfImportFileTable = LoaderSec32->LengthOfImpidStrTbl;
1118   }
1119 
1120   auto ImportTableOrErr = getObject<char>(
1121       Data,
1122       reinterpret_cast<void *>(LoaderSectionAddr + OffsetToImportFileTable),
1123       LengthOfImportFileTable);
1124   if (!ImportTableOrErr)
1125     return createError(
1126         toString(ImportTableOrErr.takeError()) +
1127         ": import file table with offset 0x" +
1128         Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
1129         " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
1130         " goes past the end of the file");
1131 
1132   const char *ImportTablePtr = ImportTableOrErr.get();
1133   if (ImportTablePtr[LengthOfImportFileTable - 1] != '\0')
1134     return createError(
1135         ": import file name table with offset 0x" +
1136         Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
1137         " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
1138         " must end with a null terminator");
1139 
1140   return StringRef(ImportTablePtr, LengthOfImportFileTable);
1141 }
1142 
1143 Expected<std::unique_ptr<XCOFFObjectFile>>
1144 XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) {
1145   // Can't use std::make_unique because of the private constructor.
1146   std::unique_ptr<XCOFFObjectFile> Obj;
1147   Obj.reset(new XCOFFObjectFile(Type, MBR));
1148 
1149   uint64_t CurOffset = 0;
1150   const auto *Base = Obj->base();
1151   MemoryBufferRef Data = Obj->Data;
1152 
1153   // Parse file header.
1154   auto FileHeaderOrErr =
1155       getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize());
1156   if (Error E = FileHeaderOrErr.takeError())
1157     return std::move(E);
1158   Obj->FileHeader = FileHeaderOrErr.get();
1159 
1160   CurOffset += Obj->getFileHeaderSize();
1161 
1162   if (Obj->getOptionalHeaderSize()) {
1163     auto AuxiliaryHeaderOrErr =
1164         getObject<void>(Data, Base + CurOffset, Obj->getOptionalHeaderSize());
1165     if (Error E = AuxiliaryHeaderOrErr.takeError())
1166       return std::move(E);
1167     Obj->AuxiliaryHeader = AuxiliaryHeaderOrErr.get();
1168   }
1169 
1170   CurOffset += Obj->getOptionalHeaderSize();
1171 
1172   // Parse the section header table if it is present.
1173   if (Obj->getNumberOfSections()) {
1174     uint64_t SectionHeadersSize =
1175         Obj->getNumberOfSections() * Obj->getSectionHeaderSize();
1176     auto SecHeadersOrErr =
1177         getObject<void>(Data, Base + CurOffset, SectionHeadersSize);
1178     if (!SecHeadersOrErr)
1179       return createError(toString(SecHeadersOrErr.takeError()) +
1180                          ": section headers with offset 0x" +
1181                          Twine::utohexstr(CurOffset) + " and size 0x" +
1182                          Twine::utohexstr(SectionHeadersSize) +
1183                          " go past the end of the file");
1184 
1185     Obj->SectionHeaderTable = SecHeadersOrErr.get();
1186   }
1187 
1188   const uint32_t NumberOfSymbolTableEntries =
1189       Obj->getNumberOfSymbolTableEntries();
1190 
1191   // If there is no symbol table we are done parsing the memory buffer.
1192   if (NumberOfSymbolTableEntries == 0)
1193     return std::move(Obj);
1194 
1195   // Parse symbol table.
1196   CurOffset = Obj->is64Bit() ? Obj->getSymbolTableOffset64()
1197                              : Obj->getSymbolTableOffset32();
1198   const uint64_t SymbolTableSize =
1199       static_cast<uint64_t>(XCOFF::SymbolTableEntrySize) *
1200       NumberOfSymbolTableEntries;
1201   auto SymTableOrErr =
1202       getObject<void *>(Data, Base + CurOffset, SymbolTableSize);
1203   if (!SymTableOrErr)
1204     return createError(
1205         toString(SymTableOrErr.takeError()) + ": symbol table with offset 0x" +
1206         Twine::utohexstr(CurOffset) + " and size 0x" +
1207         Twine::utohexstr(SymbolTableSize) + " goes past the end of the file");
1208 
1209   Obj->SymbolTblPtr = SymTableOrErr.get();
1210   CurOffset += SymbolTableSize;
1211 
1212   // Parse String table.
1213   Expected<XCOFFStringTable> StringTableOrErr =
1214       parseStringTable(Obj.get(), CurOffset);
1215   if (Error E = StringTableOrErr.takeError())
1216     return std::move(E);
1217   Obj->StringTable = StringTableOrErr.get();
1218 
1219   return std::move(Obj);
1220 }
1221 
1222 Expected<std::unique_ptr<ObjectFile>>
1223 ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef,
1224                                   unsigned FileType) {
1225   return XCOFFObjectFile::create(FileType, MemBufRef);
1226 }
1227 
1228 bool XCOFFSymbolRef::isFunction() const {
1229   if (!isCsectSymbol())
1230     return false;
1231 
1232   if (getSymbolType() & FunctionSym)
1233     return true;
1234 
1235   Expected<XCOFFCsectAuxRef> ExpCsectAuxEnt = getXCOFFCsectAuxRef();
1236   if (!ExpCsectAuxEnt) {
1237     // If we could not get the CSECT auxiliary entry, then treat this symbol as
1238     // if it isn't a function. Consume the error and return `false` to move on.
1239     consumeError(ExpCsectAuxEnt.takeError());
1240     return false;
1241   }
1242 
1243   const XCOFFCsectAuxRef CsectAuxRef = ExpCsectAuxEnt.get();
1244 
1245   // A function definition should be a label definition.
1246   // FIXME: This is not necessarily the case when -ffunction-sections is
1247   // enabled.
1248   if (!CsectAuxRef.isLabel())
1249     return false;
1250 
1251   if (CsectAuxRef.getStorageMappingClass() != XCOFF::XMC_PR)
1252     return false;
1253 
1254   const int16_t SectNum = getSectionNumber();
1255   Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum);
1256   if (!SI) {
1257     // If we could not get the section, then this symbol should not be
1258     // a function. So consume the error and return `false` to move on.
1259     consumeError(SI.takeError());
1260     return false;
1261   }
1262 
1263   return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT);
1264 }
1265 
1266 bool XCOFFSymbolRef::isCsectSymbol() const {
1267   XCOFF::StorageClass SC = getStorageClass();
1268   return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT ||
1269           SC == XCOFF::C_HIDEXT);
1270 }
1271 
1272 Expected<XCOFFCsectAuxRef> XCOFFSymbolRef::getXCOFFCsectAuxRef() const {
1273   assert(isCsectSymbol() &&
1274          "Calling csect symbol interface with a non-csect symbol.");
1275 
1276   uint8_t NumberOfAuxEntries = getNumberOfAuxEntries();
1277 
1278   Expected<StringRef> NameOrErr = getName();
1279   if (auto Err = NameOrErr.takeError())
1280     return std::move(Err);
1281 
1282   uint32_t SymbolIdx = OwningObjectPtr->getSymbolIndex(getEntryAddress());
1283   if (!NumberOfAuxEntries) {
1284     return createError("csect symbol \"" + *NameOrErr + "\" with index " +
1285                        Twine(SymbolIdx) + " contains no auxiliary entry");
1286   }
1287 
1288   if (!OwningObjectPtr->is64Bit()) {
1289     // In XCOFF32, the csect auxilliary entry is always the last auxiliary
1290     // entry for the symbol.
1291     uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
1292         getEntryAddress(), NumberOfAuxEntries);
1293     return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt32>(AuxAddr));
1294   }
1295 
1296   // XCOFF64 uses SymbolAuxType to identify the auxiliary entry type.
1297   // We need to iterate through all the auxiliary entries to find it.
1298   for (uint8_t Index = NumberOfAuxEntries; Index > 0; --Index) {
1299     uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
1300         getEntryAddress(), Index);
1301     if (*OwningObjectPtr->getSymbolAuxType(AuxAddr) ==
1302         XCOFF::SymbolAuxType::AUX_CSECT) {
1303 #ifndef NDEBUG
1304       OwningObjectPtr->checkSymbolEntryPointer(AuxAddr);
1305 #endif
1306       return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt64>(AuxAddr));
1307     }
1308   }
1309 
1310   return createError(
1311       "a csect auxiliary entry has not been found for symbol \"" + *NameOrErr +
1312       "\" with index " + Twine(SymbolIdx));
1313 }
1314 
1315 Expected<StringRef> XCOFFSymbolRef::getName() const {
1316   // A storage class value with the high-order bit on indicates that the name is
1317   // a symbolic debugger stabstring.
1318   if (getStorageClass() & 0x80)
1319     return StringRef("Unimplemented Debug Name");
1320 
1321   if (Entry32) {
1322     if (Entry32->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
1323       return generateXCOFFFixedNameStringRef(Entry32->SymbolName);
1324 
1325     return OwningObjectPtr->getStringTableEntry(Entry32->NameInStrTbl.Offset);
1326   }
1327 
1328   return OwningObjectPtr->getStringTableEntry(Entry64->Offset);
1329 }
1330 
1331 // Explictly instantiate template classes.
1332 template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
1333 template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
1334 
1335 template struct XCOFFRelocation<llvm::support::ubig32_t>;
1336 template struct XCOFFRelocation<llvm::support::ubig64_t>;
1337 
1338 template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation64>>
1339 llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader64,
1340                                            llvm::object::XCOFFRelocation64>(
1341     llvm::object::XCOFFSectionHeader64 const &) const;
1342 template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation32>>
1343 llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader32,
1344                                            llvm::object::XCOFFRelocation32>(
1345     llvm::object::XCOFFSectionHeader32 const &) const;
1346 
1347 bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes) {
1348   if (Bytes.size() < 4)
1349     return false;
1350 
1351   return support::endian::read32be(Bytes.data()) == 0;
1352 }
1353 
1354 #define GETVALUEWITHMASK(X) (Data & (TracebackTable::X))
1355 #define GETVALUEWITHMASKSHIFT(X, S)                                            \
1356   ((Data & (TracebackTable::X)) >> (TracebackTable::S))
1357 
1358 Expected<TBVectorExt> TBVectorExt::create(StringRef TBvectorStrRef) {
1359   Error Err = Error::success();
1360   TBVectorExt TBTVecExt(TBvectorStrRef, Err);
1361   if (Err)
1362     return std::move(Err);
1363   return TBTVecExt;
1364 }
1365 
1366 TBVectorExt::TBVectorExt(StringRef TBvectorStrRef, Error &Err) {
1367   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(TBvectorStrRef.data());
1368   Data = support::endian::read16be(Ptr);
1369   uint32_t VecParmsTypeValue = support::endian::read32be(Ptr + 2);
1370   unsigned ParmsNum =
1371       GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask, NumberOfVectorParmsShift);
1372 
1373   ErrorAsOutParameter EAO(&Err);
1374   Expected<SmallString<32>> VecParmsTypeOrError =
1375       parseVectorParmsType(VecParmsTypeValue, ParmsNum);
1376   if (!VecParmsTypeOrError)
1377     Err = VecParmsTypeOrError.takeError();
1378   else
1379     VecParmsInfo = VecParmsTypeOrError.get();
1380 }
1381 
1382 uint8_t TBVectorExt::getNumberOfVRSaved() const {
1383   return GETVALUEWITHMASKSHIFT(NumberOfVRSavedMask, NumberOfVRSavedShift);
1384 }
1385 
1386 bool TBVectorExt::isVRSavedOnStack() const {
1387   return GETVALUEWITHMASK(IsVRSavedOnStackMask);
1388 }
1389 
1390 bool TBVectorExt::hasVarArgs() const {
1391   return GETVALUEWITHMASK(HasVarArgsMask);
1392 }
1393 
1394 uint8_t TBVectorExt::getNumberOfVectorParms() const {
1395   return GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask,
1396                                NumberOfVectorParmsShift);
1397 }
1398 
1399 bool TBVectorExt::hasVMXInstruction() const {
1400   return GETVALUEWITHMASK(HasVMXInstructionMask);
1401 }
1402 #undef GETVALUEWITHMASK
1403 #undef GETVALUEWITHMASKSHIFT
1404 
1405 Expected<XCOFFTracebackTable> XCOFFTracebackTable::create(const uint8_t *Ptr,
1406                                                           uint64_t &Size) {
1407   Error Err = Error::success();
1408   XCOFFTracebackTable TBT(Ptr, Size, Err);
1409   if (Err)
1410     return std::move(Err);
1411   return TBT;
1412 }
1413 
1414 XCOFFTracebackTable::XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size,
1415                                          Error &Err)
1416     : TBPtr(Ptr) {
1417   ErrorAsOutParameter EAO(&Err);
1418   DataExtractor DE(ArrayRef<uint8_t>(Ptr, Size), /*IsLittleEndian=*/false,
1419                    /*AddressSize=*/0);
1420   DataExtractor::Cursor Cur(/*Offset=*/0);
1421 
1422   // Skip 8 bytes of mandatory fields.
1423   DE.getU64(Cur);
1424 
1425   unsigned FixedParmsNum = getNumberOfFixedParms();
1426   unsigned FloatingParmsNum = getNumberOfFPParms();
1427   uint32_t ParamsTypeValue = 0;
1428 
1429   // Begin to parse optional fields.
1430   if (Cur && (FixedParmsNum + FloatingParmsNum) > 0)
1431     ParamsTypeValue = DE.getU32(Cur);
1432 
1433   if (Cur && hasTraceBackTableOffset())
1434     TraceBackTableOffset = DE.getU32(Cur);
1435 
1436   if (Cur && isInterruptHandler())
1437     HandlerMask = DE.getU32(Cur);
1438 
1439   if (Cur && hasControlledStorage()) {
1440     NumOfCtlAnchors = DE.getU32(Cur);
1441     if (Cur && NumOfCtlAnchors) {
1442       SmallVector<uint32_t, 8> Disp;
1443       Disp.reserve(*NumOfCtlAnchors);
1444       for (uint32_t I = 0; I < NumOfCtlAnchors && Cur; ++I)
1445         Disp.push_back(DE.getU32(Cur));
1446       if (Cur)
1447         ControlledStorageInfoDisp = std::move(Disp);
1448     }
1449   }
1450 
1451   if (Cur && isFuncNamePresent()) {
1452     uint16_t FunctionNameLen = DE.getU16(Cur);
1453     if (Cur)
1454       FunctionName = DE.getBytes(Cur, FunctionNameLen);
1455   }
1456 
1457   if (Cur && isAllocaUsed())
1458     AllocaRegister = DE.getU8(Cur);
1459 
1460   unsigned VectorParmsNum = 0;
1461   if (Cur && hasVectorInfo()) {
1462     StringRef VectorExtRef = DE.getBytes(Cur, 6);
1463     if (Cur) {
1464       Expected<TBVectorExt> TBVecExtOrErr = TBVectorExt::create(VectorExtRef);
1465       if (!TBVecExtOrErr) {
1466         Err = TBVecExtOrErr.takeError();
1467         return;
1468       }
1469       VecExt = TBVecExtOrErr.get();
1470       VectorParmsNum = VecExt->getNumberOfVectorParms();
1471     }
1472   }
1473 
1474   // As long as there is no fixed-point or floating-point parameter, this
1475   // field remains not present even when hasVectorInfo gives true and
1476   // indicates the presence of vector parameters.
1477   if (Cur && (FixedParmsNum + FloatingParmsNum) > 0) {
1478     Expected<SmallString<32>> ParmsTypeOrError =
1479         hasVectorInfo()
1480             ? parseParmsTypeWithVecInfo(ParamsTypeValue, FixedParmsNum,
1481                                         FloatingParmsNum, VectorParmsNum)
1482             : parseParmsType(ParamsTypeValue, FixedParmsNum, FloatingParmsNum);
1483 
1484     if (!ParmsTypeOrError) {
1485       Err = ParmsTypeOrError.takeError();
1486       return;
1487     }
1488     ParmsType = ParmsTypeOrError.get();
1489   }
1490 
1491   if (Cur && hasExtensionTable())
1492     ExtensionTable = DE.getU8(Cur);
1493 
1494   if (!Cur)
1495     Err = Cur.takeError();
1496 
1497   Size = Cur.tell();
1498 }
1499 
1500 #define GETBITWITHMASK(P, X)                                                   \
1501   (support::endian::read32be(TBPtr + (P)) & (TracebackTable::X))
1502 #define GETBITWITHMASKSHIFT(P, X, S)                                           \
1503   ((support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) >>           \
1504    (TracebackTable::S))
1505 
1506 uint8_t XCOFFTracebackTable::getVersion() const {
1507   return GETBITWITHMASKSHIFT(0, VersionMask, VersionShift);
1508 }
1509 
1510 uint8_t XCOFFTracebackTable::getLanguageID() const {
1511   return GETBITWITHMASKSHIFT(0, LanguageIdMask, LanguageIdShift);
1512 }
1513 
1514 bool XCOFFTracebackTable::isGlobalLinkage() const {
1515   return GETBITWITHMASK(0, IsGlobaLinkageMask);
1516 }
1517 
1518 bool XCOFFTracebackTable::isOutOfLineEpilogOrPrologue() const {
1519   return GETBITWITHMASK(0, IsOutOfLineEpilogOrPrologueMask);
1520 }
1521 
1522 bool XCOFFTracebackTable::hasTraceBackTableOffset() const {
1523   return GETBITWITHMASK(0, HasTraceBackTableOffsetMask);
1524 }
1525 
1526 bool XCOFFTracebackTable::isInternalProcedure() const {
1527   return GETBITWITHMASK(0, IsInternalProcedureMask);
1528 }
1529 
1530 bool XCOFFTracebackTable::hasControlledStorage() const {
1531   return GETBITWITHMASK(0, HasControlledStorageMask);
1532 }
1533 
1534 bool XCOFFTracebackTable::isTOCless() const {
1535   return GETBITWITHMASK(0, IsTOClessMask);
1536 }
1537 
1538 bool XCOFFTracebackTable::isFloatingPointPresent() const {
1539   return GETBITWITHMASK(0, IsFloatingPointPresentMask);
1540 }
1541 
1542 bool XCOFFTracebackTable::isFloatingPointOperationLogOrAbortEnabled() const {
1543   return GETBITWITHMASK(0, IsFloatingPointOperationLogOrAbortEnabledMask);
1544 }
1545 
1546 bool XCOFFTracebackTable::isInterruptHandler() const {
1547   return GETBITWITHMASK(0, IsInterruptHandlerMask);
1548 }
1549 
1550 bool XCOFFTracebackTable::isFuncNamePresent() const {
1551   return GETBITWITHMASK(0, IsFunctionNamePresentMask);
1552 }
1553 
1554 bool XCOFFTracebackTable::isAllocaUsed() const {
1555   return GETBITWITHMASK(0, IsAllocaUsedMask);
1556 }
1557 
1558 uint8_t XCOFFTracebackTable::getOnConditionDirective() const {
1559   return GETBITWITHMASKSHIFT(0, OnConditionDirectiveMask,
1560                              OnConditionDirectiveShift);
1561 }
1562 
1563 bool XCOFFTracebackTable::isCRSaved() const {
1564   return GETBITWITHMASK(0, IsCRSavedMask);
1565 }
1566 
1567 bool XCOFFTracebackTable::isLRSaved() const {
1568   return GETBITWITHMASK(0, IsLRSavedMask);
1569 }
1570 
1571 bool XCOFFTracebackTable::isBackChainStored() const {
1572   return GETBITWITHMASK(4, IsBackChainStoredMask);
1573 }
1574 
1575 bool XCOFFTracebackTable::isFixup() const {
1576   return GETBITWITHMASK(4, IsFixupMask);
1577 }
1578 
1579 uint8_t XCOFFTracebackTable::getNumOfFPRsSaved() const {
1580   return GETBITWITHMASKSHIFT(4, FPRSavedMask, FPRSavedShift);
1581 }
1582 
1583 bool XCOFFTracebackTable::hasExtensionTable() const {
1584   return GETBITWITHMASK(4, HasExtensionTableMask);
1585 }
1586 
1587 bool XCOFFTracebackTable::hasVectorInfo() const {
1588   return GETBITWITHMASK(4, HasVectorInfoMask);
1589 }
1590 
1591 uint8_t XCOFFTracebackTable::getNumOfGPRsSaved() const {
1592   return GETBITWITHMASKSHIFT(4, GPRSavedMask, GPRSavedShift);
1593 }
1594 
1595 uint8_t XCOFFTracebackTable::getNumberOfFixedParms() const {
1596   return GETBITWITHMASKSHIFT(4, NumberOfFixedParmsMask,
1597                              NumberOfFixedParmsShift);
1598 }
1599 
1600 uint8_t XCOFFTracebackTable::getNumberOfFPParms() const {
1601   return GETBITWITHMASKSHIFT(4, NumberOfFloatingPointParmsMask,
1602                              NumberOfFloatingPointParmsShift);
1603 }
1604 
1605 bool XCOFFTracebackTable::hasParmsOnStack() const {
1606   return GETBITWITHMASK(4, HasParmsOnStackMask);
1607 }
1608 
1609 #undef GETBITWITHMASK
1610 #undef GETBITWITHMASKSHIFT
1611 } // namespace object
1612 } // namespace llvm
1613