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