Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include/llvm/Object/XCOFFObjectFile.h
Warning:line 723, column 50
Dereference of null pointer

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-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.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-15~++20220420111733+e13d2efed663/llvm/lib/Object -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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-15/lib/clang/15.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-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/lib/Object/XCOFFObjectFile.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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);
1
Calling 'XCOFFSymbolRef::getNumberOfAuxEntries'
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();
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 // There is no visibility in old 32 bit XCOFF object file interpret.
619 if (is64Bit() || (auxiliaryHeader32() && (auxiliaryHeader32()->getVersion() ==
620 NEW_XCOFF_INTERPRET))) {
621 uint16_t SymType = XCOFFSym.getSymbolType();
622 if ((SymType & VISIBILITY_MASK) == SYM_V_HIDDEN)
623 Result |= SymbolRef::SF_Hidden;
624
625 if ((SymType & VISIBILITY_MASK) == SYM_V_EXPORTED)
626 Result |= SymbolRef::SF_Exported;
627 }
628 return Result;
629}
630
631basic_symbol_iterator XCOFFObjectFile::symbol_begin() const {
632 DataRefImpl SymDRI;
633 SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr);
634 return basic_symbol_iterator(SymbolRef(SymDRI, this));
635}
636
637basic_symbol_iterator XCOFFObjectFile::symbol_end() const {
638 DataRefImpl SymDRI;
639 const uint32_t NumberOfSymbolTableEntries = getNumberOfSymbolTableEntries();
640 SymDRI.p = getSymbolEntryAddressByIndex(NumberOfSymbolTableEntries);
641 return basic_symbol_iterator(SymbolRef(SymDRI, this));
642}
643
644section_iterator XCOFFObjectFile::section_begin() const {
645 DataRefImpl DRI;
646 DRI.p = getSectionHeaderTableAddress();
647 return section_iterator(SectionRef(DRI, this));
648}
649
650section_iterator XCOFFObjectFile::section_end() const {
651 DataRefImpl DRI;
652 DRI.p = getWithOffset(getSectionHeaderTableAddress(),
653 getNumberOfSections() * getSectionHeaderSize());
654 return section_iterator(SectionRef(DRI, this));
655}
656
657uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; }
658
659StringRef XCOFFObjectFile::getFileFormatName() const {
660 return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000";
661}
662
663Triple::ArchType XCOFFObjectFile::getArch() const {
664 return is64Bit() ? Triple::ppc64 : Triple::ppc;
665}
666
667SubtargetFeatures XCOFFObjectFile::getFeatures() const {
668 return SubtargetFeatures();
669}
670
671bool XCOFFObjectFile::isRelocatableObject() const {
672 if (is64Bit())
673 return !(fileHeader64()->Flags & NoRelMask);
674 return !(fileHeader32()->Flags & NoRelMask);
675}
676
677Expected<uint64_t> XCOFFObjectFile::getStartAddress() const {
678 // TODO FIXME Should get from auxiliary_header->o_entry when support for the
679 // auxiliary_header is added.
680 return 0;
681}
682
683StringRef XCOFFObjectFile::mapDebugSectionName(StringRef Name) const {
684 return StringSwitch<StringRef>(Name)
685 .Case("dwinfo", "debug_info")
686 .Case("dwline", "debug_line")
687 .Case("dwpbnms", "debug_pubnames")
688 .Case("dwpbtyp", "debug_pubtypes")
689 .Case("dwarnge", "debug_aranges")
690 .Case("dwabrev", "debug_abbrev")
691 .Case("dwstr", "debug_str")
692 .Case("dwrnges", "debug_ranges")
693 .Case("dwloc", "debug_loc")
694 .Case("dwframe", "debug_frame")
695 .Case("dwmac", "debug_macinfo")
696 .Default(Name);
697}
698
699size_t XCOFFObjectFile::getFileHeaderSize() const {
700 return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32);
701}
702
703size_t XCOFFObjectFile::getSectionHeaderSize() const {
704 return is64Bit() ? sizeof(XCOFFSectionHeader64) :
705 sizeof(XCOFFSectionHeader32);
706}
707
708bool XCOFFObjectFile::is64Bit() const {
709 return Binary::ID_XCOFF64 == getType();
710}
711
712Expected<StringRef> XCOFFObjectFile::getRawData(const char *Start,
713 uint64_t Size,
714 StringRef Name) const {
715 uintptr_t StartPtr = reinterpret_cast<uintptr_t>(Start);
716 // TODO: this path is untested.
717 if (Error E = Binary::checkOffset(Data, StartPtr, Size))
718 return createError(toString(std::move(E)) + ": " + Name.data() +
719 " data with offset 0x" + Twine::utohexstr(StartPtr) +
720 " and size 0x" + Twine::utohexstr(Size) +
721 " goes past the end of the file");
722 return StringRef(Start, Size);
723}
724
725uint16_t XCOFFObjectFile::getMagic() const {
726 return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic;
727}
728
729Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const {
730 if (Num <= 0 || Num > getNumberOfSections())
731 return createStringError(object_error::invalid_section_index,
732 "the section index (" + Twine(Num) +
733 ") is invalid");
734
735 DataRefImpl DRI;
736 DRI.p = getWithOffset(getSectionHeaderTableAddress(),
737 getSectionHeaderSize() * (Num - 1));
738 return DRI;
739}
740
741Expected<StringRef>
742XCOFFObjectFile::getSymbolSectionName(XCOFFSymbolRef SymEntPtr) const {
743 const int16_t SectionNum = SymEntPtr.getSectionNumber();
744
745 switch (SectionNum) {
746 case XCOFF::N_DEBUG:
747 return "N_DEBUG";
748 case XCOFF::N_ABS:
749 return "N_ABS";
750 case XCOFF::N_UNDEF:
751 return "N_UNDEF";
752 default:
753 Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum);
754 if (SecRef)
755 return generateXCOFFFixedNameStringRef(
756 getSectionNameInternal(SecRef.get()));
757 return SecRef.takeError();
758 }
759}
760
761unsigned XCOFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
762 XCOFFSymbolRef XCOFFSymRef(Sym.getRawDataRefImpl(), this);
763 return XCOFFSymRef.getSectionNumber();
764}
765
766bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) {
767 return (SectionNumber <= 0 && SectionNumber >= -2);
768}
769
770uint16_t XCOFFObjectFile::getNumberOfSections() const {
771 return is64Bit() ? fileHeader64()->NumberOfSections
772 : fileHeader32()->NumberOfSections;
773}
774
775int32_t XCOFFObjectFile::getTimeStamp() const {
776 return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp;
777}
778
779uint16_t XCOFFObjectFile::getOptionalHeaderSize() const {
780 return is64Bit() ? fileHeader64()->AuxHeaderSize
781 : fileHeader32()->AuxHeaderSize;
782}
783
784uint32_t XCOFFObjectFile::getSymbolTableOffset32() const {
785 return fileHeader32()->SymbolTableOffset;
786}
787
788int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const {
789 // As far as symbol table size is concerned, if this field is negative it is
790 // to be treated as a 0. However since this field is also used for printing we
791 // don't want to truncate any negative values.
792 return fileHeader32()->NumberOfSymTableEntries;
793}
794
795uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const {
796 return (fileHeader32()->NumberOfSymTableEntries >= 0
797 ? fileHeader32()->NumberOfSymTableEntries
798 : 0);
799}
800
801uint64_t XCOFFObjectFile::getSymbolTableOffset64() const {
802 return fileHeader64()->SymbolTableOffset;
803}
804
805uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const {
806 return fileHeader64()->NumberOfSymTableEntries;
807}
808
809uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries() const {
810 return is64Bit() ? getNumberOfSymbolTableEntries64()
811 : getLogicalNumberOfSymbolTableEntries32();
812}
813
814uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const {
815 const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
816 return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr),
817 XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries);
818}
819
820void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const {
821 if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr))
822 report_fatal_error("Symbol table entry is outside of symbol table.");
823
824 if (SymbolEntPtr >= getEndOfSymbolTableAddress())
825 report_fatal_error("Symbol table entry is outside of symbol table.");
826
827 ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) -
828 reinterpret_cast<const char *>(SymbolTblPtr);
829
830 if (Offset % XCOFF::SymbolTableEntrySize != 0)
831 report_fatal_error(
832 "Symbol table entry position is not valid inside of symbol table.");
833}
834
835uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const {
836 return (reinterpret_cast<const char *>(SymbolEntPtr) -
837 reinterpret_cast<const char *>(SymbolTblPtr)) /
838 XCOFF::SymbolTableEntrySize;
839}
840
841uint64_t XCOFFObjectFile::getSymbolSize(DataRefImpl Symb) const {
842 uint64_t Result = 0;
843 XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
844 if (XCOFFSym.isCsectSymbol()) {
845 Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
846 XCOFFSym.getXCOFFCsectAuxRef();
847 if (!CsectAuxRefOrError)
848 // TODO: report the error up the stack.
849 consumeError(CsectAuxRefOrError.takeError());
850 else {
851 XCOFFCsectAuxRef CsectAuxRef = CsectAuxRefOrError.get();
852 uint8_t SymType = CsectAuxRef.getSymbolType();
853 if (SymType == XCOFF::XTY_SD || SymType == XCOFF::XTY_CM)
854 Result = CsectAuxRef.getSectionOrLength();
855 }
856 }
857 return Result;
858}
859
860uintptr_t XCOFFObjectFile::getSymbolEntryAddressByIndex(uint32_t Index) const {
861 return getAdvancedSymbolEntryAddress(
862 reinterpret_cast<uintptr_t>(getPointerToSymbolTable()), Index);
863}
864
865Expected<StringRef>
866XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const {
867 const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
868
869 if (Index >= NumberOfSymTableEntries)
870 return createError("symbol index " + Twine(Index) +
871 " exceeds symbol count " +
872 Twine(NumberOfSymTableEntries));
873
874 DataRefImpl SymDRI;
875 SymDRI.p = getSymbolEntryAddressByIndex(Index);
876 return getSymbolName(SymDRI);
877}
878
879uint16_t XCOFFObjectFile::getFlags() const {
880 return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags;
881}
882
883const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const {
884 return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name;
885}
886
887uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const {
888 return reinterpret_cast<uintptr_t>(SectionHeaderTable);
889}
890
891int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const {
892 return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags;
893}
894
895XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object)
896 : ObjectFile(Type, Object) {
897 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", 897, __extension__ __PRETTY_FUNCTION__
))
;
898}
899
900ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const {
901 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", 901, __extension__ __PRETTY_FUNCTION__
))
;
902 const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64();
903 return ArrayRef<XCOFFSectionHeader64>(TablePtr,
904 TablePtr + getNumberOfSections());
905}
906
907ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const {
908 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", 908, __extension__ __PRETTY_FUNCTION__
))
;
909 const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32();
910 return ArrayRef<XCOFFSectionHeader32>(TablePtr,
911 TablePtr + getNumberOfSections());
912}
913
914// In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO
915// section header contains the actual count of relocation entries in the s_paddr
916// field. STYP_OVRFLO headers contain the section index of their corresponding
917// sections as their raw "NumberOfRelocations" field value.
918template <typename T>
919Expected<uint32_t> XCOFFObjectFile::getNumberOfRelocationEntries(
920 const XCOFFSectionHeader<T> &Sec) const {
921 const T &Section = static_cast<const T &>(Sec);
922 if (is64Bit())
923 return Section.NumberOfRelocations;
924
925 uint16_t SectionIndex = &Section - sectionHeaderTable<T>() + 1;
926 if (Section.NumberOfRelocations < XCOFF::RelocOverflow)
927 return Section.NumberOfRelocations;
928 for (const auto &Sec : sections32()) {
929 if (Sec.Flags == XCOFF::STYP_OVRFLO &&
930 Sec.NumberOfRelocations == SectionIndex)
931 return Sec.PhysicalAddress;
932 }
933 return errorCodeToError(object_error::parse_failed);
934}
935
936template <typename Shdr, typename Reloc>
937Expected<ArrayRef<Reloc>> XCOFFObjectFile::relocations(const Shdr &Sec) const {
938 uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader),
939 Sec.FileOffsetToRelocationInfo);
940 auto NumRelocEntriesOrErr = getNumberOfRelocationEntries(Sec);
941 if (Error E = NumRelocEntriesOrErr.takeError())
942 return std::move(E);
943
944 uint32_t NumRelocEntries = NumRelocEntriesOrErr.get();
945 static_assert((sizeof(Reloc) == XCOFF::RelocationSerializationSize64 ||
946 sizeof(Reloc) == XCOFF::RelocationSerializationSize32),
947 "Relocation structure is incorrect");
948 auto RelocationOrErr =
949 getObject<Reloc>(Data, reinterpret_cast<void *>(RelocAddr),
950 NumRelocEntries * sizeof(Reloc));
951 if (!RelocationOrErr)
952 return createError(
953 toString(RelocationOrErr.takeError()) + ": relocations with offset 0x" +
954 Twine::utohexstr(Sec.FileOffsetToRelocationInfo) + " and size 0x" +
955 Twine::utohexstr(NumRelocEntries * sizeof(Reloc)) +
956 " go past the end of the file");
957
958 const Reloc *StartReloc = RelocationOrErr.get();
959
960 return ArrayRef<Reloc>(StartReloc, StartReloc + NumRelocEntries);
961}
962
963Expected<XCOFFStringTable>
964XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) {
965 // If there is a string table, then the buffer must contain at least 4 bytes
966 // for the string table's size. Not having a string table is not an error.
967 if (Error E = Binary::checkOffset(
968 Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4)) {
969 consumeError(std::move(E));
970 return XCOFFStringTable{0, nullptr};
971 }
972
973 // Read the size out of the buffer.
974 uint32_t Size = support::endian::read32be(Obj->base() + Offset);
975
976 // If the size is less then 4, then the string table is just a size and no
977 // string data.
978 if (Size <= 4)
979 return XCOFFStringTable{4, nullptr};
980
981 auto StringTableOrErr =
982 getObject<char>(Obj->Data, Obj->base() + Offset, Size);
983 if (!StringTableOrErr)
984 return createError(toString(StringTableOrErr.takeError()) +
985 ": string table with offset 0x" +
986 Twine::utohexstr(Offset) + " and size 0x" +
987 Twine::utohexstr(Size) +
988 " goes past the end of the file");
989
990 const char *StringTablePtr = StringTableOrErr.get();
991 if (StringTablePtr[Size - 1] != '\0')
992 return errorCodeToError(object_error::string_table_non_null_end);
993
994 return XCOFFStringTable{Size, StringTablePtr};
995}
996
997// This function returns the import file table. Each entry in the import file
998// table consists of: "path_name\0base_name\0archive_member_name\0".
999Expected<StringRef> XCOFFObjectFile::getImportFileTable() const {
1000 Expected<uintptr_t> LoaderSectionAddrOrError = getLoaderSectionAddress();
1001 if (!LoaderSectionAddrOrError)
1002 return LoaderSectionAddrOrError.takeError();
1003
1004 uintptr_t LoaderSectionAddr = LoaderSectionAddrOrError.get();
1005 if (!LoaderSectionAddr)
1006 return StringRef();
1007
1008 uint64_t OffsetToImportFileTable = 0;
1009 uint64_t LengthOfImportFileTable = 0;
1010 if (is64Bit()) {
1011 const LoaderSectionHeader64 *LoaderSec64 =
1012 viewAs<LoaderSectionHeader64>(LoaderSectionAddr);
1013 OffsetToImportFileTable = LoaderSec64->OffsetToImpid;
1014 LengthOfImportFileTable = LoaderSec64->LengthOfImpidStrTbl;
1015 } else {
1016 const LoaderSectionHeader32 *LoaderSec32 =
1017 viewAs<LoaderSectionHeader32>(LoaderSectionAddr);
1018 OffsetToImportFileTable = LoaderSec32->OffsetToImpid;
1019 LengthOfImportFileTable = LoaderSec32->LengthOfImpidStrTbl;
1020 }
1021
1022 auto ImportTableOrErr = getObject<char>(
1023 Data,
1024 reinterpret_cast<void *>(LoaderSectionAddr + OffsetToImportFileTable),
1025 LengthOfImportFileTable);
1026 if (!ImportTableOrErr)
1027 return createError(
1028 toString(ImportTableOrErr.takeError()) +
1029 ": import file table with offset 0x" +
1030 Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
1031 " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
1032 " goes past the end of the file");
1033
1034 const char *ImportTablePtr = ImportTableOrErr.get();
1035 if (ImportTablePtr[LengthOfImportFileTable - 1] != '\0')
1036 return createError(
1037 ": import file name table with offset 0x" +
1038 Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
1039 " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
1040 " must end with a null terminator");
1041
1042 return StringRef(ImportTablePtr, LengthOfImportFileTable);
1043}
1044
1045Expected<std::unique_ptr<XCOFFObjectFile>>
1046XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) {
1047 // Can't use std::make_unique because of the private constructor.
1048 std::unique_ptr<XCOFFObjectFile> Obj;
1049 Obj.reset(new XCOFFObjectFile(Type, MBR));
1050
1051 uint64_t CurOffset = 0;
1052 const auto *Base = Obj->base();
1053 MemoryBufferRef Data = Obj->Data;
1054
1055 // Parse file header.
1056 auto FileHeaderOrErr =
1057 getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize());
1058 if (Error E = FileHeaderOrErr.takeError())
1059 return std::move(E);
1060 Obj->FileHeader = FileHeaderOrErr.get();
1061
1062 CurOffset += Obj->getFileHeaderSize();
1063
1064 if (Obj->getOptionalHeaderSize()) {
1065 auto AuxiliaryHeaderOrErr =
1066 getObject<void>(Data, Base + CurOffset, Obj->getOptionalHeaderSize());
1067 if (Error E = AuxiliaryHeaderOrErr.takeError())
1068 return std::move(E);
1069 Obj->AuxiliaryHeader = AuxiliaryHeaderOrErr.get();
1070 }
1071
1072 CurOffset += Obj->getOptionalHeaderSize();
1073
1074 // Parse the section header table if it is present.
1075 if (Obj->getNumberOfSections()) {
1076 uint64_t SectionHeadersSize =
1077 Obj->getNumberOfSections() * Obj->getSectionHeaderSize();
1078 auto SecHeadersOrErr =
1079 getObject<void>(Data, Base + CurOffset, SectionHeadersSize);
1080 if (!SecHeadersOrErr)
1081 return createError(toString(SecHeadersOrErr.takeError()) +
1082 ": section headers with offset 0x" +
1083 Twine::utohexstr(CurOffset) + " and size 0x" +
1084 Twine::utohexstr(SectionHeadersSize) +
1085 " go past the end of the file");
1086
1087 Obj->SectionHeaderTable = SecHeadersOrErr.get();
1088 }
1089
1090 const uint32_t NumberOfSymbolTableEntries =
1091 Obj->getNumberOfSymbolTableEntries();
1092
1093 // If there is no symbol table we are done parsing the memory buffer.
1094 if (NumberOfSymbolTableEntries == 0)
1095 return std::move(Obj);
1096
1097 // Parse symbol table.
1098 CurOffset = Obj->is64Bit() ? Obj->getSymbolTableOffset64()
1099 : Obj->getSymbolTableOffset32();
1100 const uint64_t SymbolTableSize =
1101 static_cast<uint64_t>(XCOFF::SymbolTableEntrySize) *
1102 NumberOfSymbolTableEntries;
1103 auto SymTableOrErr =
1104 getObject<void *>(Data, Base + CurOffset, SymbolTableSize);
1105 if (!SymTableOrErr)
1106 return createError(
1107 toString(SymTableOrErr.takeError()) + ": symbol table with offset 0x" +
1108 Twine::utohexstr(CurOffset) + " and size 0x" +
1109 Twine::utohexstr(SymbolTableSize) + " goes past the end of the file");
1110
1111 Obj->SymbolTblPtr = SymTableOrErr.get();
1112 CurOffset += SymbolTableSize;
1113
1114 // Parse String table.
1115 Expected<XCOFFStringTable> StringTableOrErr =
1116 parseStringTable(Obj.get(), CurOffset);
1117 if (Error E = StringTableOrErr.takeError())
1118 return std::move(E);
1119 Obj->StringTable = StringTableOrErr.get();
1120
1121 return std::move(Obj);
1122}
1123
1124Expected<std::unique_ptr<ObjectFile>>
1125ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef,
1126 unsigned FileType) {
1127 return XCOFFObjectFile::create(FileType, MemBufRef);
1128}
1129
1130bool XCOFFSymbolRef::isFunction() const {
1131 if (!isCsectSymbol())
1132 return false;
1133
1134 if (getSymbolType() & FunctionSym)
1135 return true;
1136
1137 Expected<XCOFFCsectAuxRef> ExpCsectAuxEnt = getXCOFFCsectAuxRef();
1138 if (!ExpCsectAuxEnt) {
1139 // If we could not get the CSECT auxiliary entry, then treat this symbol as
1140 // if it isn't a function. Consume the error and return `false` to move on.
1141 consumeError(ExpCsectAuxEnt.takeError());
1142 return false;
1143 }
1144
1145 const XCOFFCsectAuxRef CsectAuxRef = ExpCsectAuxEnt.get();
1146
1147 // A function definition should be a label definition.
1148 // FIXME: This is not necessarily the case when -ffunction-sections is
1149 // enabled.
1150 if (!CsectAuxRef.isLabel())
1151 return false;
1152
1153 if (CsectAuxRef.getStorageMappingClass() != XCOFF::XMC_PR)
1154 return false;
1155
1156 const int16_t SectNum = getSectionNumber();
1157 Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum);
1158 if (!SI) {
1159 // If we could not get the section, then this symbol should not be
1160 // a function. So consume the error and return `false` to move on.
1161 consumeError(SI.takeError());
1162 return false;
1163 }
1164
1165 return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT);
1166}
1167
1168bool XCOFFSymbolRef::isCsectSymbol() const {
1169 XCOFF::StorageClass SC = getStorageClass();
1170 return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT ||
1171 SC == XCOFF::C_HIDEXT);
1172}
1173
1174Expected<XCOFFCsectAuxRef> XCOFFSymbolRef::getXCOFFCsectAuxRef() const {
1175 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", 1176, __extension__ __PRETTY_FUNCTION__
))
1176 "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", 1176, __extension__ __PRETTY_FUNCTION__
))
;
1177
1178 uint8_t NumberOfAuxEntries = getNumberOfAuxEntries();
1179
1180 Expected<StringRef> NameOrErr = getName();
1181 if (auto Err = NameOrErr.takeError())
1182 return std::move(Err);
1183
1184 uint32_t SymbolIdx = OwningObjectPtr->getSymbolIndex(getEntryAddress());
1185 if (!NumberOfAuxEntries) {
1186 return createError("csect symbol \"" + *NameOrErr + "\" with index " +
1187 Twine(SymbolIdx) + " contains no auxiliary entry");
1188 }
1189
1190 if (!OwningObjectPtr->is64Bit()) {
1191 // In XCOFF32, the csect auxilliary entry is always the last auxiliary
1192 // entry for the symbol.
1193 uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
1194 getEntryAddress(), NumberOfAuxEntries);
1195 return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt32>(AuxAddr));
1196 }
1197
1198 // XCOFF64 uses SymbolAuxType to identify the auxiliary entry type.
1199 // We need to iterate through all the auxiliary entries to find it.
1200 for (uint8_t Index = NumberOfAuxEntries; Index > 0; --Index) {
1201 uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
1202 getEntryAddress(), Index);
1203 if (*OwningObjectPtr->getSymbolAuxType(AuxAddr) ==
1204 XCOFF::SymbolAuxType::AUX_CSECT) {
1205#ifndef NDEBUG
1206 OwningObjectPtr->checkSymbolEntryPointer(AuxAddr);
1207#endif
1208 return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt64>(AuxAddr));
1209 }
1210 }
1211
1212 return createError(
1213 "a csect auxiliary entry has not been found for symbol \"" + *NameOrErr +
1214 "\" with index " + Twine(SymbolIdx));
1215}
1216
1217Expected<StringRef> XCOFFSymbolRef::getName() const {
1218 // A storage class value with the high-order bit on indicates that the name is
1219 // a symbolic debugger stabstring.
1220 if (getStorageClass() & 0x80)
1221 return StringRef("Unimplemented Debug Name");
1222
1223 if (Entry32) {
1224 if (Entry32->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
1225 return generateXCOFFFixedNameStringRef(Entry32->SymbolName);
1226
1227 return OwningObjectPtr->getStringTableEntry(Entry32->NameInStrTbl.Offset);
1228 }
1229
1230 return OwningObjectPtr->getStringTableEntry(Entry64->Offset);
1231}
1232
1233// Explictly instantiate template classes.
1234template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
1235template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
1236
1237template struct XCOFFRelocation<llvm::support::ubig32_t>;
1238template struct XCOFFRelocation<llvm::support::ubig64_t>;
1239
1240template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation64>>
1241llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader64,
1242 llvm::object::XCOFFRelocation64>(
1243 llvm::object::XCOFFSectionHeader64 const &) const;
1244template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation32>>
1245llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader32,
1246 llvm::object::XCOFFRelocation32>(
1247 llvm::object::XCOFFSectionHeader32 const &) const;
1248
1249bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes) {
1250 if (Bytes.size() < 4)
1251 return false;
1252
1253 return support::endian::read32be(Bytes.data()) == 0;
1254}
1255
1256#define GETVALUEWITHMASK(X) (Data & (TracebackTable::X))
1257#define GETVALUEWITHMASKSHIFT(X, S) \
1258 ((Data & (TracebackTable::X)) >> (TracebackTable::S))
1259
1260Expected<TBVectorExt> TBVectorExt::create(StringRef TBvectorStrRef) {
1261 Error Err = Error::success();
1262 TBVectorExt TBTVecExt(TBvectorStrRef, Err);
1263 if (Err)
1264 return std::move(Err);
1265 return TBTVecExt;
1266}
1267
1268TBVectorExt::TBVectorExt(StringRef TBvectorStrRef, Error &Err) {
1269 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(TBvectorStrRef.data());
1270 Data = support::endian::read16be(Ptr);
1271 uint32_t VecParmsTypeValue = support::endian::read32be(Ptr + 2);
1272 unsigned ParmsNum =
1273 GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask, NumberOfVectorParmsShift);
1274
1275 ErrorAsOutParameter EAO(&Err);
1276 Expected<SmallString<32>> VecParmsTypeOrError =
1277 parseVectorParmsType(VecParmsTypeValue, ParmsNum);
1278 if (!VecParmsTypeOrError)
1279 Err = VecParmsTypeOrError.takeError();
1280 else
1281 VecParmsInfo = VecParmsTypeOrError.get();
1282}
1283
1284uint8_t TBVectorExt::getNumberOfVRSaved() const {
1285 return GETVALUEWITHMASKSHIFT(NumberOfVRSavedMask, NumberOfVRSavedShift);
1286}
1287
1288bool TBVectorExt::isVRSavedOnStack() const {
1289 return GETVALUEWITHMASK(IsVRSavedOnStackMask);
1290}
1291
1292bool TBVectorExt::hasVarArgs() const {
1293 return GETVALUEWITHMASK(HasVarArgsMask);
1294}
1295
1296uint8_t TBVectorExt::getNumberOfVectorParms() const {
1297 return GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask,
1298 NumberOfVectorParmsShift);
1299}
1300
1301bool TBVectorExt::hasVMXInstruction() const {
1302 return GETVALUEWITHMASK(HasVMXInstructionMask);
1303}
1304#undef GETVALUEWITHMASK
1305#undef GETVALUEWITHMASKSHIFT
1306
1307Expected<XCOFFTracebackTable> XCOFFTracebackTable::create(const uint8_t *Ptr,
1308 uint64_t &Size) {
1309 Error Err = Error::success();
1310 XCOFFTracebackTable TBT(Ptr, Size, Err);
1311 if (Err)
1312 return std::move(Err);
1313 return TBT;
1314}
1315
1316XCOFFTracebackTable::XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size,
1317 Error &Err)
1318 : TBPtr(Ptr) {
1319 ErrorAsOutParameter EAO(&Err);
1320 DataExtractor DE(ArrayRef<uint8_t>(Ptr, Size), /*IsLittleEndian=*/false,
1321 /*AddressSize=*/0);
1322 DataExtractor::Cursor Cur(/*Offset=*/0);
1323
1324 // Skip 8 bytes of mandatory fields.
1325 DE.getU64(Cur);
1326
1327 unsigned FixedParmsNum = getNumberOfFixedParms();
1328 unsigned FloatingParmsNum = getNumberOfFPParms();
1329 uint32_t ParamsTypeValue = 0;
1330
1331 // Begin to parse optional fields.
1332 if (Cur && (FixedParmsNum + FloatingParmsNum) > 0)
1333 ParamsTypeValue = DE.getU32(Cur);
1334
1335 if (Cur && hasTraceBackTableOffset())
1336 TraceBackTableOffset = DE.getU32(Cur);
1337
1338 if (Cur && isInterruptHandler())
1339 HandlerMask = DE.getU32(Cur);
1340
1341 if (Cur && hasControlledStorage()) {
1342 NumOfCtlAnchors = DE.getU32(Cur);
1343 if (Cur && NumOfCtlAnchors) {
1344 SmallVector<uint32_t, 8> Disp;
1345 Disp.reserve(NumOfCtlAnchors.getValue());
1346 for (uint32_t I = 0; I < NumOfCtlAnchors && Cur; ++I)
1347 Disp.push_back(DE.getU32(Cur));
1348 if (Cur)
1349 ControlledStorageInfoDisp = std::move(Disp);
1350 }
1351 }
1352
1353 if (Cur && isFuncNamePresent()) {
1354 uint16_t FunctionNameLen = DE.getU16(Cur);
1355 if (Cur)
1356 FunctionName = DE.getBytes(Cur, FunctionNameLen);
1357 }
1358
1359 if (Cur && isAllocaUsed())
1360 AllocaRegister = DE.getU8(Cur);
1361
1362 unsigned VectorParmsNum = 0;
1363 if (Cur && hasVectorInfo()) {
1364 StringRef VectorExtRef = DE.getBytes(Cur, 6);
1365 if (Cur) {
1366 Expected<TBVectorExt> TBVecExtOrErr = TBVectorExt::create(VectorExtRef);
1367 if (!TBVecExtOrErr) {
1368 Err = TBVecExtOrErr.takeError();
1369 return;
1370 }
1371 VecExt = TBVecExtOrErr.get();
1372 VectorParmsNum = VecExt.getValue().getNumberOfVectorParms();
1373 }
1374 }
1375
1376 // As long as there is no fixed-point or floating-point parameter, this
1377 // field remains not present even when hasVectorInfo gives true and
1378 // indicates the presence of vector parameters.
1379 if (Cur && (FixedParmsNum + FloatingParmsNum) > 0) {
1380 Expected<SmallString<32>> ParmsTypeOrError =
1381 hasVectorInfo()
1382 ? parseParmsTypeWithVecInfo(ParamsTypeValue, FixedParmsNum,
1383 FloatingParmsNum, VectorParmsNum)
1384 : parseParmsType(ParamsTypeValue, FixedParmsNum, FloatingParmsNum);
1385
1386 if (!ParmsTypeOrError) {
1387 Err = ParmsTypeOrError.takeError();
1388 return;
1389 }
1390 ParmsType = ParmsTypeOrError.get();
1391 }
1392
1393 if (Cur && hasExtensionTable())
1394 ExtensionTable = DE.getU8(Cur);
1395
1396 if (!Cur)
1397 Err = Cur.takeError();
1398
1399 Size = Cur.tell();
1400}
1401
1402#define GETBITWITHMASK(P, X) \
1403 (support::endian::read32be(TBPtr + (P)) & (TracebackTable::X))
1404#define GETBITWITHMASKSHIFT(P, X, S) \
1405 ((support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) >> \
1406 (TracebackTable::S))
1407
1408uint8_t XCOFFTracebackTable::getVersion() const {
1409 return GETBITWITHMASKSHIFT(0, VersionMask, VersionShift);
1410}
1411
1412uint8_t XCOFFTracebackTable::getLanguageID() const {
1413 return GETBITWITHMASKSHIFT(0, LanguageIdMask, LanguageIdShift);
1414}
1415
1416bool XCOFFTracebackTable::isGlobalLinkage() const {
1417 return GETBITWITHMASK(0, IsGlobaLinkageMask);
1418}
1419
1420bool XCOFFTracebackTable::isOutOfLineEpilogOrPrologue() const {
1421 return GETBITWITHMASK(0, IsOutOfLineEpilogOrPrologueMask);
1422}
1423
1424bool XCOFFTracebackTable::hasTraceBackTableOffset() const {
1425 return GETBITWITHMASK(0, HasTraceBackTableOffsetMask);
1426}
1427
1428bool XCOFFTracebackTable::isInternalProcedure() const {
1429 return GETBITWITHMASK(0, IsInternalProcedureMask);
1430}
1431
1432bool XCOFFTracebackTable::hasControlledStorage() const {
1433 return GETBITWITHMASK(0, HasControlledStorageMask);
1434}
1435
1436bool XCOFFTracebackTable::isTOCless() const {
1437 return GETBITWITHMASK(0, IsTOClessMask);
1438}
1439
1440bool XCOFFTracebackTable::isFloatingPointPresent() const {
1441 return GETBITWITHMASK(0, IsFloatingPointPresentMask);
1442}
1443
1444bool XCOFFTracebackTable::isFloatingPointOperationLogOrAbortEnabled() const {
1445 return GETBITWITHMASK(0, IsFloatingPointOperationLogOrAbortEnabledMask);
1446}
1447
1448bool XCOFFTracebackTable::isInterruptHandler() const {
1449 return GETBITWITHMASK(0, IsInterruptHandlerMask);
1450}
1451
1452bool XCOFFTracebackTable::isFuncNamePresent() const {
1453 return GETBITWITHMASK(0, IsFunctionNamePresentMask);
1454}
1455
1456bool XCOFFTracebackTable::isAllocaUsed() const {
1457 return GETBITWITHMASK(0, IsAllocaUsedMask);
1458}
1459
1460uint8_t XCOFFTracebackTable::getOnConditionDirective() const {
1461 return GETBITWITHMASKSHIFT(0, OnConditionDirectiveMask,
1462 OnConditionDirectiveShift);
1463}
1464
1465bool XCOFFTracebackTable::isCRSaved() const {
1466 return GETBITWITHMASK(0, IsCRSavedMask);
1467}
1468
1469bool XCOFFTracebackTable::isLRSaved() const {
1470 return GETBITWITHMASK(0, IsLRSavedMask);
1471}
1472
1473bool XCOFFTracebackTable::isBackChainStored() const {
1474 return GETBITWITHMASK(4, IsBackChainStoredMask);
1475}
1476
1477bool XCOFFTracebackTable::isFixup() const {
1478 return GETBITWITHMASK(4, IsFixupMask);
1479}
1480
1481uint8_t XCOFFTracebackTable::getNumOfFPRsSaved() const {
1482 return GETBITWITHMASKSHIFT(4, FPRSavedMask, FPRSavedShift);
1483}
1484
1485bool XCOFFTracebackTable::hasExtensionTable() const {
1486 return GETBITWITHMASK(4, HasExtensionTableMask);
1487}
1488
1489bool XCOFFTracebackTable::hasVectorInfo() const {
1490 return GETBITWITHMASK(4, HasVectorInfoMask);
1491}
1492
1493uint8_t XCOFFTracebackTable::getNumOfGPRsSaved() const {
1494 return GETBITWITHMASKSHIFT(4, GPRSavedMask, GPRSavedShift);
1495}
1496
1497uint8_t XCOFFTracebackTable::getNumberOfFixedParms() const {
1498 return GETBITWITHMASKSHIFT(4, NumberOfFixedParmsMask,
1499 NumberOfFixedParmsShift);
1500}
1501
1502uint8_t XCOFFTracebackTable::getNumberOfFPParms() const {
1503 return GETBITWITHMASKSHIFT(4, NumberOfFloatingPointParmsMask,
1504 NumberOfFloatingPointParmsShift);
1505}
1506
1507bool XCOFFTracebackTable::hasParmsOnStack() const {
1508 return GETBITWITHMASK(4, HasParmsOnStackMask);
1509}
1510
1511#undef GETBITWITHMASK
1512#undef GETBITWITHMASKSHIFT
1513} // namespace object
1514} // namespace llvm

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