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