Bug Summary

File:llvm/include/llvm/Object/XCOFFObjectFile.h
Warning:line 647, column 45
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name XCOFFObjectFile.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I lib/Object -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Object -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Object/XCOFFObjectFile.cpp

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/lib/Object/XCOFFObjectFile.cpp

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

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include/llvm/Object/XCOFFObjectFile.h

1//===- XCOFFObjectFile.h - XCOFF object file implementation -----*- C++ -*-===//
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 declares the XCOFFObjectFile class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_OBJECT_XCOFFOBJECTFILE_H
14#define LLVM_OBJECT_XCOFFOBJECTFILE_H
15
16#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/BinaryFormat/XCOFF.h"
19#include "llvm/Object/ObjectFile.h"
20#include "llvm/Support/Endian.h"
21#include <limits>
22
23namespace llvm {
24namespace object {
25
26struct XCOFFFileHeader32 {
27 support::ubig16_t Magic;
28 support::ubig16_t NumberOfSections;
29
30 // Unix time value, value of 0 indicates no timestamp.
31 // Negative values are reserved.
32 support::big32_t TimeStamp;
33
34 support::ubig32_t SymbolTableOffset; // File offset to symbol table.
35 support::big32_t NumberOfSymTableEntries;
36 support::ubig16_t AuxHeaderSize;
37 support::ubig16_t Flags;
38};
39
40struct XCOFFFileHeader64 {
41 support::ubig16_t Magic;
42 support::ubig16_t NumberOfSections;
43
44 // Unix time value, value of 0 indicates no timestamp.
45 // Negative values are reserved.
46 support::big32_t TimeStamp;
47
48 support::ubig64_t SymbolTableOffset; // File offset to symbol table.
49 support::ubig16_t AuxHeaderSize;
50 support::ubig16_t Flags;
51 support::ubig32_t NumberOfSymTableEntries;
52};
53
54template <typename T> struct XCOFFAuxiliaryHeader {
55 static constexpr uint8_t AuxiHeaderFlagMask = 0xF0;
56 static constexpr uint8_t AuxiHeaderTDataAlignmentMask = 0x0F;
57
58public:
59 uint8_t getFlag() const {
60 return static_cast<const T *>(this)->FlagAndTDataAlignment &
61 AuxiHeaderFlagMask;
62 }
63 uint8_t getTDataAlignment() const {
64 return static_cast<const T *>(this)->FlagAndTDataAlignment &
65 AuxiHeaderTDataAlignmentMask;
66 }
67};
68
69struct XCOFFAuxiliaryHeader32 : XCOFFAuxiliaryHeader<XCOFFAuxiliaryHeader32> {
70 support::ubig16_t
71 AuxMagic; ///< If the value of the o_vstamp field is greater than 1, the
72 ///< o_mflags field is reserved for future use and it should
73 ///< contain 0. Otherwise, this field is not used.
74 support::ubig16_t
75 Version; ///< The valid values are 1 and 2. When the o_vstamp field is 2
76 ///< in an XCOFF32 file, the new interpretation of the n_type
77 ///< field in the symbol table entry is used.
78 support::ubig32_t TextSize;
79 support::ubig32_t InitDataSize;
80 support::ubig32_t BssDataSize;
81 support::ubig32_t EntryPointAddr;
82 support::ubig32_t TextStartAddr;
83 support::ubig32_t DataStartAddr;
84 support::ubig32_t TOCAnchorAddr;
85 support::ubig16_t SecNumOfEntryPoint;
86 support::ubig16_t SecNumOfText;
87 support::ubig16_t SecNumOfData;
88 support::ubig16_t SecNumOfTOC;
89 support::ubig16_t SecNumOfLoader;
90 support::ubig16_t SecNumOfBSS;
91 support::ubig16_t MaxAlignOfText;
92 support::ubig16_t MaxAlignOfData;
93 support::ubig16_t ModuleType;
94 uint8_t CpuFlag;
95 uint8_t CpuType;
96 support::ubig32_t MaxStackSize; ///< If the value is 0, the system default
97 ///< maximum stack size is used.
98 support::ubig32_t MaxDataSize; ///< If the value is 0, the system default
99 ///< maximum data size is used.
100 support::ubig32_t
101 ReservedForDebugger; ///< This field should contain 0. When a loaded
102 ///< program is being debugged, the memory image of
103 ///< this field may be modified by a debugger to
104 ///< insert a trap instruction.
105 uint8_t TextPageSize; ///< Specifies the size of pages for the exec text. The
106 ///< default value is 0 (system-selected page size).
107 uint8_t DataPageSize; ///< Specifies the size of pages for the exec data. The
108 ///< default value is 0 (system-selected page size).
109 uint8_t StackPageSize; ///< Specifies the size of pages for the stack. The
110 ///< default value is 0 (system-selected page size).
111 uint8_t FlagAndTDataAlignment;
112 support::ubig16_t SecNumOfTData;
113 support::ubig16_t SecNumOfTBSS;
114};
115
116struct XCOFFAuxiliaryHeader64 : XCOFFAuxiliaryHeader<XCOFFAuxiliaryHeader32> {
117 support::ubig16_t AuxMagic;
118 support::ubig16_t Version;
119 support::ubig32_t ReservedForDebugger;
120 support::ubig64_t TextStartAddr;
121 support::ubig64_t DataStartAddr;
122 support::ubig64_t TOCAnchorAddr;
123 support::ubig16_t SecNumOfEntryPoint;
124 support::ubig16_t SecNumOfText;
125 support::ubig16_t SecNumOfData;
126 support::ubig16_t SecNumOfTOC;
127 support::ubig16_t SecNumOfLoader;
128 support::ubig16_t SecNumOfBSS;
129 support::ubig16_t MaxAlignOfText;
130 support::ubig16_t MaxAlignOfData;
131 support::ubig16_t ModuleType;
132 uint8_t CpuFlag;
133 uint8_t CpuType;
134 uint8_t TextPageSize;
135 uint8_t DataPageSize;
136 uint8_t StackPageSize;
137 uint8_t FlagAndTDataAlignment;
138 support::ubig64_t TextSize;
139 support::ubig64_t InitDataSize;
140 support::ubig64_t BssDataSize;
141 support::ubig64_t EntryPointAddr;
142 support::ubig64_t MaxStackSize;
143 support::ubig64_t MaxDataSize;
144 support::ubig16_t SecNumOfTData;
145 support::ubig16_t SecNumOfTBSS;
146 support::ubig16_t XCOFF64Flag;
147};
148
149template <typename T> struct XCOFFSectionHeader {
150 // Least significant 3 bits are reserved.
151 static constexpr unsigned SectionFlagsReservedMask = 0x7;
152
153 // The low order 16 bits of section flags denotes the section type.
154 static constexpr unsigned SectionFlagsTypeMask = 0xffffu;
155
156public:
157 StringRef getName() const;
158 uint16_t getSectionType() const;
159 bool isReservedSectionType() const;
160};
161
162// Explicit extern template declarations.
163struct XCOFFSectionHeader32;
164struct XCOFFSectionHeader64;
165extern template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
166extern template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
167
168struct XCOFFSectionHeader32 : XCOFFSectionHeader<XCOFFSectionHeader32> {
169 char Name[XCOFF::NameSize];
170 support::ubig32_t PhysicalAddress;
171 support::ubig32_t VirtualAddress;
172 support::ubig32_t SectionSize;
173 support::ubig32_t FileOffsetToRawData;
174 support::ubig32_t FileOffsetToRelocationInfo;
175 support::ubig32_t FileOffsetToLineNumberInfo;
176 support::ubig16_t NumberOfRelocations;
177 support::ubig16_t NumberOfLineNumbers;
178 support::big32_t Flags;
179};
180
181struct XCOFFSectionHeader64 : XCOFFSectionHeader<XCOFFSectionHeader64> {
182 char Name[XCOFF::NameSize];
183 support::ubig64_t PhysicalAddress;
184 support::ubig64_t VirtualAddress;
185 support::ubig64_t SectionSize;
186 support::big64_t FileOffsetToRawData;
187 support::big64_t FileOffsetToRelocationInfo;
188 support::big64_t FileOffsetToLineNumberInfo;
189 support::ubig32_t NumberOfRelocations;
190 support::ubig32_t NumberOfLineNumbers;
191 support::big32_t Flags;
192 char Padding[4];
193};
194
195struct LoaderSectionHeader32 {
196 support::ubig32_t Version;
197 support::ubig32_t NumberOfSymTabEnt;
198 support::ubig32_t NumberOfRelTabEnt;
199 support::ubig32_t LengthOfImpidStrTbl;
200 support::ubig32_t NumberOfImpid;
201 support::big32_t OffsetToImpid;
202 support::ubig32_t LengthOfStrTbl;
203 support::big32_t OffsetToStrTbl;
204};
205
206struct LoaderSectionHeader64 {
207 support::ubig32_t Version;
208 support::ubig32_t NumberOfSymTabEnt;
209 support::ubig32_t NumberOfRelTabEnt;
210 support::ubig32_t LengthOfImpidStrTbl;
211 support::ubig32_t NumberOfImpid;
212 support::ubig32_t LengthOfStrTbl;
213 support::big64_t OffsetToImpid;
214 support::big64_t OffsetToStrTbl;
215 support::big64_t OffsetToSymTbl;
216 char Padding[16];
217 support::big32_t OffsetToRelEnt;
218};
219
220struct XCOFFStringTable {
221 uint32_t Size;
222 const char *Data;
223};
224
225struct XCOFFCsectAuxEnt32 {
226 support::ubig32_t SectionOrLength;
227 support::ubig32_t ParameterHashIndex;
228 support::ubig16_t TypeChkSectNum;
229 uint8_t SymbolAlignmentAndType;
230 XCOFF::StorageMappingClass StorageMappingClass;
231 support::ubig32_t StabInfoIndex;
232 support::ubig16_t StabSectNum;
233};
234
235struct XCOFFCsectAuxEnt64 {
236 support::ubig32_t SectionOrLengthLowByte;
237 support::ubig32_t ParameterHashIndex;
238 support::ubig16_t TypeChkSectNum;
239 uint8_t SymbolAlignmentAndType;
240 XCOFF::StorageMappingClass StorageMappingClass;
241 support::ubig32_t SectionOrLengthHighByte;
242 uint8_t Pad;
243 XCOFF::SymbolAuxType AuxType;
244};
245
246class XCOFFCsectAuxRef {
247public:
248 static constexpr uint8_t SymbolTypeMask = 0x07;
249 static constexpr uint8_t SymbolAlignmentMask = 0xF8;
250 static constexpr size_t SymbolAlignmentBitOffset = 3;
251
252 XCOFFCsectAuxRef(const XCOFFCsectAuxEnt32 *Entry32) : Entry32(Entry32) {}
253 XCOFFCsectAuxRef(const XCOFFCsectAuxEnt64 *Entry64) : Entry64(Entry64) {}
254
255 // For getSectionOrLength(),
256 // If the symbol type is XTY_SD or XTY_CM, the csect length.
257 // If the symbol type is XTY_LD, the symbol table
258 // index of the containing csect.
259 // If the symbol type is XTY_ER, 0.
260 uint64_t getSectionOrLength() const {
261 return Entry32 ? getSectionOrLength32() : getSectionOrLength64();
262 }
263
264 uint32_t getSectionOrLength32() const {
265 assert(Entry32 && "32-bit interface called on 64-bit object file.")(static_cast <bool> (Entry32 && "32-bit interface called on 64-bit object file."
) ? void (0) : __assert_fail ("Entry32 && \"32-bit interface called on 64-bit object file.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 265, __extension__
__PRETTY_FUNCTION__))
;
266 return Entry32->SectionOrLength;
267 }
268
269 uint64_t getSectionOrLength64() const {
270 assert(Entry64 && "64-bit interface called on 32-bit object file.")(static_cast <bool> (Entry64 && "64-bit interface called on 32-bit object file."
) ? void (0) : __assert_fail ("Entry64 && \"64-bit interface called on 32-bit object file.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 270, __extension__
__PRETTY_FUNCTION__))
;
271 return (static_cast<uint64_t>(Entry64->SectionOrLengthHighByte) << 32) |
272 Entry64->SectionOrLengthLowByte;
273 }
274
275#define GETVALUE(X) Entry32 ? Entry32->X : Entry64->X
276
277 uint32_t getParameterHashIndex() const {
278 return GETVALUE(ParameterHashIndex);
279 }
280
281 uint16_t getTypeChkSectNum() const { return GETVALUE(TypeChkSectNum); }
282
283 XCOFF::StorageMappingClass getStorageMappingClass() const {
284 return GETVALUE(StorageMappingClass);
285 }
286
287 uintptr_t getEntryAddress() const {
288 return Entry32 ? reinterpret_cast<uintptr_t>(Entry32)
289 : reinterpret_cast<uintptr_t>(Entry64);
290 }
291
292 uint16_t getAlignmentLog2() const {
293 return (getSymbolAlignmentAndType() & SymbolAlignmentMask) >>
294 SymbolAlignmentBitOffset;
295 }
296
297 uint8_t getSymbolType() const {
298 return getSymbolAlignmentAndType() & SymbolTypeMask;
299 }
300
301 bool isLabel() const { return getSymbolType() == XCOFF::XTY_LD; }
302
303 uint32_t getStabInfoIndex32() const {
304 assert(Entry32 && "32-bit interface called on 64-bit object file.")(static_cast <bool> (Entry32 && "32-bit interface called on 64-bit object file."
) ? void (0) : __assert_fail ("Entry32 && \"32-bit interface called on 64-bit object file.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 304, __extension__
__PRETTY_FUNCTION__))
;
305 return Entry32->StabInfoIndex;
306 }
307
308 uint16_t getStabSectNum32() const {
309 assert(Entry32 && "32-bit interface called on 64-bit object file.")(static_cast <bool> (Entry32 && "32-bit interface called on 64-bit object file."
) ? void (0) : __assert_fail ("Entry32 && \"32-bit interface called on 64-bit object file.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 309, __extension__
__PRETTY_FUNCTION__))
;
310 return Entry32->StabSectNum;
311 }
312
313 XCOFF::SymbolAuxType getAuxType64() const {
314 assert(Entry64 && "64-bit interface called on 32-bit object file.")(static_cast <bool> (Entry64 && "64-bit interface called on 32-bit object file."
) ? void (0) : __assert_fail ("Entry64 && \"64-bit interface called on 32-bit object file.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 314, __extension__
__PRETTY_FUNCTION__))
;
315 return Entry64->AuxType;
316 }
317
318private:
319 uint8_t getSymbolAlignmentAndType() const {
320 return GETVALUE(SymbolAlignmentAndType);
321 }
322
323#undef GETVALUE
324
325 const XCOFFCsectAuxEnt32 *Entry32 = nullptr;
326 const XCOFFCsectAuxEnt64 *Entry64 = nullptr;
327};
328
329struct XCOFFFileAuxEnt {
330 typedef struct {
331 support::big32_t Magic; // Zero indicates name in string table.
332 support::ubig32_t Offset;
333 char NamePad[XCOFF::FileNamePadSize];
334 } NameInStrTblType;
335 union {
336 char Name[XCOFF::NameSize + XCOFF::FileNamePadSize];
337 NameInStrTblType NameInStrTbl;
338 };
339 XCOFF::CFileStringType Type;
340 uint8_t ReservedZeros[2];
341 XCOFF::SymbolAuxType AuxType; // 64-bit XCOFF file only.
342};
343
344struct XCOFFSectAuxEntForStat {
345 support::ubig32_t SectionLength;
346 support::ubig16_t NumberOfRelocEnt;
347 support::ubig16_t NumberOfLineNum;
348 uint8_t Pad[10];
349}; // 32-bit XCOFF file only.
350
351template <typename AddressType> struct XCOFFRelocation {
352 // Masks for packing/unpacking the r_rsize field of relocations.
353
354 // The msb is used to indicate if the bits being relocated are signed or
355 // unsigned.
356 static constexpr uint8_t XR_SIGN_INDICATOR_MASK = 0x80;
357
358 // The 2nd msb is used to indicate that the binder has replaced/modified the
359 // original instruction.
360 static constexpr uint8_t XR_FIXUP_INDICATOR_MASK = 0x40;
361
362 // The remaining bits specify the bit length of the relocatable reference
363 // minus one.
364 static constexpr uint8_t XR_BIASED_LENGTH_MASK = 0x3f;
365
366public:
367 AddressType VirtualAddress;
368 support::ubig32_t SymbolIndex;
369
370 // Packed field, see XR_* masks for details of packing.
371 uint8_t Info;
372
373 XCOFF::RelocationType Type;
374
375public:
376 bool isRelocationSigned() const;
377 bool isFixupIndicated() const;
378
379 // Returns the number of bits being relocated.
380 uint8_t getRelocatedLength() const;
381};
382
383extern template struct XCOFFRelocation<llvm::support::ubig32_t>;
384extern template struct XCOFFRelocation<llvm::support::ubig64_t>;
385
386struct XCOFFRelocation32 : XCOFFRelocation<llvm::support::ubig32_t> {};
387struct XCOFFRelocation64 : XCOFFRelocation<llvm::support::ubig64_t> {};
388
389class XCOFFSymbolRef;
390
391class XCOFFObjectFile : public ObjectFile {
392private:
393 const void *FileHeader = nullptr;
394 const void *AuxiliaryHeader = nullptr;
395 const void *SectionHeaderTable = nullptr;
396
397 const void *SymbolTblPtr = nullptr;
398 XCOFFStringTable StringTable = {0, nullptr};
399
400 const XCOFFFileHeader32 *fileHeader32() const;
401 const XCOFFFileHeader64 *fileHeader64() const;
402
403 const XCOFFSectionHeader32 *sectionHeaderTable32() const;
404 const XCOFFSectionHeader64 *sectionHeaderTable64() const;
405 template <typename T> const T *sectionHeaderTable() const;
406
407 size_t getFileHeaderSize() const;
408 size_t getSectionHeaderSize() const;
409
410 const XCOFFSectionHeader32 *toSection32(DataRefImpl Ref) const;
411 const XCOFFSectionHeader64 *toSection64(DataRefImpl Ref) const;
412 uintptr_t getSectionHeaderTableAddress() const;
413 uintptr_t getEndOfSymbolTableAddress() const;
414 Expected<uintptr_t> getLoaderSectionAddress() const;
415
416 // This returns a pointer to the start of the storage for the name field of
417 // the 32-bit or 64-bit SectionHeader struct. This string is *not* necessarily
418 // null-terminated.
419 const char *getSectionNameInternal(DataRefImpl Sec) const;
420
421 static bool isReservedSectionNumber(int16_t SectionNumber);
422
423 // Constructor and "create" factory function. The constructor is only a thin
424 // wrapper around the base constructor. The "create" function fills out the
425 // XCOFF-specific information and performs the error checking along the way.
426 XCOFFObjectFile(unsigned Type, MemoryBufferRef Object);
427 static Expected<std::unique_ptr<XCOFFObjectFile>> create(unsigned Type,
428 MemoryBufferRef MBR);
429
430 // Helper for parsing the StringTable. Returns an 'Error' if parsing failed
431 // and an XCOFFStringTable if parsing succeeded.
432 static Expected<XCOFFStringTable> parseStringTable(const XCOFFObjectFile *Obj,
433 uint64_t Offset);
434
435 // Make a friend so it can call the private 'create' function.
436 friend Expected<std::unique_ptr<ObjectFile>>
437 ObjectFile::createXCOFFObjectFile(MemoryBufferRef Object, unsigned FileType);
438
439 void checkSectionAddress(uintptr_t Addr, uintptr_t TableAddr) const;
440
441public:
442 static constexpr uint64_t InvalidRelocOffset =
443 std::numeric_limits<uint64_t>::max();
444
445 // Interface inherited from base classes.
446 void moveSymbolNext(DataRefImpl &Symb) const override;
447 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
448 basic_symbol_iterator symbol_begin() const override;
449 basic_symbol_iterator symbol_end() const override;
450
451 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
452 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
453 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
454 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
455 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
456 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
457 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
458
459 void moveSectionNext(DataRefImpl &Sec) const override;
460 Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
461 uint64_t getSectionAddress(DataRefImpl Sec) const override;
462 uint64_t getSectionIndex(DataRefImpl Sec) const override;
463 uint64_t getSectionSize(DataRefImpl Sec) const override;
464 Expected<ArrayRef<uint8_t>>
465 getSectionContents(DataRefImpl Sec) const override;
466 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
467 bool isSectionCompressed(DataRefImpl Sec) const override;
468 bool isSectionText(DataRefImpl Sec) const override;
469 bool isSectionData(DataRefImpl Sec) const override;
470 bool isSectionBSS(DataRefImpl Sec) const override;
471 bool isDebugSection(DataRefImpl Sec) const override;
472
473 bool isSectionVirtual(DataRefImpl Sec) const override;
474 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
475 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
476
477 void moveRelocationNext(DataRefImpl &Rel) const override;
478
479 /// \returns the relocation offset with the base address of the containing
480 /// section as zero, or InvalidRelocOffset on errors (such as a relocation
481 /// that does not refer to an address in any section).
482 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
483 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
484 uint64_t getRelocationType(DataRefImpl Rel) const override;
485 void getRelocationTypeName(DataRefImpl Rel,
486 SmallVectorImpl<char> &Result) const override;
487
488 section_iterator section_begin() const override;
489 section_iterator section_end() const override;
490 uint8_t getBytesInAddress() const override;
491 StringRef getFileFormatName() const override;
492 Triple::ArchType getArch() const override;
493 SubtargetFeatures getFeatures() const override;
494 Expected<uint64_t> getStartAddress() const override;
495 StringRef mapDebugSectionName(StringRef Name) const override;
496 bool isRelocatableObject() const override;
497
498 // Below here is the non-inherited interface.
499 bool is64Bit() const;
500
501 const XCOFFAuxiliaryHeader32 *auxiliaryHeader32() const;
502 const XCOFFAuxiliaryHeader64 *auxiliaryHeader64() const;
503
504 const void *getPointerToSymbolTable() const { return SymbolTblPtr; }
505
506 Expected<StringRef> getSymbolSectionName(XCOFFSymbolRef Ref) const;
507 unsigned getSymbolSectionID(SymbolRef Sym) const;
508 XCOFFSymbolRef toSymbolRef(DataRefImpl Ref) const;
509
510 // File header related interfaces.
511 uint16_t getMagic() const;
512 uint16_t getNumberOfSections() const;
513 int32_t getTimeStamp() const;
514
515 // Symbol table offset and entry count are handled differently between
516 // XCOFF32 and XCOFF64.
517 uint32_t getSymbolTableOffset32() const;
518 uint64_t getSymbolTableOffset64() const;
519
520 // Note that this value is signed and might return a negative value. Negative
521 // values are reserved for future use.
522 int32_t getRawNumberOfSymbolTableEntries32() const;
523
524 // The sanitized value appropriate to use as an index into the symbol table.
525 uint32_t getLogicalNumberOfSymbolTableEntries32() const;
526
527 uint32_t getNumberOfSymbolTableEntries64() const;
528
529 // Return getLogicalNumberOfSymbolTableEntries32 or
530 // getNumberOfSymbolTableEntries64 depending on the object mode.
531 uint32_t getNumberOfSymbolTableEntries() const;
532
533 uint32_t getSymbolIndex(uintptr_t SymEntPtr) const;
534 uint64_t getSymbolSize(DataRefImpl Symb) const;
535 uintptr_t getSymbolByIndex(uint32_t Idx) const {
536 return reinterpret_cast<uintptr_t>(SymbolTblPtr) +
537 XCOFF::SymbolTableEntrySize * Idx;
538 }
539 uintptr_t getSymbolEntryAddressByIndex(uint32_t SymbolTableIndex) const;
540 Expected<StringRef> getSymbolNameByIndex(uint32_t SymbolTableIndex) const;
541
542 Expected<StringRef> getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const;
543 uint16_t getOptionalHeaderSize() const;
544 uint16_t getFlags() const;
545
546 // Section header table related interfaces.
547 ArrayRef<XCOFFSectionHeader32> sections32() const;
548 ArrayRef<XCOFFSectionHeader64> sections64() const;
549
550 int32_t getSectionFlags(DataRefImpl Sec) const;
551 Expected<DataRefImpl> getSectionByNum(int16_t Num) const;
552
553 void checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const;
554
555 // Relocation-related interfaces.
556 template <typename T>
557 Expected<uint32_t>
558 getNumberOfRelocationEntries(const XCOFFSectionHeader<T> &Sec) const;
559
560 template <typename Shdr, typename Reloc>
561 Expected<ArrayRef<Reloc>> relocations(const Shdr &Sec) const;
562
563 // Loader section related interfaces.
564 Expected<StringRef> getImportFileTable() const;
565
566 // This function returns string table entry.
567 Expected<StringRef> getStringTableEntry(uint32_t Offset) const;
568
569 // This function returns the string table.
570 StringRef getStringTable() const;
571
572 const XCOFF::SymbolAuxType *getSymbolAuxType(uintptr_t AuxEntryAddress) const;
573
574 static uintptr_t getAdvancedSymbolEntryAddress(uintptr_t CurrentAddress,
575 uint32_t Distance);
576
577 static bool classof(const Binary *B) { return B->isXCOFF(); }
578}; // XCOFFObjectFile
579
580typedef struct {
581 uint8_t LanguageId;
582 uint8_t CpuTypeId;
583} CFileLanguageIdAndTypeIdType;
584
585struct XCOFFSymbolEntry32 {
586 typedef struct {
587 support::big32_t Magic; // Zero indicates name in string table.
588 support::ubig32_t Offset;
589 } NameInStrTblType;
590
591 union {
592 char SymbolName[XCOFF::NameSize];
593 NameInStrTblType NameInStrTbl;
594 };
595
596 support::ubig32_t Value; // Symbol value; storage class-dependent.
597 support::big16_t SectionNumber;
598
599 union {
600 support::ubig16_t SymbolType;
601 CFileLanguageIdAndTypeIdType CFileLanguageIdAndTypeId;
602 };
603
604 XCOFF::StorageClass StorageClass;
605 uint8_t NumberOfAuxEntries;
606};
607
608struct XCOFFSymbolEntry64 {
609 support::ubig64_t Value; // Symbol value; storage class-dependent.
610 support::ubig32_t Offset;
611 support::big16_t SectionNumber;
612
613 union {
614 support::ubig16_t SymbolType;
615 CFileLanguageIdAndTypeIdType CFileLanguageIdAndTypeId;
616 };
617
618 XCOFF::StorageClass StorageClass;
619 uint8_t NumberOfAuxEntries;
620};
621
622class XCOFFSymbolRef {
623public:
624 enum { NAME_IN_STR_TBL_MAGIC = 0x0 };
625
626 XCOFFSymbolRef(DataRefImpl SymEntDataRef,
627 const XCOFFObjectFile *OwningObjectPtr)
628 : OwningObjectPtr(OwningObjectPtr) {
629 assert(OwningObjectPtr && "OwningObjectPtr cannot be nullptr!")(static_cast <bool> (OwningObjectPtr && "OwningObjectPtr cannot be nullptr!"
) ? void (0) : __assert_fail ("OwningObjectPtr && \"OwningObjectPtr cannot be nullptr!\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 629, __extension__
__PRETTY_FUNCTION__))
;
630 assert(SymEntDataRef.p != 0 &&(static_cast <bool> (SymEntDataRef.p != 0 && "Symbol table entry pointer cannot be nullptr!"
) ? void (0) : __assert_fail ("SymEntDataRef.p != 0 && \"Symbol table entry pointer cannot be nullptr!\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 631, __extension__
__PRETTY_FUNCTION__))
631 "Symbol table entry pointer cannot be nullptr!")(static_cast <bool> (SymEntDataRef.p != 0 && "Symbol table entry pointer cannot be nullptr!"
) ? void (0) : __assert_fail ("SymEntDataRef.p != 0 && \"Symbol table entry pointer cannot be nullptr!\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 631, __extension__
__PRETTY_FUNCTION__))
;
632
633 if (OwningObjectPtr->is64Bit())
634 Entry64 = reinterpret_cast<const XCOFFSymbolEntry64 *>(SymEntDataRef.p);
635 else
636 Entry32 = reinterpret_cast<const XCOFFSymbolEntry32 *>(SymEntDataRef.p);
637 }
638
639 uint64_t getValue() const { return Entry32 ? getValue32() : getValue64(); }
640
641 uint32_t getValue32() const { return Entry32->Value; }
642
643 uint64_t getValue64() const { return Entry64->Value; }
644
645#define GETVALUE(X) Entry32 ? Entry32->X : Entry64->X
646
647 int16_t getSectionNumber() const { return GETVALUE(SectionNumber); }
2
Assuming field 'Entry32' is null
3
'?' condition is false
4
Called C++ object pointer is null
648
649 uint16_t getSymbolType() const { return GETVALUE(SymbolType); }
650
651 uint8_t getLanguageIdForCFile() const {
652 assert(getStorageClass() == XCOFF::C_FILE &&(static_cast <bool> (getStorageClass() == XCOFF::C_FILE
&& "This interface is for C_FILE only.") ? void (0) :
__assert_fail ("getStorageClass() == XCOFF::C_FILE && \"This interface is for C_FILE only.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 653, __extension__
__PRETTY_FUNCTION__))
653 "This interface is for C_FILE only.")(static_cast <bool> (getStorageClass() == XCOFF::C_FILE
&& "This interface is for C_FILE only.") ? void (0) :
__assert_fail ("getStorageClass() == XCOFF::C_FILE && \"This interface is for C_FILE only.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 653, __extension__
__PRETTY_FUNCTION__))
;
654 return GETVALUE(CFileLanguageIdAndTypeId.LanguageId);
655 }
656
657 uint8_t getCPUTypeIddForCFile() const {
658 assert(getStorageClass() == XCOFF::C_FILE &&(static_cast <bool> (getStorageClass() == XCOFF::C_FILE
&& "This interface is for C_FILE only.") ? void (0) :
__assert_fail ("getStorageClass() == XCOFF::C_FILE && \"This interface is for C_FILE only.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 659, __extension__
__PRETTY_FUNCTION__))
659 "This interface is for C_FILE only.")(static_cast <bool> (getStorageClass() == XCOFF::C_FILE
&& "This interface is for C_FILE only.") ? void (0) :
__assert_fail ("getStorageClass() == XCOFF::C_FILE && \"This interface is for C_FILE only.\""
, "llvm/include/llvm/Object/XCOFFObjectFile.h", 659, __extension__
__PRETTY_FUNCTION__))
;
660 return GETVALUE(CFileLanguageIdAndTypeId.CpuTypeId);
661 }
662
663 XCOFF::StorageClass getStorageClass() const { return GETVALUE(StorageClass); }
664
665 uint8_t getNumberOfAuxEntries() const { return GETVALUE(NumberOfAuxEntries); }
666
667#undef GETVALUE
668
669 uintptr_t getEntryAddress() const {
670 return Entry32 ? reinterpret_cast<uintptr_t>(Entry32)
671 : reinterpret_cast<uintptr_t>(Entry64);
672 }
673
674 Expected<StringRef> getName() const;
675 bool isFunction() const;
676 bool isCsectSymbol() const;
677 Expected<XCOFFCsectAuxRef> getXCOFFCsectAuxRef() const;
678
679private:
680 const XCOFFObjectFile *OwningObjectPtr;
681 const XCOFFSymbolEntry32 *Entry32 = nullptr;
682 const XCOFFSymbolEntry64 *Entry64 = nullptr;
683};
684
685class TBVectorExt {
686 uint16_t Data;
687 SmallString<32> VecParmsInfo;
688
689 TBVectorExt(StringRef TBvectorStrRef, Error &Err);
690
691public:
692 static Expected<TBVectorExt> create(StringRef TBvectorStrRef);
693 uint8_t getNumberOfVRSaved() const;
694 bool isVRSavedOnStack() const;
695 bool hasVarArgs() const;
696 uint8_t getNumberOfVectorParms() const;
697 bool hasVMXInstruction() const;
698 SmallString<32> getVectorParmsInfo() const { return VecParmsInfo; };
699};
700
701/// This class provides methods to extract traceback table data from a buffer.
702/// The various accessors may reference the buffer provided via the constructor.
703
704class XCOFFTracebackTable {
705 const uint8_t *const TBPtr;
706 Optional<SmallString<32>> ParmsType;
707 Optional<uint32_t> TraceBackTableOffset;
708 Optional<uint32_t> HandlerMask;
709 Optional<uint32_t> NumOfCtlAnchors;
710 Optional<SmallVector<uint32_t, 8>> ControlledStorageInfoDisp;
711 Optional<StringRef> FunctionName;
712 Optional<uint8_t> AllocaRegister;
713 Optional<TBVectorExt> VecExt;
714 Optional<uint8_t> ExtensionTable;
715
716 XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size, Error &Err);
717
718public:
719 /// Parse an XCOFF Traceback Table from \a Ptr with \a Size bytes.
720 /// Returns an XCOFFTracebackTable upon successful parsing, otherwise an
721 /// Error is returned.
722 ///
723 /// \param[in] Ptr
724 /// A pointer that points just past the initial 4 bytes of zeros at the
725 /// beginning of an XCOFF Traceback Table.
726 ///
727 /// \param[in, out] Size
728 /// A pointer that points to the length of the XCOFF Traceback Table.
729 /// If the XCOFF Traceback Table is not parsed successfully or there are
730 /// extra bytes that are not recognized, \a Size will be updated to be the
731 /// size up to the end of the last successfully parsed field of the table.
732 static Expected<XCOFFTracebackTable> create(const uint8_t *Ptr,
733 uint64_t &Size);
734 uint8_t getVersion() const;
735 uint8_t getLanguageID() const;
736
737 bool isGlobalLinkage() const;
738 bool isOutOfLineEpilogOrPrologue() const;
739 bool hasTraceBackTableOffset() const;
740 bool isInternalProcedure() const;
741 bool hasControlledStorage() const;
742 bool isTOCless() const;
743 bool isFloatingPointPresent() const;
744 bool isFloatingPointOperationLogOrAbortEnabled() const;
745
746 bool isInterruptHandler() const;
747 bool isFuncNamePresent() const;
748 bool isAllocaUsed() const;
749 uint8_t getOnConditionDirective() const;
750 bool isCRSaved() const;
751 bool isLRSaved() const;
752
753 bool isBackChainStored() const;
754 bool isFixup() const;
755 uint8_t getNumOfFPRsSaved() const;
756
757 bool hasVectorInfo() const;
758 bool hasExtensionTable() const;
759 uint8_t getNumOfGPRsSaved() const;
760
761 uint8_t getNumberOfFixedParms() const;
762
763 uint8_t getNumberOfFPParms() const;
764 bool hasParmsOnStack() const;
765
766 const Optional<SmallString<32>> &getParmsType() const { return ParmsType; }
767 const Optional<uint32_t> &getTraceBackTableOffset() const {
768 return TraceBackTableOffset;
769 }
770 const Optional<uint32_t> &getHandlerMask() const { return HandlerMask; }
771 const Optional<uint32_t> &getNumOfCtlAnchors() { return NumOfCtlAnchors; }
772 const Optional<SmallVector<uint32_t, 8>> &getControlledStorageInfoDisp() {
773 return ControlledStorageInfoDisp;
774 }
775 const Optional<StringRef> &getFunctionName() const { return FunctionName; }
776 const Optional<uint8_t> &getAllocaRegister() const { return AllocaRegister; }
777 const Optional<TBVectorExt> &getVectorExt() const { return VecExt; }
778 const Optional<uint8_t> &getExtensionTable() const { return ExtensionTable; }
779};
780
781bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes);
782} // namespace object
783} // namespace llvm
784
785#endif // LLVM_OBJECT_XCOFFOBJECTFILE_H