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