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