xref: /llvm-project/llvm/lib/Object/XCOFFObjectFile.cpp (revision b91f798fde42668a3a7b361c015deb787a46720d)
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 <cstddef>
15 #include <cstring>
16 
17 namespace llvm {
18 namespace object {
19 
20 enum { FUNCTION_SYM = 0x20, SYM_TYPE_MASK = 0x07, RELOC_OVERFLOW = 65535 };
21 
22 // Checks that [Ptr, Ptr + Size) bytes fall inside the memory buffer
23 // 'M'. Returns a pointer to the underlying object on success.
24 template <typename T>
25 static Expected<const T *> getObject(MemoryBufferRef M, const void *Ptr,
26                                      const uint64_t Size = sizeof(T)) {
27   uintptr_t Addr = uintptr_t(Ptr);
28   if (std::error_code EC = Binary::checkOffset(M, Addr, Size))
29     return errorCodeToError(EC);
30   return reinterpret_cast<const T *>(Addr);
31 }
32 
33 static uintptr_t getWithOffset(uintptr_t Base, ptrdiff_t Offset) {
34   return reinterpret_cast<uintptr_t>(reinterpret_cast<const char *>(Base) +
35                                      Offset);
36 }
37 
38 template <typename T> static const T *viewAs(uintptr_t in) {
39   return reinterpret_cast<const T *>(in);
40 }
41 
42 static StringRef generateXCOFFFixedNameStringRef(const char *Name) {
43   auto NulCharPtr =
44       static_cast<const char *>(memchr(Name, '\0', XCOFF::NameSize));
45   return NulCharPtr ? StringRef(Name, NulCharPtr - Name)
46                     : StringRef(Name, XCOFF::NameSize);
47 }
48 
49 template <typename T> StringRef XCOFFSectionHeader<T>::getName() const {
50   const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
51   return generateXCOFFFixedNameStringRef(DerivedXCOFFSectionHeader.Name);
52 }
53 
54 template <typename T> uint16_t XCOFFSectionHeader<T>::getSectionType() const {
55   const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
56   return DerivedXCOFFSectionHeader.Flags & SectionFlagsTypeMask;
57 }
58 
59 template <typename T>
60 bool XCOFFSectionHeader<T>::isReservedSectionType() const {
61   return getSectionType() & SectionFlagsReservedMask;
62 }
63 
64 bool XCOFFRelocation32::isRelocationSigned() const {
65   return Info & XR_SIGN_INDICATOR_MASK;
66 }
67 
68 bool XCOFFRelocation32::isFixupIndicated() const {
69   return Info & XR_FIXUP_INDICATOR_MASK;
70 }
71 
72 uint8_t XCOFFRelocation32::getRelocatedLength() const {
73   // The relocation encodes the bit length being relocated minus 1. Add back
74   // the 1 to get the actual length being relocated.
75   return (Info & XR_BIASED_LENGTH_MASK) + 1;
76 }
77 
78 void XCOFFObjectFile::checkSectionAddress(uintptr_t Addr,
79                                           uintptr_t TableAddress) const {
80   if (Addr < TableAddress)
81     report_fatal_error("Section header outside of section header table.");
82 
83   uintptr_t Offset = Addr - TableAddress;
84   if (Offset >= getSectionHeaderSize() * getNumberOfSections())
85     report_fatal_error("Section header outside of section header table.");
86 
87   if (Offset % getSectionHeaderSize() != 0)
88     report_fatal_error(
89         "Section header pointer does not point to a valid section header.");
90 }
91 
92 const XCOFFSectionHeader32 *
93 XCOFFObjectFile::toSection32(DataRefImpl Ref) const {
94   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
95 #ifndef NDEBUG
96   checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
97 #endif
98   return viewAs<XCOFFSectionHeader32>(Ref.p);
99 }
100 
101 const XCOFFSectionHeader64 *
102 XCOFFObjectFile::toSection64(DataRefImpl Ref) const {
103   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
104 #ifndef NDEBUG
105   checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
106 #endif
107   return viewAs<XCOFFSectionHeader64>(Ref.p);
108 }
109 
110 const XCOFFSymbolEntry *XCOFFObjectFile::toSymbolEntry(DataRefImpl Ref) const {
111   assert(!is64Bit() && "Symbol table support not implemented for 64-bit.");
112   assert(Ref.p != 0 && "Symbol table pointer can not be nullptr!");
113 #ifndef NDEBUG
114   checkSymbolEntryPointer(Ref.p);
115 #endif
116   auto SymEntPtr = viewAs<XCOFFSymbolEntry>(Ref.p);
117   return SymEntPtr;
118 }
119 
120 const XCOFFFileHeader32 *XCOFFObjectFile::fileHeader32() const {
121   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
122   return static_cast<const XCOFFFileHeader32 *>(FileHeader);
123 }
124 
125 const XCOFFFileHeader64 *XCOFFObjectFile::fileHeader64() const {
126   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
127   return static_cast<const XCOFFFileHeader64 *>(FileHeader);
128 }
129 
130 const XCOFFSectionHeader32 *
131 XCOFFObjectFile::sectionHeaderTable32() const {
132   assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
133   return static_cast<const XCOFFSectionHeader32 *>(SectionHeaderTable);
134 }
135 
136 const XCOFFSectionHeader64 *
137 XCOFFObjectFile::sectionHeaderTable64() const {
138   assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
139   return static_cast<const XCOFFSectionHeader64 *>(SectionHeaderTable);
140 }
141 
142 void XCOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
143   const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb);
144   SymEntPtr += SymEntPtr->NumberOfAuxEntries + 1;
145 #ifndef NDEBUG
146   // This function is used by basic_symbol_iterator, which allows to
147   // point to the end-of-symbol-table address.
148   if (reinterpret_cast<uintptr_t>(SymEntPtr) != getEndOfSymbolTableAddress())
149     checkSymbolEntryPointer(reinterpret_cast<uintptr_t>(SymEntPtr));
150 #endif
151   Symb.p = reinterpret_cast<uintptr_t>(SymEntPtr);
152 }
153 
154 Expected<StringRef>
155 XCOFFObjectFile::getStringTableEntry(uint32_t Offset) const {
156   // The byte offset is relative to the start of the string table.
157   // A byte offset value of 0 is a null or zero-length symbol
158   // name. A byte offset in the range 1 to 3 (inclusive) points into the length
159   // field; as a soft-error recovery mechanism, we treat such cases as having an
160   // offset of 0.
161   if (Offset < 4)
162     return StringRef(nullptr, 0);
163 
164   if (StringTable.Data != nullptr && StringTable.Size > Offset)
165     return (StringTable.Data + Offset);
166 
167   return make_error<GenericBinaryError>("Bad offset for string table entry",
168                                         object_error::parse_failed);
169 }
170 
171 Expected<StringRef>
172 XCOFFObjectFile::getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const {
173   if (CFileEntPtr->NameInStrTbl.Magic !=
174       XCOFFSymbolEntry::NAME_IN_STR_TBL_MAGIC)
175     return generateXCOFFFixedNameStringRef(CFileEntPtr->Name);
176   return getStringTableEntry(CFileEntPtr->NameInStrTbl.Offset);
177 }
178 
179 Expected<StringRef> XCOFFObjectFile::getSymbolName(DataRefImpl Symb) const {
180   const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb);
181 
182   // A storage class value with the high-order bit on indicates that the name is
183   // a symbolic debugger stabstring.
184   if (SymEntPtr->StorageClass & 0x80)
185     return StringRef("Unimplemented Debug Name");
186 
187   if (SymEntPtr->NameInStrTbl.Magic != XCOFFSymbolEntry::NAME_IN_STR_TBL_MAGIC)
188     return generateXCOFFFixedNameStringRef(SymEntPtr->SymbolName);
189 
190   return getStringTableEntry(SymEntPtr->NameInStrTbl.Offset);
191 }
192 
193 Expected<uint64_t> XCOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const {
194   assert(!is64Bit() && "Symbol table support not implemented for 64-bit.");
195   return toSymbolEntry(Symb)->Value;
196 }
197 
198 uint64_t XCOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
199   assert(!is64Bit() && "Symbol table support not implemented for 64-bit.");
200   return toSymbolEntry(Symb)->Value;
201 }
202 
203 uint64_t XCOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
204   uint64_t Result = 0;
205   llvm_unreachable("Not yet implemented!");
206   return Result;
207 }
208 
209 Expected<SymbolRef::Type>
210 XCOFFObjectFile::getSymbolType(DataRefImpl Symb) const {
211   llvm_unreachable("Not yet implemented!");
212   return SymbolRef::ST_Other;
213 }
214 
215 Expected<section_iterator>
216 XCOFFObjectFile::getSymbolSection(DataRefImpl Symb) const {
217   const XCOFFSymbolEntry *SymEntPtr = toSymbolEntry(Symb);
218   int16_t SectNum = SymEntPtr->SectionNumber;
219 
220   if (isReservedSectionNumber(SectNum))
221     return section_end();
222 
223   Expected<DataRefImpl> ExpSec = getSectionByNum(SectNum);
224   if (!ExpSec)
225     return ExpSec.takeError();
226 
227   return section_iterator(SectionRef(ExpSec.get(), this));
228 }
229 
230 void XCOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const {
231   const char *Ptr = reinterpret_cast<const char *>(Sec.p);
232   Sec.p = reinterpret_cast<uintptr_t>(Ptr + getSectionHeaderSize());
233 }
234 
235 Expected<StringRef> XCOFFObjectFile::getSectionName(DataRefImpl Sec) const {
236   return generateXCOFFFixedNameStringRef(getSectionNameInternal(Sec));
237 }
238 
239 uint64_t XCOFFObjectFile::getSectionAddress(DataRefImpl Sec) const {
240   // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
241   // with MSVC.
242   if (is64Bit())
243     return toSection64(Sec)->VirtualAddress;
244 
245   return toSection32(Sec)->VirtualAddress;
246 }
247 
248 uint64_t XCOFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
249   // Section numbers in XCOFF are numbered beginning at 1. A section number of
250   // zero is used to indicate that a symbol is being imported or is undefined.
251   if (is64Bit())
252     return toSection64(Sec) - sectionHeaderTable64() + 1;
253   else
254     return toSection32(Sec) - sectionHeaderTable32() + 1;
255 }
256 
257 uint64_t XCOFFObjectFile::getSectionSize(DataRefImpl Sec) const {
258   // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
259   // with MSVC.
260   if (is64Bit())
261     return toSection64(Sec)->SectionSize;
262 
263   return toSection32(Sec)->SectionSize;
264 }
265 
266 Expected<ArrayRef<uint8_t>>
267 XCOFFObjectFile::getSectionContents(DataRefImpl Sec) const {
268   if (isSectionVirtual(Sec))
269     return ArrayRef<uint8_t>();
270 
271   const uint64_t OffsetToRaw = is64Bit()
272                                    ? toSection64(Sec)->FileOffsetToRawData
273                                    : toSection32(Sec)->FileOffsetToRawData;
274 
275   const uint8_t * ContentStart = base() + OffsetToRaw;
276   uint64_t SectionSize = getSectionSize(Sec);
277   if (checkOffset(Data, uintptr_t(ContentStart), SectionSize))
278     return make_error<BinaryError>();
279 
280   return makeArrayRef(ContentStart,SectionSize);
281 }
282 
283 uint64_t XCOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const {
284   uint64_t Result = 0;
285   llvm_unreachable("Not yet implemented!");
286   return Result;
287 }
288 
289 bool XCOFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
290   bool Result = false;
291   llvm_unreachable("Not yet implemented!");
292   return Result;
293 }
294 
295 bool XCOFFObjectFile::isSectionText(DataRefImpl Sec) const {
296   return getSectionFlags(Sec) & XCOFF::STYP_TEXT;
297 }
298 
299 bool XCOFFObjectFile::isSectionData(DataRefImpl Sec) const {
300   uint32_t Flags = getSectionFlags(Sec);
301   return Flags & (XCOFF::STYP_DATA | XCOFF::STYP_TDATA);
302 }
303 
304 bool XCOFFObjectFile::isSectionBSS(DataRefImpl Sec) const {
305   uint32_t Flags = getSectionFlags(Sec);
306   return Flags & (XCOFF::STYP_BSS | XCOFF::STYP_TBSS);
307 }
308 
309 bool XCOFFObjectFile::isSectionVirtual(DataRefImpl Sec) const {
310   return is64Bit() ? toSection64(Sec)->FileOffsetToRawData == 0
311                    : toSection32(Sec)->FileOffsetToRawData == 0;
312 }
313 
314 relocation_iterator XCOFFObjectFile::section_rel_begin(DataRefImpl Sec) const {
315   llvm_unreachable("Not yet implemented!");
316   return relocation_iterator(RelocationRef());
317 }
318 
319 relocation_iterator XCOFFObjectFile::section_rel_end(DataRefImpl Sec) const {
320   llvm_unreachable("Not yet implemented!");
321   return relocation_iterator(RelocationRef());
322 }
323 
324 void XCOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
325   llvm_unreachable("Not yet implemented!");
326   return;
327 }
328 
329 uint64_t XCOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
330   llvm_unreachable("Not yet implemented!");
331   uint64_t Result = 0;
332   return Result;
333 }
334 
335 symbol_iterator XCOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
336   llvm_unreachable("Not yet implemented!");
337   return symbol_iterator(SymbolRef());
338 }
339 
340 uint64_t XCOFFObjectFile::getRelocationType(DataRefImpl Rel) const {
341   llvm_unreachable("Not yet implemented!");
342   uint64_t Result = 0;
343   return Result;
344 }
345 
346 void XCOFFObjectFile::getRelocationTypeName(
347     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
348   llvm_unreachable("Not yet implemented!");
349   return;
350 }
351 
352 uint32_t XCOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const {
353   uint32_t Result = 0;
354   llvm_unreachable("Not yet implemented!");
355   return Result;
356 }
357 
358 basic_symbol_iterator XCOFFObjectFile::symbol_begin() const {
359   assert(!is64Bit() && "64-bit support not implemented yet.");
360   DataRefImpl SymDRI;
361   SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr);
362   return basic_symbol_iterator(SymbolRef(SymDRI, this));
363 }
364 
365 basic_symbol_iterator XCOFFObjectFile::symbol_end() const {
366   assert(!is64Bit() && "64-bit support not implemented yet.");
367   DataRefImpl SymDRI;
368   SymDRI.p = reinterpret_cast<uintptr_t>(
369       SymbolTblPtr + getLogicalNumberOfSymbolTableEntries32());
370   return basic_symbol_iterator(SymbolRef(SymDRI, this));
371 }
372 
373 section_iterator XCOFFObjectFile::section_begin() const {
374   DataRefImpl DRI;
375   DRI.p = getSectionHeaderTableAddress();
376   return section_iterator(SectionRef(DRI, this));
377 }
378 
379 section_iterator XCOFFObjectFile::section_end() const {
380   DataRefImpl DRI;
381   DRI.p = getWithOffset(getSectionHeaderTableAddress(),
382                         getNumberOfSections() * getSectionHeaderSize());
383   return section_iterator(SectionRef(DRI, this));
384 }
385 
386 uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; }
387 
388 StringRef XCOFFObjectFile::getFileFormatName() const {
389   return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000";
390 }
391 
392 Triple::ArchType XCOFFObjectFile::getArch() const {
393   return is64Bit() ? Triple::ppc64 : Triple::ppc;
394 }
395 
396 SubtargetFeatures XCOFFObjectFile::getFeatures() const {
397   return SubtargetFeatures();
398 }
399 
400 bool XCOFFObjectFile::isRelocatableObject() const {
401   bool Result = false;
402   llvm_unreachable("Not yet implemented!");
403   return Result;
404 }
405 
406 Expected<uint64_t> XCOFFObjectFile::getStartAddress() const {
407   // TODO FIXME Should get from auxiliary_header->o_entry when support for the
408   // auxiliary_header is added.
409   return 0;
410 }
411 
412 size_t XCOFFObjectFile::getFileHeaderSize() const {
413   return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32);
414 }
415 
416 size_t XCOFFObjectFile::getSectionHeaderSize() const {
417   return is64Bit() ? sizeof(XCOFFSectionHeader64) :
418                      sizeof(XCOFFSectionHeader32);
419 }
420 
421 bool XCOFFObjectFile::is64Bit() const {
422   return Binary::ID_XCOFF64 == getType();
423 }
424 
425 uint16_t XCOFFObjectFile::getMagic() const {
426   return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic;
427 }
428 
429 Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const {
430   if (Num <= 0 || Num > getNumberOfSections())
431     return errorCodeToError(object_error::invalid_section_index);
432 
433   DataRefImpl DRI;
434   DRI.p = getWithOffset(getSectionHeaderTableAddress(),
435                         getSectionHeaderSize() * (Num - 1));
436   return DRI;
437 }
438 
439 Expected<StringRef>
440 XCOFFObjectFile::getSymbolSectionName(const XCOFFSymbolEntry *SymEntPtr) const {
441   assert(!is64Bit() && "Symbol table support not implemented for 64-bit.");
442   int16_t SectionNum = SymEntPtr->SectionNumber;
443 
444   switch (SectionNum) {
445   case XCOFF::N_DEBUG:
446     return "N_DEBUG";
447   case XCOFF::N_ABS:
448     return "N_ABS";
449   case XCOFF::N_UNDEF:
450     return "N_UNDEF";
451   default:
452     Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum);
453     if (SecRef)
454       return generateXCOFFFixedNameStringRef(
455           getSectionNameInternal(SecRef.get()));
456     return SecRef.takeError();
457   }
458 }
459 
460 bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) {
461   return (SectionNumber <= 0 && SectionNumber >= -2);
462 }
463 
464 uint16_t XCOFFObjectFile::getNumberOfSections() const {
465   return is64Bit() ? fileHeader64()->NumberOfSections
466                    : fileHeader32()->NumberOfSections;
467 }
468 
469 int32_t XCOFFObjectFile::getTimeStamp() const {
470   return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp;
471 }
472 
473 uint16_t XCOFFObjectFile::getOptionalHeaderSize() const {
474   return is64Bit() ? fileHeader64()->AuxHeaderSize
475                    : fileHeader32()->AuxHeaderSize;
476 }
477 
478 uint32_t XCOFFObjectFile::getSymbolTableOffset32() const {
479   return fileHeader32()->SymbolTableOffset;
480 }
481 
482 int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const {
483   // As far as symbol table size is concerned, if this field is negative it is
484   // to be treated as a 0. However since this field is also used for printing we
485   // don't want to truncate any negative values.
486   return fileHeader32()->NumberOfSymTableEntries;
487 }
488 
489 uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const {
490   return (fileHeader32()->NumberOfSymTableEntries >= 0
491               ? fileHeader32()->NumberOfSymTableEntries
492               : 0);
493 }
494 
495 uint64_t XCOFFObjectFile::getSymbolTableOffset64() const {
496   return fileHeader64()->SymbolTableOffset;
497 }
498 
499 uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const {
500   return fileHeader64()->NumberOfSymTableEntries;
501 }
502 
503 uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const {
504   uint32_t NumberOfSymTableEntries =
505       is64Bit() ? getNumberOfSymbolTableEntries64()
506                 : getLogicalNumberOfSymbolTableEntries32();
507   return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr),
508                        XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries);
509 }
510 
511 void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const {
512   if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr))
513     report_fatal_error("Symbol table entry is outside of symbol table.");
514 
515   if (SymbolEntPtr >= getEndOfSymbolTableAddress())
516     report_fatal_error("Symbol table entry is outside of symbol table.");
517 
518   ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) -
519                      reinterpret_cast<const char *>(SymbolTblPtr);
520 
521   if (Offset % XCOFF::SymbolTableEntrySize != 0)
522     report_fatal_error(
523         "Symbol table entry position is not valid inside of symbol table.");
524 }
525 
526 uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const {
527   return (reinterpret_cast<const char *>(SymbolEntPtr) -
528           reinterpret_cast<const char *>(SymbolTblPtr)) /
529          XCOFF::SymbolTableEntrySize;
530 }
531 
532 Expected<StringRef>
533 XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const {
534   if (is64Bit())
535     report_fatal_error("64-bit symbol table support not implemented yet.");
536 
537   if (Index >= getLogicalNumberOfSymbolTableEntries32())
538     return errorCodeToError(object_error::invalid_symbol_index);
539 
540   DataRefImpl SymDRI;
541   SymDRI.p = reinterpret_cast<uintptr_t>(getPointerToSymbolTable() + Index);
542   return getSymbolName(SymDRI);
543 }
544 
545 uint16_t XCOFFObjectFile::getFlags() const {
546   return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags;
547 }
548 
549 const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const {
550   return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name;
551 }
552 
553 uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const {
554   return reinterpret_cast<uintptr_t>(SectionHeaderTable);
555 }
556 
557 int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const {
558   return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags;
559 }
560 
561 XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object)
562     : ObjectFile(Type, Object) {
563   assert(Type == Binary::ID_XCOFF32 || Type == Binary::ID_XCOFF64);
564 }
565 
566 ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const {
567   assert(is64Bit() && "64-bit interface called for non 64-bit file.");
568   const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64();
569   return ArrayRef<XCOFFSectionHeader64>(TablePtr,
570                                         TablePtr + getNumberOfSections());
571 }
572 
573 ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const {
574   assert(!is64Bit() && "32-bit interface called for non 32-bit file.");
575   const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32();
576   return ArrayRef<XCOFFSectionHeader32>(TablePtr,
577                                         TablePtr + getNumberOfSections());
578 }
579 
580 // In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO
581 // section header contains the actual count of relocation entries in the s_paddr
582 // field. STYP_OVRFLO headers contain the section index of their corresponding
583 // sections as their raw "NumberOfRelocations" field value.
584 Expected<uint32_t> XCOFFObjectFile::getLogicalNumberOfRelocationEntries(
585     const XCOFFSectionHeader32 &Sec) const {
586 
587   uint16_t SectionIndex = &Sec - sectionHeaderTable32() + 1;
588 
589   if (Sec.NumberOfRelocations < RELOC_OVERFLOW)
590     return Sec.NumberOfRelocations;
591   for (const auto &Sec : sections32()) {
592     if (Sec.Flags == XCOFF::STYP_OVRFLO &&
593         Sec.NumberOfRelocations == SectionIndex)
594       return Sec.PhysicalAddress;
595   }
596   return errorCodeToError(object_error::parse_failed);
597 }
598 
599 Expected<ArrayRef<XCOFFRelocation32>>
600 XCOFFObjectFile::relocations(const XCOFFSectionHeader32 &Sec) const {
601   uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader),
602                                       Sec.FileOffsetToRelocationInfo);
603   auto NumRelocEntriesOrErr = getLogicalNumberOfRelocationEntries(Sec);
604   if (Error E = NumRelocEntriesOrErr.takeError())
605     return std::move(E);
606 
607   uint32_t NumRelocEntries = NumRelocEntriesOrErr.get();
608 
609   auto RelocationOrErr =
610       getObject<XCOFFRelocation32>(Data, reinterpret_cast<void *>(RelocAddr),
611                                    NumRelocEntries * sizeof(XCOFFRelocation32));
612   if (Error E = RelocationOrErr.takeError())
613     return std::move(E);
614 
615   const XCOFFRelocation32 *StartReloc = RelocationOrErr.get();
616 
617   return ArrayRef<XCOFFRelocation32>(StartReloc, StartReloc + NumRelocEntries);
618 }
619 
620 Expected<XCOFFStringTable>
621 XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) {
622   // If there is a string table, then the buffer must contain at least 4 bytes
623   // for the string table's size. Not having a string table is not an error.
624   if (auto EC = Binary::checkOffset(
625           Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4))
626     return XCOFFStringTable{0, nullptr};
627 
628   // Read the size out of the buffer.
629   uint32_t Size = support::endian::read32be(Obj->base() + Offset);
630 
631   // If the size is less then 4, then the string table is just a size and no
632   // string data.
633   if (Size <= 4)
634     return XCOFFStringTable{4, nullptr};
635 
636   auto StringTableOrErr =
637       getObject<char>(Obj->Data, Obj->base() + Offset, Size);
638   if (Error E = StringTableOrErr.takeError())
639     return std::move(E);
640 
641   const char *StringTablePtr = StringTableOrErr.get();
642   if (StringTablePtr[Size - 1] != '\0')
643     return errorCodeToError(object_error::string_table_non_null_end);
644 
645   return XCOFFStringTable{Size, StringTablePtr};
646 }
647 
648 Expected<std::unique_ptr<XCOFFObjectFile>>
649 XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) {
650   // Can't use std::make_unique because of the private constructor.
651   std::unique_ptr<XCOFFObjectFile> Obj;
652   Obj.reset(new XCOFFObjectFile(Type, MBR));
653 
654   uint64_t CurOffset = 0;
655   const auto *Base = Obj->base();
656   MemoryBufferRef Data = Obj->Data;
657 
658   // Parse file header.
659   auto FileHeaderOrErr =
660       getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize());
661   if (Error E = FileHeaderOrErr.takeError())
662     return std::move(E);
663   Obj->FileHeader = FileHeaderOrErr.get();
664 
665   CurOffset += Obj->getFileHeaderSize();
666   // TODO FIXME we don't have support for an optional header yet, so just skip
667   // past it.
668   CurOffset += Obj->getOptionalHeaderSize();
669 
670   // Parse the section header table if it is present.
671   if (Obj->getNumberOfSections()) {
672     auto SecHeadersOrErr = getObject<void>(Data, Base + CurOffset,
673                                            Obj->getNumberOfSections() *
674                                                Obj->getSectionHeaderSize());
675     if (Error E = SecHeadersOrErr.takeError())
676       return std::move(E);
677     Obj->SectionHeaderTable = SecHeadersOrErr.get();
678   }
679 
680   // 64-bit object supports only file header and section headers for now.
681   if (Obj->is64Bit())
682     return std::move(Obj);
683 
684   // If there is no symbol table we are done parsing the memory buffer.
685   if (Obj->getLogicalNumberOfSymbolTableEntries32() == 0)
686     return std::move(Obj);
687 
688   // Parse symbol table.
689   CurOffset = Obj->fileHeader32()->SymbolTableOffset;
690   uint64_t SymbolTableSize = (uint64_t)(sizeof(XCOFFSymbolEntry)) *
691                              Obj->getLogicalNumberOfSymbolTableEntries32();
692   auto SymTableOrErr =
693       getObject<XCOFFSymbolEntry>(Data, Base + CurOffset, SymbolTableSize);
694   if (Error E = SymTableOrErr.takeError())
695     return std::move(E);
696   Obj->SymbolTblPtr = SymTableOrErr.get();
697   CurOffset += SymbolTableSize;
698 
699   // Parse String table.
700   Expected<XCOFFStringTable> StringTableOrErr =
701       parseStringTable(Obj.get(), CurOffset);
702   if (Error E = StringTableOrErr.takeError())
703     return std::move(E);
704   Obj->StringTable = StringTableOrErr.get();
705 
706   return std::move(Obj);
707 }
708 
709 Expected<std::unique_ptr<ObjectFile>>
710 ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef,
711                                   unsigned FileType) {
712   return XCOFFObjectFile::create(FileType, MemBufRef);
713 }
714 
715 XCOFF::StorageClass XCOFFSymbolRef::getStorageClass() const {
716   return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->StorageClass;
717 }
718 
719 uint8_t XCOFFSymbolRef::getNumberOfAuxEntries() const {
720   return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->NumberOfAuxEntries;
721 }
722 
723 const XCOFFCsectAuxEnt32 *XCOFFSymbolRef::getXCOFFCsectAuxEnt32() const {
724   assert(!OwningObjectPtr->is64Bit() &&
725          "32-bit interface called on 64-bit object file.");
726   assert(hasCsectAuxEnt() && "No Csect Auxiliary Entry is found.");
727 
728   // In XCOFF32, the csect auxilliary entry is always the last auxiliary
729   // entry for the symbol.
730   uintptr_t AuxAddr = getWithOffset(
731       SymEntDataRef.p, XCOFF::SymbolTableEntrySize * getNumberOfAuxEntries());
732 
733 #ifndef NDEBUG
734   OwningObjectPtr->checkSymbolEntryPointer(AuxAddr);
735 #endif
736 
737   return reinterpret_cast<const XCOFFCsectAuxEnt32 *>(AuxAddr);
738 }
739 
740 uint16_t XCOFFSymbolRef::getType() const {
741   return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->SymbolType;
742 }
743 
744 int16_t XCOFFSymbolRef::getSectionNumber() const {
745   return OwningObjectPtr->toSymbolEntry(SymEntDataRef)->SectionNumber;
746 }
747 
748 bool XCOFFSymbolRef::hasCsectAuxEnt() const {
749   XCOFF::StorageClass SC = getStorageClass();
750   return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT ||
751           SC == XCOFF::C_HIDEXT);
752 }
753 
754 bool XCOFFSymbolRef::isFunction() const {
755   if (OwningObjectPtr->is64Bit())
756     report_fatal_error("64-bit support is unimplemented yet.");
757 
758   if (getType() & FUNCTION_SYM)
759     return true;
760 
761   if (!hasCsectAuxEnt())
762     return false;
763 
764   const XCOFFCsectAuxEnt32 *CsectAuxEnt = getXCOFFCsectAuxEnt32();
765 
766   // A function definition should be a label definition.
767   if ((CsectAuxEnt->SymbolAlignmentAndType & SYM_TYPE_MASK) != XCOFF::XTY_LD)
768     return false;
769 
770   if (CsectAuxEnt->StorageMappingClass != XCOFF::XMC_PR)
771     return false;
772 
773   int16_t SectNum = getSectionNumber();
774   Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum);
775   if (!SI)
776     return false;
777 
778   return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT);
779 }
780 
781 // Explictly instantiate template classes.
782 template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
783 template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
784 
785 } // namespace object
786 } // namespace llvm
787