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