Bug Summary

File:src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object/XCOFFObjectFile.h
Warning:line 501, column 40
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -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 -mrelocation-model pic -pic-level 1 -fhalf-no-semantic-interposition -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/AMDGPU -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Analysis -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ASMParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/BinaryFormat -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitcode -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Bitstream -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /include/llvm/CodeGen -I /include/llvm/CodeGen/PBQP -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IR -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Coroutines -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData/Coverage -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/CodeView -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/DWARF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/MSF -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/PDB -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Demangle -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/JITLink -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ExecutionEngine/Orc -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenACC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Frontend/OpenMP -I /include/llvm/CodeGen/GlobalISel -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/IRReader -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/Transforms/InstCombine -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/LTO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Linker -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/MC/MCParser -I /include/llvm/CodeGen/MIRParser -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Object -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Option -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Passes -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ProfileData -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Scalar -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/ADT -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Support -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/DebugInfo/Symbolize -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Target -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Utils -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/Vectorize -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include/llvm/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Target/X86 -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include/llvm/Transforms/IPO -I /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libLLVM/../include -I /usr/src/gnu/usr.bin/clang/libLLVM/obj -I /usr/src/gnu/usr.bin/clang/libLLVM/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -D PIC -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libLLVM/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -D_RET_PROTECTOR -ret-protector -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/llvm/lib/Object/XCOFFObjectFile.cpp

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/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
72bool XCOFFRelocation32::isRelocationSigned() const {
73 return Info & XR_SIGN_INDICATOR_MASK;
74}
75
76bool XCOFFRelocation32::isFixupIndicated() const {
77 return Info & XR_FIXUP_INDICATOR_MASK;
78}
79
80uint8_t XCOFFRelocation32::getRelocatedLength() const {
81 // The relocation encodes the bit length being relocated minus 1. Add back
82 // the 1 to get the actual length being relocated.
83 return (Info & XR_BIASED_LENGTH_MASK) + 1;
84}
85
86uintptr_t
87XCOFFObjectFile::getAdvancedSymbolEntryAddress(uintptr_t CurrentAddress,
88 uint32_t Distance) {
89 return getWithOffset(CurrentAddress, Distance * XCOFF::SymbolTableEntrySize);
90}
91
92const XCOFF::SymbolAuxType *
93XCOFFObjectFile::getSymbolAuxType(uintptr_t AuxEntryAddress) const {
94 assert(is64Bit() && "64-bit interface called on a 32-bit object file.")((void)0);
95 return viewAs<XCOFF::SymbolAuxType>(
96 getWithOffset(AuxEntryAddress, SymbolAuxTypeOffset));
97}
98
99void XCOFFObjectFile::checkSectionAddress(uintptr_t Addr,
100 uintptr_t TableAddress) const {
101 if (Addr < TableAddress)
102 report_fatal_error("Section header outside of section header table.");
103
104 uintptr_t Offset = Addr - TableAddress;
105 if (Offset >= getSectionHeaderSize() * getNumberOfSections())
106 report_fatal_error("Section header outside of section header table.");
107
108 if (Offset % getSectionHeaderSize() != 0)
109 report_fatal_error(
110 "Section header pointer does not point to a valid section header.");
111}
112
113const XCOFFSectionHeader32 *
114XCOFFObjectFile::toSection32(DataRefImpl Ref) const {
115 assert(!is64Bit() && "32-bit interface called on 64-bit object file.")((void)0);
116#ifndef NDEBUG1
117 checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
118#endif
119 return viewAs<XCOFFSectionHeader32>(Ref.p);
120}
121
122const XCOFFSectionHeader64 *
123XCOFFObjectFile::toSection64(DataRefImpl Ref) const {
124 assert(is64Bit() && "64-bit interface called on a 32-bit object file.")((void)0);
125#ifndef NDEBUG1
126 checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
127#endif
128 return viewAs<XCOFFSectionHeader64>(Ref.p);
129}
130
131XCOFFSymbolRef XCOFFObjectFile::toSymbolRef(DataRefImpl Ref) const {
132 assert(Ref.p != 0 && "Symbol table pointer can not be nullptr!")((void)0);
133#ifndef NDEBUG1
134 checkSymbolEntryPointer(Ref.p);
135#endif
136 return XCOFFSymbolRef(Ref, this);
2
Calling constructor for 'XCOFFSymbolRef'
5
Returning from constructor for 'XCOFFSymbolRef'
137}
138
139const XCOFFFileHeader32 *XCOFFObjectFile::fileHeader32() const {
140 assert(!is64Bit() && "32-bit interface called on 64-bit object file.")((void)0);
141 return static_cast<const XCOFFFileHeader32 *>(FileHeader);
142}
143
144const XCOFFFileHeader64 *XCOFFObjectFile::fileHeader64() const {
145 assert(is64Bit() && "64-bit interface called on a 32-bit object file.")((void)0);
146 return static_cast<const XCOFFFileHeader64 *>(FileHeader);
147}
148
149const XCOFFSectionHeader32 *
150XCOFFObjectFile::sectionHeaderTable32() const {
151 assert(!is64Bit() && "32-bit interface called on 64-bit object file.")((void)0);
152 return static_cast<const XCOFFSectionHeader32 *>(SectionHeaderTable);
153}
154
155const XCOFFSectionHeader64 *
156XCOFFObjectFile::sectionHeaderTable64() const {
157 assert(is64Bit() && "64-bit interface called on a 32-bit object file.")((void)0);
158 return static_cast<const XCOFFSectionHeader64 *>(SectionHeaderTable);
159}
160
161void XCOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
162 uintptr_t NextSymbolAddr = getAdvancedSymbolEntryAddress(
163 Symb.p, toSymbolRef(Symb).getNumberOfAuxEntries() + 1);
164#ifndef NDEBUG1
165 // This function is used by basic_symbol_iterator, which allows to
166 // point to the end-of-symbol-table address.
167 if (NextSymbolAddr != getEndOfSymbolTableAddress())
168 checkSymbolEntryPointer(NextSymbolAddr);
169#endif
170 Symb.p = NextSymbolAddr;
171}
172
173Expected<StringRef>
174XCOFFObjectFile::getStringTableEntry(uint32_t Offset) const {
175 // The byte offset is relative to the start of the string table.
176 // A byte offset value of 0 is a null or zero-length symbol
177 // name. A byte offset in the range 1 to 3 (inclusive) points into the length
178 // field; as a soft-error recovery mechanism, we treat such cases as having an
179 // offset of 0.
180 if (Offset < 4)
181 return StringRef(nullptr, 0);
182
183 if (StringTable.Data != nullptr && StringTable.Size > Offset)
184 return (StringTable.Data + Offset);
185
186 return make_error<GenericBinaryError>("Bad offset for string table entry",
187 object_error::parse_failed);
188}
189
190StringRef XCOFFObjectFile::getStringTable() const {
191 return StringRef(StringTable.Data, StringTable.Size);
192}
193
194Expected<StringRef>
195XCOFFObjectFile::getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const {
196 if (CFileEntPtr->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
197 return generateXCOFFFixedNameStringRef(CFileEntPtr->Name);
198 return getStringTableEntry(CFileEntPtr->NameInStrTbl.Offset);
199}
200
201Expected<StringRef> XCOFFObjectFile::getSymbolName(DataRefImpl Symb) const {
202 return toSymbolRef(Symb).getName();
203}
204
205Expected<uint64_t> XCOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const {
206 return toSymbolRef(Symb).getValue();
207}
208
209uint64_t XCOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
210 return toSymbolRef(Symb).getValue();
1
Calling 'XCOFFObjectFile::toSymbolRef'
6
Returning from 'XCOFFObjectFile::toSymbolRef'
7
Calling 'XCOFFSymbolRef::getValue'
211}
212
213uint64_t XCOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
214 uint64_t Result = 0;
215 llvm_unreachable("Not yet implemented!")__builtin_unreachable();
216 return Result;
217}
218
219Expected<SymbolRef::Type>
220XCOFFObjectFile::getSymbolType(DataRefImpl Symb) const {
221 // TODO: Return the correct symbol type.
222 return SymbolRef::ST_Other;
223}
224
225Expected<section_iterator>
226XCOFFObjectFile::getSymbolSection(DataRefImpl Symb) const {
227 const int16_t SectNum = toSymbolRef(Symb).getSectionNumber();
228
229 if (isReservedSectionNumber(SectNum))
230 return section_end();
231
232 Expected<DataRefImpl> ExpSec = getSectionByNum(SectNum);
233 if (!ExpSec)
234 return ExpSec.takeError();
235
236 return section_iterator(SectionRef(ExpSec.get(), this));
237}
238
239void XCOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const {
240 const char *Ptr = reinterpret_cast<const char *>(Sec.p);
241 Sec.p = reinterpret_cast<uintptr_t>(Ptr + getSectionHeaderSize());
242}
243
244Expected<StringRef> XCOFFObjectFile::getSectionName(DataRefImpl Sec) const {
245 return generateXCOFFFixedNameStringRef(getSectionNameInternal(Sec));
246}
247
248uint64_t XCOFFObjectFile::getSectionAddress(DataRefImpl Sec) const {
249 // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
250 // with MSVC.
251 if (is64Bit())
252 return toSection64(Sec)->VirtualAddress;
253
254 return toSection32(Sec)->VirtualAddress;
255}
256
257uint64_t XCOFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
258 // Section numbers in XCOFF are numbered beginning at 1. A section number of
259 // zero is used to indicate that a symbol is being imported or is undefined.
260 if (is64Bit())
261 return toSection64(Sec) - sectionHeaderTable64() + 1;
262 else
263 return toSection32(Sec) - sectionHeaderTable32() + 1;
264}
265
266uint64_t XCOFFObjectFile::getSectionSize(DataRefImpl Sec) const {
267 // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
268 // with MSVC.
269 if (is64Bit())
270 return toSection64(Sec)->SectionSize;
271
272 return toSection32(Sec)->SectionSize;
273}
274
275Expected<ArrayRef<uint8_t>>
276XCOFFObjectFile::getSectionContents(DataRefImpl Sec) const {
277 if (isSectionVirtual(Sec))
278 return ArrayRef<uint8_t>();
279
280 uint64_t OffsetToRaw;
281 if (is64Bit())
282 OffsetToRaw = toSection64(Sec)->FileOffsetToRawData;
283 else
284 OffsetToRaw = toSection32(Sec)->FileOffsetToRawData;
285
286 const uint8_t * ContentStart = base() + OffsetToRaw;
287 uint64_t SectionSize = getSectionSize(Sec);
288 if (checkOffset(Data, reinterpret_cast<uintptr_t>(ContentStart), SectionSize))
289 return make_error<BinaryError>();
290
291 return makeArrayRef(ContentStart,SectionSize);
292}
293
294uint64_t XCOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const {
295 uint64_t Result = 0;
296 llvm_unreachable("Not yet implemented!")__builtin_unreachable();
297 return Result;
298}
299
300bool XCOFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
301 return false;
302}
303
304bool XCOFFObjectFile::isSectionText(DataRefImpl Sec) const {
305 return getSectionFlags(Sec) & XCOFF::STYP_TEXT;
306}
307
308bool XCOFFObjectFile::isSectionData(DataRefImpl Sec) const {
309 uint32_t Flags = getSectionFlags(Sec);
310 return Flags & (XCOFF::STYP_DATA | XCOFF::STYP_TDATA);
311}
312
313bool XCOFFObjectFile::isSectionBSS(DataRefImpl Sec) const {
314 uint32_t Flags = getSectionFlags(Sec);
315 return Flags & (XCOFF::STYP_BSS | XCOFF::STYP_TBSS);
316}
317
318bool XCOFFObjectFile::isDebugSection(DataRefImpl Sec) const {
319 uint32_t Flags = getSectionFlags(Sec);
320 return Flags & (XCOFF::STYP_DEBUG | XCOFF::STYP_DWARF);
321}
322
323bool XCOFFObjectFile::isSectionVirtual(DataRefImpl Sec) const {
324 return is64Bit() ? toSection64(Sec)->FileOffsetToRawData == 0
325 : toSection32(Sec)->FileOffsetToRawData == 0;
326}
327
328relocation_iterator XCOFFObjectFile::section_rel_begin(DataRefImpl Sec) const {
329 if (is64Bit())
330 report_fatal_error("64-bit support not implemented yet");
331 const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
332 auto RelocationsOrErr = relocations(*SectionEntPtr);
333 if (Error E = RelocationsOrErr.takeError())
334 return relocation_iterator(RelocationRef());
335 DataRefImpl Ret;
336 Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin());
337 return relocation_iterator(RelocationRef(Ret, this));
338}
339
340relocation_iterator XCOFFObjectFile::section_rel_end(DataRefImpl Sec) const {
341 if (is64Bit())
342 report_fatal_error("64-bit support not implemented yet");
343 const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
344 auto RelocationsOrErr = relocations(*SectionEntPtr);
345 if (Error E = RelocationsOrErr.takeError())
346 return relocation_iterator(RelocationRef());
347 DataRefImpl Ret;
348 Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end());
349 return relocation_iterator(RelocationRef(Ret, this));
350}
351
352void XCOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
353 Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation32>(Rel.p) + 1);
354}
355
356uint64_t XCOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
357 if (is64Bit())
358 report_fatal_error("64-bit support not implemented yet");
359 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
360 const XCOFFSectionHeader32 *Sec32 = sectionHeaderTable32();
361 const uint32_t RelocAddress = Reloc->VirtualAddress;
362 const uint16_t NumberOfSections = getNumberOfSections();
363 for (uint16_t i = 0; i < NumberOfSections; ++i) {
364 // Find which section this relocation is belonging to, and get the
365 // relocation offset relative to the start of the section.
366 if (Sec32->VirtualAddress <= RelocAddress &&
367 RelocAddress < Sec32->VirtualAddress + Sec32->SectionSize) {
368 return RelocAddress - Sec32->VirtualAddress;
369 }
370 ++Sec32;
371 }
372 return InvalidRelocOffset;
373}
374
375symbol_iterator XCOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
376 if (is64Bit())
377 report_fatal_error("64-bit support not implemented yet");
378 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
379 const uint32_t Index = Reloc->SymbolIndex;
380
381 if (Index >= getLogicalNumberOfSymbolTableEntries32())
382 return symbol_end();
383
384 DataRefImpl SymDRI;
385 SymDRI.p = getSymbolEntryAddressByIndex(Index);
386 return symbol_iterator(SymbolRef(SymDRI, this));
387}
388
389uint64_t XCOFFObjectFile::getRelocationType(DataRefImpl Rel) const {
390 if (is64Bit())
391 report_fatal_error("64-bit support not implemented yet");
392 return viewAs<XCOFFRelocation32>(Rel.p)->Type;
393}
394
395void XCOFFObjectFile::getRelocationTypeName(
396 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
397 if (is64Bit())
398 report_fatal_error("64-bit support not implemented yet");
399 const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
400 StringRef Res = XCOFF::getRelocationTypeString(Reloc->Type);
401 Result.append(Res.begin(), Res.end());
402}
403
404Expected<uint32_t> XCOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const {
405 uint32_t Result = 0;
406 // TODO: Return correct symbol flags.
407 return Result;
408}
409
410basic_symbol_iterator XCOFFObjectFile::symbol_begin() const {
411 DataRefImpl SymDRI;
412 SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr);
413 return basic_symbol_iterator(SymbolRef(SymDRI, this));
414}
415
416basic_symbol_iterator XCOFFObjectFile::symbol_end() const {
417 DataRefImpl SymDRI;
418 const uint32_t NumberOfSymbolTableEntries = getNumberOfSymbolTableEntries();
419 SymDRI.p = getSymbolEntryAddressByIndex(NumberOfSymbolTableEntries);
420 return basic_symbol_iterator(SymbolRef(SymDRI, this));
421}
422
423section_iterator XCOFFObjectFile::section_begin() const {
424 DataRefImpl DRI;
425 DRI.p = getSectionHeaderTableAddress();
426 return section_iterator(SectionRef(DRI, this));
427}
428
429section_iterator XCOFFObjectFile::section_end() const {
430 DataRefImpl DRI;
431 DRI.p = getWithOffset(getSectionHeaderTableAddress(),
432 getNumberOfSections() * getSectionHeaderSize());
433 return section_iterator(SectionRef(DRI, this));
434}
435
436uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; }
437
438StringRef XCOFFObjectFile::getFileFormatName() const {
439 return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000";
440}
441
442Triple::ArchType XCOFFObjectFile::getArch() const {
443 return is64Bit() ? Triple::ppc64 : Triple::ppc;
444}
445
446SubtargetFeatures XCOFFObjectFile::getFeatures() const {
447 return SubtargetFeatures();
448}
449
450bool XCOFFObjectFile::isRelocatableObject() const {
451 if (is64Bit())
452 return !(fileHeader64()->Flags & NoRelMask);
453 return !(fileHeader32()->Flags & NoRelMask);
454}
455
456Expected<uint64_t> XCOFFObjectFile::getStartAddress() const {
457 // TODO FIXME Should get from auxiliary_header->o_entry when support for the
458 // auxiliary_header is added.
459 return 0;
460}
461
462StringRef XCOFFObjectFile::mapDebugSectionName(StringRef Name) const {
463 return StringSwitch<StringRef>(Name)
464 .Case("dwinfo", "debug_info")
465 .Case("dwline", "debug_line")
466 .Case("dwpbnms", "debug_pubnames")
467 .Case("dwpbtyp", "debug_pubtypes")
468 .Case("dwarnge", "debug_aranges")
469 .Case("dwabrev", "debug_abbrev")
470 .Case("dwstr", "debug_str")
471 .Case("dwrnges", "debug_ranges")
472 .Case("dwloc", "debug_loc")
473 .Case("dwframe", "debug_frame")
474 .Case("dwmac", "debug_macinfo")
475 .Default(Name);
476}
477
478size_t XCOFFObjectFile::getFileHeaderSize() const {
479 return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32);
480}
481
482size_t XCOFFObjectFile::getSectionHeaderSize() const {
483 return is64Bit() ? sizeof(XCOFFSectionHeader64) :
484 sizeof(XCOFFSectionHeader32);
485}
486
487bool XCOFFObjectFile::is64Bit() const {
488 return Binary::ID_XCOFF64 == getType();
489}
490
491uint16_t XCOFFObjectFile::getMagic() const {
492 return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic;
493}
494
495Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const {
496 if (Num <= 0 || Num > getNumberOfSections())
497 return errorCodeToError(object_error::invalid_section_index);
498
499 DataRefImpl DRI;
500 DRI.p = getWithOffset(getSectionHeaderTableAddress(),
501 getSectionHeaderSize() * (Num - 1));
502 return DRI;
503}
504
505Expected<StringRef>
506XCOFFObjectFile::getSymbolSectionName(XCOFFSymbolRef SymEntPtr) const {
507 const int16_t SectionNum = SymEntPtr.getSectionNumber();
508
509 switch (SectionNum) {
510 case XCOFF::N_DEBUG:
511 return "N_DEBUG";
512 case XCOFF::N_ABS:
513 return "N_ABS";
514 case XCOFF::N_UNDEF:
515 return "N_UNDEF";
516 default:
517 Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum);
518 if (SecRef)
519 return generateXCOFFFixedNameStringRef(
520 getSectionNameInternal(SecRef.get()));
521 return SecRef.takeError();
522 }
523}
524
525unsigned XCOFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
526 XCOFFSymbolRef XCOFFSymRef(Sym.getRawDataRefImpl(), this);
527 return XCOFFSymRef.getSectionNumber();
528}
529
530bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) {
531 return (SectionNumber <= 0 && SectionNumber >= -2);
532}
533
534uint16_t XCOFFObjectFile::getNumberOfSections() const {
535 return is64Bit() ? fileHeader64()->NumberOfSections
536 : fileHeader32()->NumberOfSections;
537}
538
539int32_t XCOFFObjectFile::getTimeStamp() const {
540 return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp;
541}
542
543uint16_t XCOFFObjectFile::getOptionalHeaderSize() const {
544 return is64Bit() ? fileHeader64()->AuxHeaderSize
545 : fileHeader32()->AuxHeaderSize;
546}
547
548uint32_t XCOFFObjectFile::getSymbolTableOffset32() const {
549 return fileHeader32()->SymbolTableOffset;
550}
551
552int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const {
553 // As far as symbol table size is concerned, if this field is negative it is
554 // to be treated as a 0. However since this field is also used for printing we
555 // don't want to truncate any negative values.
556 return fileHeader32()->NumberOfSymTableEntries;
557}
558
559uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const {
560 return (fileHeader32()->NumberOfSymTableEntries >= 0
561 ? fileHeader32()->NumberOfSymTableEntries
562 : 0);
563}
564
565uint64_t XCOFFObjectFile::getSymbolTableOffset64() const {
566 return fileHeader64()->SymbolTableOffset;
567}
568
569uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const {
570 return fileHeader64()->NumberOfSymTableEntries;
571}
572
573uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries() const {
574 return is64Bit() ? getNumberOfSymbolTableEntries64()
575 : getLogicalNumberOfSymbolTableEntries32();
576}
577
578uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const {
579 const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
580 return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr),
581 XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries);
582}
583
584void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const {
585 if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr))
586 report_fatal_error("Symbol table entry is outside of symbol table.");
587
588 if (SymbolEntPtr >= getEndOfSymbolTableAddress())
589 report_fatal_error("Symbol table entry is outside of symbol table.");
590
591 ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) -
592 reinterpret_cast<const char *>(SymbolTblPtr);
593
594 if (Offset % XCOFF::SymbolTableEntrySize != 0)
595 report_fatal_error(
596 "Symbol table entry position is not valid inside of symbol table.");
597}
598
599uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const {
600 return (reinterpret_cast<const char *>(SymbolEntPtr) -
601 reinterpret_cast<const char *>(SymbolTblPtr)) /
602 XCOFF::SymbolTableEntrySize;
603}
604
605uintptr_t XCOFFObjectFile::getSymbolEntryAddressByIndex(uint32_t Index) const {
606 return getAdvancedSymbolEntryAddress(
607 reinterpret_cast<uintptr_t>(getPointerToSymbolTable()), Index);
608}
609
610Expected<StringRef>
611XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const {
612 const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
613
614 if (Index >= NumberOfSymTableEntries)
615 return errorCodeToError(object_error::invalid_symbol_index);
616
617 DataRefImpl SymDRI;
618 SymDRI.p = getSymbolEntryAddressByIndex(Index);
619 return getSymbolName(SymDRI);
620}
621
622uint16_t XCOFFObjectFile::getFlags() const {
623 return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags;
624}
625
626const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const {
627 return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name;
628}
629
630uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const {
631 return reinterpret_cast<uintptr_t>(SectionHeaderTable);
632}
633
634int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const {
635 return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags;
636}
637
638XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object)
639 : ObjectFile(Type, Object) {
640 assert(Type == Binary::ID_XCOFF32 || Type == Binary::ID_XCOFF64)((void)0);
641}
642
643ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const {
644 assert(is64Bit() && "64-bit interface called for non 64-bit file.")((void)0);
645 const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64();
646 return ArrayRef<XCOFFSectionHeader64>(TablePtr,
647 TablePtr + getNumberOfSections());
648}
649
650ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const {
651 assert(!is64Bit() && "32-bit interface called for non 32-bit file.")((void)0);
652 const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32();
653 return ArrayRef<XCOFFSectionHeader32>(TablePtr,
654 TablePtr + getNumberOfSections());
655}
656
657// In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO
658// section header contains the actual count of relocation entries in the s_paddr
659// field. STYP_OVRFLO headers contain the section index of their corresponding
660// sections as their raw "NumberOfRelocations" field value.
661Expected<uint32_t> XCOFFObjectFile::getLogicalNumberOfRelocationEntries(
662 const XCOFFSectionHeader32 &Sec) const {
663
664 uint16_t SectionIndex = &Sec - sectionHeaderTable32() + 1;
665
666 if (Sec.NumberOfRelocations < XCOFF::RelocOverflow)
667 return Sec.NumberOfRelocations;
668 for (const auto &Sec : sections32()) {
669 if (Sec.Flags == XCOFF::STYP_OVRFLO &&
670 Sec.NumberOfRelocations == SectionIndex)
671 return Sec.PhysicalAddress;
672 }
673 return errorCodeToError(object_error::parse_failed);
674}
675
676Expected<ArrayRef<XCOFFRelocation32>>
677XCOFFObjectFile::relocations(const XCOFFSectionHeader32 &Sec) const {
678 uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader),
679 Sec.FileOffsetToRelocationInfo);
680 auto NumRelocEntriesOrErr = getLogicalNumberOfRelocationEntries(Sec);
681 if (Error E = NumRelocEntriesOrErr.takeError())
682 return std::move(E);
683
684 uint32_t NumRelocEntries = NumRelocEntriesOrErr.get();
685
686 static_assert(
687 sizeof(XCOFFRelocation32) == XCOFF::RelocationSerializationSize32, "");
688 auto RelocationOrErr =
689 getObject<XCOFFRelocation32>(Data, reinterpret_cast<void *>(RelocAddr),
690 NumRelocEntries * sizeof(XCOFFRelocation32));
691 if (Error E = RelocationOrErr.takeError())
692 return std::move(E);
693
694 const XCOFFRelocation32 *StartReloc = RelocationOrErr.get();
695
696 return ArrayRef<XCOFFRelocation32>(StartReloc, StartReloc + NumRelocEntries);
697}
698
699Expected<XCOFFStringTable>
700XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) {
701 // If there is a string table, then the buffer must contain at least 4 bytes
702 // for the string table's size. Not having a string table is not an error.
703 if (Error E = Binary::checkOffset(
704 Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4)) {
705 consumeError(std::move(E));
706 return XCOFFStringTable{0, nullptr};
707 }
708
709 // Read the size out of the buffer.
710 uint32_t Size = support::endian::read32be(Obj->base() + Offset);
711
712 // If the size is less then 4, then the string table is just a size and no
713 // string data.
714 if (Size <= 4)
715 return XCOFFStringTable{4, nullptr};
716
717 auto StringTableOrErr =
718 getObject<char>(Obj->Data, Obj->base() + Offset, Size);
719 if (Error E = StringTableOrErr.takeError())
720 return std::move(E);
721
722 const char *StringTablePtr = StringTableOrErr.get();
723 if (StringTablePtr[Size - 1] != '\0')
724 return errorCodeToError(object_error::string_table_non_null_end);
725
726 return XCOFFStringTable{Size, StringTablePtr};
727}
728
729Expected<std::unique_ptr<XCOFFObjectFile>>
730XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) {
731 // Can't use std::make_unique because of the private constructor.
732 std::unique_ptr<XCOFFObjectFile> Obj;
733 Obj.reset(new XCOFFObjectFile(Type, MBR));
734
735 uint64_t CurOffset = 0;
736 const auto *Base = Obj->base();
737 MemoryBufferRef Data = Obj->Data;
738
739 // Parse file header.
740 auto FileHeaderOrErr =
741 getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize());
742 if (Error E = FileHeaderOrErr.takeError())
743 return std::move(E);
744 Obj->FileHeader = FileHeaderOrErr.get();
745
746 CurOffset += Obj->getFileHeaderSize();
747 // TODO FIXME we don't have support for an optional header yet, so just skip
748 // past it.
749 CurOffset += Obj->getOptionalHeaderSize();
750
751 // Parse the section header table if it is present.
752 if (Obj->getNumberOfSections()) {
753 auto SecHeadersOrErr = getObject<void>(Data, Base + CurOffset,
754 Obj->getNumberOfSections() *
755 Obj->getSectionHeaderSize());
756 if (Error E = SecHeadersOrErr.takeError())
757 return std::move(E);
758 Obj->SectionHeaderTable = SecHeadersOrErr.get();
759 }
760
761 const uint32_t NumberOfSymbolTableEntries =
762 Obj->getNumberOfSymbolTableEntries();
763
764 // If there is no symbol table we are done parsing the memory buffer.
765 if (NumberOfSymbolTableEntries == 0)
766 return std::move(Obj);
767
768 // Parse symbol table.
769 CurOffset = Obj->is64Bit() ? Obj->getSymbolTableOffset64()
770 : Obj->getSymbolTableOffset32();
771 const uint64_t SymbolTableSize =
772 static_cast<uint64_t>(XCOFF::SymbolTableEntrySize) *
773 NumberOfSymbolTableEntries;
774 auto SymTableOrErr =
775 getObject<void *>(Data, Base + CurOffset, SymbolTableSize);
776 if (Error E = SymTableOrErr.takeError())
777 return std::move(E);
778 Obj->SymbolTblPtr = SymTableOrErr.get();
779 CurOffset += SymbolTableSize;
780
781 // Parse String table.
782 Expected<XCOFFStringTable> StringTableOrErr =
783 parseStringTable(Obj.get(), CurOffset);
784 if (Error E = StringTableOrErr.takeError())
785 return std::move(E);
786 Obj->StringTable = StringTableOrErr.get();
787
788 return std::move(Obj);
789}
790
791Expected<std::unique_ptr<ObjectFile>>
792ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef,
793 unsigned FileType) {
794 return XCOFFObjectFile::create(FileType, MemBufRef);
795}
796
797bool XCOFFSymbolRef::isFunction() const {
798 if (!isCsectSymbol())
799 return false;
800
801 if (getSymbolType() & FunctionSym)
802 return true;
803
804 Expected<XCOFFCsectAuxRef> ExpCsectAuxEnt = getXCOFFCsectAuxRef();
805 if (!ExpCsectAuxEnt)
806 return false;
807
808 const XCOFFCsectAuxRef CsectAuxRef = ExpCsectAuxEnt.get();
809
810 // A function definition should be a label definition.
811 // FIXME: This is not necessarily the case when -ffunction-sections is
812 // enabled.
813 if (!CsectAuxRef.isLabel())
814 return false;
815
816 if (CsectAuxRef.getStorageMappingClass() != XCOFF::XMC_PR)
817 return false;
818
819 const int16_t SectNum = getSectionNumber();
820 Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum);
821 if (!SI) {
822 // If we could not get the section, then this symbol should not be
823 // a function. So consume the error and return `false` to move on.
824 consumeError(SI.takeError());
825 return false;
826 }
827
828 return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT);
829}
830
831bool XCOFFSymbolRef::isCsectSymbol() const {
832 XCOFF::StorageClass SC = getStorageClass();
833 return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT ||
834 SC == XCOFF::C_HIDEXT);
835}
836
837Expected<XCOFFCsectAuxRef> XCOFFSymbolRef::getXCOFFCsectAuxRef() const {
838 assert(isCsectSymbol() &&((void)0)
839 "Calling csect symbol interface with a non-csect symbol.")((void)0);
840
841 uint8_t NumberOfAuxEntries = getNumberOfAuxEntries();
842
843 Expected<StringRef> NameOrErr = getName();
844 if (auto Err = NameOrErr.takeError())
845 return std::move(Err);
846
847 if (!NumberOfAuxEntries) {
848 return createStringError(object_error::parse_failed,
849 "csect symbol \"" + *NameOrErr +
850 "\" contains no auxiliary entry");
851 }
852
853 if (!OwningObjectPtr->is64Bit()) {
854 // In XCOFF32, the csect auxilliary entry is always the last auxiliary
855 // entry for the symbol.
856 uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
857 getEntryAddress(), NumberOfAuxEntries);
858 return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt32>(AuxAddr));
859 }
860
861 // XCOFF64 uses SymbolAuxType to identify the auxiliary entry type.
862 // We need to iterate through all the auxiliary entries to find it.
863 for (uint8_t Index = NumberOfAuxEntries; Index > 0; --Index) {
864 uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
865 getEntryAddress(), Index);
866 if (*OwningObjectPtr->getSymbolAuxType(AuxAddr) ==
867 XCOFF::SymbolAuxType::AUX_CSECT) {
868#ifndef NDEBUG1
869 OwningObjectPtr->checkSymbolEntryPointer(AuxAddr);
870#endif
871 return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt64>(AuxAddr));
872 }
873 }
874
875 return createStringError(
876 object_error::parse_failed,
877 "a csect auxiliary entry is not found for symbol \"" + *NameOrErr + "\"");
878}
879
880Expected<StringRef> XCOFFSymbolRef::getName() const {
881 // A storage class value with the high-order bit on indicates that the name is
882 // a symbolic debugger stabstring.
883 if (getStorageClass() & 0x80)
884 return StringRef("Unimplemented Debug Name");
885
886 if (Entry32) {
887 if (Entry32->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
888 return generateXCOFFFixedNameStringRef(Entry32->SymbolName);
889
890 return OwningObjectPtr->getStringTableEntry(Entry32->NameInStrTbl.Offset);
891 }
892
893 return OwningObjectPtr->getStringTableEntry(Entry64->Offset);
894}
895
896// Explictly instantiate template classes.
897template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
898template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
899
900bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes) {
901 if (Bytes.size() < 4)
902 return false;
903
904 return support::endian::read32be(Bytes.data()) == 0;
905}
906
907#define GETVALUEWITHMASK(X) (Data & (TracebackTable::X))
908#define GETVALUEWITHMASKSHIFT(X, S) \
909 ((Data & (TracebackTable::X)) >> (TracebackTable::S))
910
911Expected<TBVectorExt> TBVectorExt::create(StringRef TBvectorStrRef) {
912 Error Err = Error::success();
913 TBVectorExt TBTVecExt(TBvectorStrRef, Err);
914 if (Err)
915 return std::move(Err);
916 return TBTVecExt;
917}
918
919TBVectorExt::TBVectorExt(StringRef TBvectorStrRef, Error &Err) {
920 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(TBvectorStrRef.data());
921 Data = support::endian::read16be(Ptr);
922 uint32_t VecParmsTypeValue = support::endian::read32be(Ptr + 2);
923 unsigned ParmsNum =
924 GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask, NumberOfVectorParmsShift);
925
926 ErrorAsOutParameter EAO(&Err);
927 Expected<SmallString<32>> VecParmsTypeOrError =
928 parseVectorParmsType(VecParmsTypeValue, ParmsNum);
929 if (!VecParmsTypeOrError)
930 Err = VecParmsTypeOrError.takeError();
931 else
932 VecParmsInfo = VecParmsTypeOrError.get();
933}
934
935uint8_t TBVectorExt::getNumberOfVRSaved() const {
936 return GETVALUEWITHMASKSHIFT(NumberOfVRSavedMask, NumberOfVRSavedShift);
937}
938
939bool TBVectorExt::isVRSavedOnStack() const {
940 return GETVALUEWITHMASK(IsVRSavedOnStackMask);
941}
942
943bool TBVectorExt::hasVarArgs() const {
944 return GETVALUEWITHMASK(HasVarArgsMask);
945}
946
947uint8_t TBVectorExt::getNumberOfVectorParms() const {
948 return GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask,
949 NumberOfVectorParmsShift);
950}
951
952bool TBVectorExt::hasVMXInstruction() const {
953 return GETVALUEWITHMASK(HasVMXInstructionMask);
954}
955#undef GETVALUEWITHMASK
956#undef GETVALUEWITHMASKSHIFT
957
958Expected<XCOFFTracebackTable> XCOFFTracebackTable::create(const uint8_t *Ptr,
959 uint64_t &Size) {
960 Error Err = Error::success();
961 XCOFFTracebackTable TBT(Ptr, Size, Err);
962 if (Err)
963 return std::move(Err);
964 return TBT;
965}
966
967XCOFFTracebackTable::XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size,
968 Error &Err)
969 : TBPtr(Ptr) {
970 ErrorAsOutParameter EAO(&Err);
971 DataExtractor DE(ArrayRef<uint8_t>(Ptr, Size), /*IsLittleEndian=*/false,
972 /*AddressSize=*/0);
973 DataExtractor::Cursor Cur(/*Offset=*/0);
974
975 // Skip 8 bytes of mandatory fields.
976 DE.getU64(Cur);
977
978 unsigned FixedParmsNum = getNumberOfFixedParms();
979 unsigned FloatingParmsNum = getNumberOfFPParms();
980 uint32_t ParamsTypeValue = 0;
981
982 // Begin to parse optional fields.
983 if (Cur && (FixedParmsNum + FloatingParmsNum) > 0)
984 ParamsTypeValue = DE.getU32(Cur);
985
986 if (Cur && hasTraceBackTableOffset())
987 TraceBackTableOffset = DE.getU32(Cur);
988
989 if (Cur && isInterruptHandler())
990 HandlerMask = DE.getU32(Cur);
991
992 if (Cur && hasControlledStorage()) {
993 NumOfCtlAnchors = DE.getU32(Cur);
994 if (Cur && NumOfCtlAnchors) {
995 SmallVector<uint32_t, 8> Disp;
996 Disp.reserve(NumOfCtlAnchors.getValue());
997 for (uint32_t I = 0; I < NumOfCtlAnchors && Cur; ++I)
998 Disp.push_back(DE.getU32(Cur));
999 if (Cur)
1000 ControlledStorageInfoDisp = std::move(Disp);
1001 }
1002 }
1003
1004 if (Cur && isFuncNamePresent()) {
1005 uint16_t FunctionNameLen = DE.getU16(Cur);
1006 if (Cur)
1007 FunctionName = DE.getBytes(Cur, FunctionNameLen);
1008 }
1009
1010 if (Cur && isAllocaUsed())
1011 AllocaRegister = DE.getU8(Cur);
1012
1013 unsigned VectorParmsNum = 0;
1014 if (Cur && hasVectorInfo()) {
1015 StringRef VectorExtRef = DE.getBytes(Cur, 6);
1016 if (Cur) {
1017 Expected<TBVectorExt> TBVecExtOrErr = TBVectorExt::create(VectorExtRef);
1018 if (!TBVecExtOrErr) {
1019 Err = TBVecExtOrErr.takeError();
1020 return;
1021 }
1022 VecExt = TBVecExtOrErr.get();
1023 VectorParmsNum = VecExt.getValue().getNumberOfVectorParms();
1024 }
1025 }
1026
1027 // As long as there is no fixed-point or floating-point parameter, this
1028 // field remains not present even when hasVectorInfo gives true and
1029 // indicates the presence of vector parameters.
1030 if (Cur && (FixedParmsNum + FloatingParmsNum) > 0) {
1031 Expected<SmallString<32>> ParmsTypeOrError =
1032 hasVectorInfo()
1033 ? parseParmsTypeWithVecInfo(ParamsTypeValue, FixedParmsNum,
1034 FloatingParmsNum, VectorParmsNum)
1035 : parseParmsType(ParamsTypeValue, FixedParmsNum, FloatingParmsNum);
1036
1037 if (!ParmsTypeOrError) {
1038 Err = ParmsTypeOrError.takeError();
1039 return;
1040 }
1041 ParmsType = ParmsTypeOrError.get();
1042 }
1043
1044 if (Cur && hasExtensionTable())
1045 ExtensionTable = DE.getU8(Cur);
1046
1047 if (!Cur)
1048 Err = Cur.takeError();
1049
1050 Size = Cur.tell();
1051}
1052
1053#define GETBITWITHMASK(P, X) \
1054 (support::endian::read32be(TBPtr + (P)) & (TracebackTable::X))
1055#define GETBITWITHMASKSHIFT(P, X, S) \
1056 ((support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) >> \
1057 (TracebackTable::S))
1058
1059uint8_t XCOFFTracebackTable::getVersion() const {
1060 return GETBITWITHMASKSHIFT(0, VersionMask, VersionShift);
1061}
1062
1063uint8_t XCOFFTracebackTable::getLanguageID() const {
1064 return GETBITWITHMASKSHIFT(0, LanguageIdMask, LanguageIdShift);
1065}
1066
1067bool XCOFFTracebackTable::isGlobalLinkage() const {
1068 return GETBITWITHMASK(0, IsGlobaLinkageMask);
1069}
1070
1071bool XCOFFTracebackTable::isOutOfLineEpilogOrPrologue() const {
1072 return GETBITWITHMASK(0, IsOutOfLineEpilogOrPrologueMask);
1073}
1074
1075bool XCOFFTracebackTable::hasTraceBackTableOffset() const {
1076 return GETBITWITHMASK(0, HasTraceBackTableOffsetMask);
1077}
1078
1079bool XCOFFTracebackTable::isInternalProcedure() const {
1080 return GETBITWITHMASK(0, IsInternalProcedureMask);
1081}
1082
1083bool XCOFFTracebackTable::hasControlledStorage() const {
1084 return GETBITWITHMASK(0, HasControlledStorageMask);
1085}
1086
1087bool XCOFFTracebackTable::isTOCless() const {
1088 return GETBITWITHMASK(0, IsTOClessMask);
1089}
1090
1091bool XCOFFTracebackTable::isFloatingPointPresent() const {
1092 return GETBITWITHMASK(0, IsFloatingPointPresentMask);
1093}
1094
1095bool XCOFFTracebackTable::isFloatingPointOperationLogOrAbortEnabled() const {
1096 return GETBITWITHMASK(0, IsFloatingPointOperationLogOrAbortEnabledMask);
1097}
1098
1099bool XCOFFTracebackTable::isInterruptHandler() const {
1100 return GETBITWITHMASK(0, IsInterruptHandlerMask);
1101}
1102
1103bool XCOFFTracebackTable::isFuncNamePresent() const {
1104 return GETBITWITHMASK(0, IsFunctionNamePresentMask);
1105}
1106
1107bool XCOFFTracebackTable::isAllocaUsed() const {
1108 return GETBITWITHMASK(0, IsAllocaUsedMask);
1109}
1110
1111uint8_t XCOFFTracebackTable::getOnConditionDirective() const {
1112 return GETBITWITHMASKSHIFT(0, OnConditionDirectiveMask,
1113 OnConditionDirectiveShift);
1114}
1115
1116bool XCOFFTracebackTable::isCRSaved() const {
1117 return GETBITWITHMASK(0, IsCRSavedMask);
1118}
1119
1120bool XCOFFTracebackTable::isLRSaved() const {
1121 return GETBITWITHMASK(0, IsLRSavedMask);
1122}
1123
1124bool XCOFFTracebackTable::isBackChainStored() const {
1125 return GETBITWITHMASK(4, IsBackChainStoredMask);
1126}
1127
1128bool XCOFFTracebackTable::isFixup() const {
1129 return GETBITWITHMASK(4, IsFixupMask);
1130}
1131
1132uint8_t XCOFFTracebackTable::getNumOfFPRsSaved() const {
1133 return GETBITWITHMASKSHIFT(4, FPRSavedMask, FPRSavedShift);
1134}
1135
1136bool XCOFFTracebackTable::hasExtensionTable() const {
1137 return GETBITWITHMASK(4, HasExtensionTableMask);
1138}
1139
1140bool XCOFFTracebackTable::hasVectorInfo() const {
1141 return GETBITWITHMASK(4, HasVectorInfoMask);
1142}
1143
1144uint8_t XCOFFTracebackTable::getNumOfGPRsSaved() const {
1145 return GETBITWITHMASKSHIFT(4, GPRSavedMask, GPRSavedShift);
1146}
1147
1148uint8_t XCOFFTracebackTable::getNumberOfFixedParms() const {
1149 return GETBITWITHMASKSHIFT(4, NumberOfFixedParmsMask,
1150 NumberOfFixedParmsShift);
1151}
1152
1153uint8_t XCOFFTracebackTable::getNumberOfFPParms() const {
1154 return GETBITWITHMASKSHIFT(4, NumberOfFloatingPointParmsMask,
1155 NumberOfFloatingPointParmsShift);
1156}
1157
1158bool XCOFFTracebackTable::hasParmsOnStack() const {
1159 return GETBITWITHMASK(4, HasParmsOnStackMask);
1160}
1161
1162#undef GETBITWITHMASK
1163#undef GETBITWITHMASKSHIFT
1164} // namespace object
1165} // namespace llvm

/usr/src/gnu/usr.bin/clang/libLLVM/../../../llvm/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 XCOFFSectionHeader {
55 // Least significant 3 bits are reserved.
56 static constexpr unsigned SectionFlagsReservedMask = 0x7;
57
58 // The low order 16 bits of section flags denotes the section type.
59 static constexpr unsigned SectionFlagsTypeMask = 0xffffu;
60
61public:
62 StringRef getName() const;
63 uint16_t getSectionType() const;
64 bool isReservedSectionType() const;
65};
66
67// Explicit extern template declarations.
68struct XCOFFSectionHeader32;
69struct XCOFFSectionHeader64;
70extern template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
71extern template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
72
73struct XCOFFSectionHeader32 : XCOFFSectionHeader<XCOFFSectionHeader32> {
74 char Name[XCOFF::NameSize];
75 support::ubig32_t PhysicalAddress;
76 support::ubig32_t VirtualAddress;
77 support::ubig32_t SectionSize;
78 support::ubig32_t FileOffsetToRawData;
79 support::ubig32_t FileOffsetToRelocationInfo;
80 support::ubig32_t FileOffsetToLineNumberInfo;
81 support::ubig16_t NumberOfRelocations;
82 support::ubig16_t NumberOfLineNumbers;
83 support::big32_t Flags;
84};
85
86struct XCOFFSectionHeader64 : XCOFFSectionHeader<XCOFFSectionHeader64> {
87 char Name[XCOFF::NameSize];
88 support::ubig64_t PhysicalAddress;
89 support::ubig64_t VirtualAddress;
90 support::ubig64_t SectionSize;
91 support::big64_t FileOffsetToRawData;
92 support::big64_t FileOffsetToRelocationInfo;
93 support::big64_t FileOffsetToLineNumberInfo;
94 support::ubig32_t NumberOfRelocations;
95 support::ubig32_t NumberOfLineNumbers;
96 support::big32_t Flags;
97 char Padding[4];
98};
99
100struct XCOFFStringTable {
101 uint32_t Size;
102 const char *Data;
103};
104
105struct XCOFFCsectAuxEnt32 {
106 support::ubig32_t SectionOrLength;
107 support::ubig32_t ParameterHashIndex;
108 support::ubig16_t TypeChkSectNum;
109 uint8_t SymbolAlignmentAndType;
110 XCOFF::StorageMappingClass StorageMappingClass;
111 support::ubig32_t StabInfoIndex;
112 support::ubig16_t StabSectNum;
113};
114
115struct XCOFFCsectAuxEnt64 {
116 support::ubig32_t SectionOrLengthLowByte;
117 support::ubig32_t ParameterHashIndex;
118 support::ubig16_t TypeChkSectNum;
119 uint8_t SymbolAlignmentAndType;
120 XCOFF::StorageMappingClass StorageMappingClass;
121 support::ubig32_t SectionOrLengthHighByte;
122 uint8_t Pad;
123 XCOFF::SymbolAuxType AuxType;
124};
125
126class XCOFFCsectAuxRef {
127public:
128 static constexpr uint8_t SymbolTypeMask = 0x07;
129 static constexpr uint8_t SymbolAlignmentMask = 0xF8;
130 static constexpr size_t SymbolAlignmentBitOffset = 3;
131
132 XCOFFCsectAuxRef(const XCOFFCsectAuxEnt32 *Entry32) : Entry32(Entry32) {}
133 XCOFFCsectAuxRef(const XCOFFCsectAuxEnt64 *Entry64) : Entry64(Entry64) {}
134
135 // For getSectionOrLength(),
136 // If the symbol type is XTY_SD or XTY_CM, the csect length.
137 // If the symbol type is XTY_LD, the symbol table
138 // index of the containing csect.
139 // If the symbol type is XTY_ER, 0.
140 uint64_t getSectionOrLength() const {
141 return Entry32 ? getSectionOrLength32() : getSectionOrLength64();
142 }
143
144 uint32_t getSectionOrLength32() const {
145 assert(Entry32 && "32-bit interface called on 64-bit object file.")((void)0);
146 return Entry32->SectionOrLength;
147 }
148
149 uint64_t getSectionOrLength64() const {
150 assert(Entry64 && "64-bit interface called on 32-bit object file.")((void)0);
151 return (static_cast<uint64_t>(Entry64->SectionOrLengthHighByte) << 32) |
152 Entry64->SectionOrLengthLowByte;
153 }
154
155#define GETVALUE(X) Entry32 ? Entry32->X : Entry64->X
156
157 uint32_t getParameterHashIndex() const {
158 return GETVALUE(ParameterHashIndex);
159 }
160
161 uint16_t getTypeChkSectNum() const { return GETVALUE(TypeChkSectNum); }
162
163 XCOFF::StorageMappingClass getStorageMappingClass() const {
164 return GETVALUE(StorageMappingClass);
165 }
166
167 uintptr_t getEntryAddress() const {
168 return Entry32 ? reinterpret_cast<uintptr_t>(Entry32)
169 : reinterpret_cast<uintptr_t>(Entry64);
170 }
171
172 uint16_t getAlignmentLog2() const {
173 return (getSymbolAlignmentAndType() & SymbolAlignmentMask) >>
174 SymbolAlignmentBitOffset;
175 }
176
177 uint8_t getSymbolType() const {
178 return getSymbolAlignmentAndType() & SymbolTypeMask;
179 }
180
181 bool isLabel() const { return getSymbolType() == XCOFF::XTY_LD; }
182
183 uint32_t getStabInfoIndex32() const {
184 assert(Entry32 && "32-bit interface called on 64-bit object file.")((void)0);
185 return Entry32->StabInfoIndex;
186 }
187
188 uint16_t getStabSectNum32() const {
189 assert(Entry32 && "32-bit interface called on 64-bit object file.")((void)0);
190 return Entry32->StabSectNum;
191 }
192
193 XCOFF::SymbolAuxType getAuxType64() const {
194 assert(Entry64 && "64-bit interface called on 32-bit object file.")((void)0);
195 return Entry64->AuxType;
196 }
197
198private:
199 uint8_t getSymbolAlignmentAndType() const {
200 return GETVALUE(SymbolAlignmentAndType);
201 }
202
203#undef GETVALUE
204
205 const XCOFFCsectAuxEnt32 *Entry32 = nullptr;
206 const XCOFFCsectAuxEnt64 *Entry64 = nullptr;
207};
208
209struct XCOFFFileAuxEnt {
210 typedef struct {
211 support::big32_t Magic; // Zero indicates name in string table.
212 support::ubig32_t Offset;
213 char NamePad[XCOFF::FileNamePadSize];
214 } NameInStrTblType;
215 union {
216 char Name[XCOFF::NameSize + XCOFF::FileNamePadSize];
217 NameInStrTblType NameInStrTbl;
218 };
219 XCOFF::CFileStringType Type;
220 uint8_t ReservedZeros[2];
221 XCOFF::SymbolAuxType AuxType; // 64-bit XCOFF file only.
222};
223
224struct XCOFFSectAuxEntForStat {
225 support::ubig32_t SectionLength;
226 support::ubig16_t NumberOfRelocEnt;
227 support::ubig16_t NumberOfLineNum;
228 uint8_t Pad[10];
229}; // 32-bit XCOFF file only.
230
231struct XCOFFRelocation32 {
232 // Masks for packing/unpacking the r_rsize field of relocations.
233
234 // The msb is used to indicate if the bits being relocated are signed or
235 // unsigned.
236 static constexpr uint8_t XR_SIGN_INDICATOR_MASK = 0x80;
237
238 // The 2nd msb is used to indicate that the binder has replaced/modified the
239 // original instruction.
240 static constexpr uint8_t XR_FIXUP_INDICATOR_MASK = 0x40;
241
242 // The remaining bits specify the bit length of the relocatable reference
243 // minus one.
244 static constexpr uint8_t XR_BIASED_LENGTH_MASK = 0x3f;
245
246public:
247 support::ubig32_t VirtualAddress;
248 support::ubig32_t SymbolIndex;
249
250 // Packed field, see XR_* masks for details of packing.
251 uint8_t Info;
252
253 XCOFF::RelocationType Type;
254
255public:
256 bool isRelocationSigned() const;
257 bool isFixupIndicated() const;
258
259 // Returns the number of bits being relocated.
260 uint8_t getRelocatedLength() const;
261};
262
263class XCOFFSymbolRef;
264
265class XCOFFObjectFile : public ObjectFile {
266private:
267 const void *FileHeader = nullptr;
268 const void *SectionHeaderTable = nullptr;
269
270 const void *SymbolTblPtr = nullptr;
271 XCOFFStringTable StringTable = {0, nullptr};
272
273 const XCOFFFileHeader32 *fileHeader32() const;
274 const XCOFFFileHeader64 *fileHeader64() const;
275
276 const XCOFFSectionHeader32 *sectionHeaderTable32() const;
277 const XCOFFSectionHeader64 *sectionHeaderTable64() const;
278
279 size_t getFileHeaderSize() const;
280 size_t getSectionHeaderSize() const;
281
282 const XCOFFSectionHeader32 *toSection32(DataRefImpl Ref) const;
283 const XCOFFSectionHeader64 *toSection64(DataRefImpl Ref) const;
284 uintptr_t getSectionHeaderTableAddress() const;
285 uintptr_t getEndOfSymbolTableAddress() const;
286
287 // This returns a pointer to the start of the storage for the name field of
288 // the 32-bit or 64-bit SectionHeader struct. This string is *not* necessarily
289 // null-terminated.
290 const char *getSectionNameInternal(DataRefImpl Sec) const;
291
292 static bool isReservedSectionNumber(int16_t SectionNumber);
293
294 // Constructor and "create" factory function. The constructor is only a thin
295 // wrapper around the base constructor. The "create" function fills out the
296 // XCOFF-specific information and performs the error checking along the way.
297 XCOFFObjectFile(unsigned Type, MemoryBufferRef Object);
298 static Expected<std::unique_ptr<XCOFFObjectFile>> create(unsigned Type,
299 MemoryBufferRef MBR);
300
301 // Helper for parsing the StringTable. Returns an 'Error' if parsing failed
302 // and an XCOFFStringTable if parsing succeeded.
303 static Expected<XCOFFStringTable> parseStringTable(const XCOFFObjectFile *Obj,
304 uint64_t Offset);
305
306 // Make a friend so it can call the private 'create' function.
307 friend Expected<std::unique_ptr<ObjectFile>>
308 ObjectFile::createXCOFFObjectFile(MemoryBufferRef Object, unsigned FileType);
309
310 void checkSectionAddress(uintptr_t Addr, uintptr_t TableAddr) const;
311
312public:
313 static constexpr uint64_t InvalidRelocOffset =
314 std::numeric_limits<uint64_t>::max();
315
316 // Interface inherited from base classes.
317 void moveSymbolNext(DataRefImpl &Symb) const override;
318 Expected<uint32_t> getSymbolFlags(DataRefImpl Symb) const override;
319 basic_symbol_iterator symbol_begin() const override;
320 basic_symbol_iterator symbol_end() const override;
321
322 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
323 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
324 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
325 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
326 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
327 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
328
329 void moveSectionNext(DataRefImpl &Sec) const override;
330 Expected<StringRef> getSectionName(DataRefImpl Sec) const override;
331 uint64_t getSectionAddress(DataRefImpl Sec) const override;
332 uint64_t getSectionIndex(DataRefImpl Sec) const override;
333 uint64_t getSectionSize(DataRefImpl Sec) const override;
334 Expected<ArrayRef<uint8_t>>
335 getSectionContents(DataRefImpl Sec) const override;
336 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
337 bool isSectionCompressed(DataRefImpl Sec) const override;
338 bool isSectionText(DataRefImpl Sec) const override;
339 bool isSectionData(DataRefImpl Sec) const override;
340 bool isSectionBSS(DataRefImpl Sec) const override;
341 bool isDebugSection(DataRefImpl Sec) const override;
342
343 bool isSectionVirtual(DataRefImpl Sec) const override;
344 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
345 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
346
347 void moveRelocationNext(DataRefImpl &Rel) const override;
348
349 /// \returns the relocation offset with the base address of the containing
350 /// section as zero, or InvalidRelocOffset on errors (such as a relocation
351 /// that does not refer to an address in any section).
352 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
353 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
354 uint64_t getRelocationType(DataRefImpl Rel) const override;
355 void getRelocationTypeName(DataRefImpl Rel,
356 SmallVectorImpl<char> &Result) const override;
357
358 section_iterator section_begin() const override;
359 section_iterator section_end() const override;
360 uint8_t getBytesInAddress() const override;
361 StringRef getFileFormatName() const override;
362 Triple::ArchType getArch() const override;
363 SubtargetFeatures getFeatures() const override;
364 Expected<uint64_t> getStartAddress() const override;
365 StringRef mapDebugSectionName(StringRef Name) const override;
366 bool isRelocatableObject() const override;
367
368 // Below here is the non-inherited interface.
369 bool is64Bit() const;
370
371 const void *getPointerToSymbolTable() const { return SymbolTblPtr; }
372
373 Expected<StringRef> getSymbolSectionName(XCOFFSymbolRef Ref) const;
374 unsigned getSymbolSectionID(SymbolRef Sym) const;
375 XCOFFSymbolRef toSymbolRef(DataRefImpl Ref) const;
376
377 // File header related interfaces.
378 uint16_t getMagic() const;
379 uint16_t getNumberOfSections() const;
380 int32_t getTimeStamp() const;
381
382 // Symbol table offset and entry count are handled differently between
383 // XCOFF32 and XCOFF64.
384 uint32_t getSymbolTableOffset32() const;
385 uint64_t getSymbolTableOffset64() const;
386
387 // Note that this value is signed and might return a negative value. Negative
388 // values are reserved for future use.
389 int32_t getRawNumberOfSymbolTableEntries32() const;
390
391 // The sanitized value appropriate to use as an index into the symbol table.
392 uint32_t getLogicalNumberOfSymbolTableEntries32() const;
393
394 uint32_t getNumberOfSymbolTableEntries64() const;
395
396 // Return getLogicalNumberOfSymbolTableEntries32 or
397 // getNumberOfSymbolTableEntries64 depending on the object mode.
398 uint32_t getNumberOfSymbolTableEntries() const;
399
400 uint32_t getSymbolIndex(uintptr_t SymEntPtr) const;
401 uintptr_t getSymbolEntryAddressByIndex(uint32_t SymbolTableIndex) const;
402 Expected<StringRef> getSymbolNameByIndex(uint32_t SymbolTableIndex) const;
403
404 Expected<StringRef> getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const;
405 uint16_t getOptionalHeaderSize() const;
406 uint16_t getFlags() const;
407
408 // Section header table related interfaces.
409 ArrayRef<XCOFFSectionHeader32> sections32() const;
410 ArrayRef<XCOFFSectionHeader64> sections64() const;
411
412 int32_t getSectionFlags(DataRefImpl Sec) const;
413 Expected<DataRefImpl> getSectionByNum(int16_t Num) const;
414
415 void checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const;
416
417 // Relocation-related interfaces.
418 Expected<uint32_t>
419 getLogicalNumberOfRelocationEntries(const XCOFFSectionHeader32 &Sec) const;
420
421 Expected<ArrayRef<XCOFFRelocation32>>
422 relocations(const XCOFFSectionHeader32 &) const;
423
424 // This function returns string table entry.
425 Expected<StringRef> getStringTableEntry(uint32_t Offset) const;
426
427 // This function returns the string table.
428 StringRef getStringTable() const;
429
430 const XCOFF::SymbolAuxType *getSymbolAuxType(uintptr_t AuxEntryAddress) const;
431
432 static uintptr_t getAdvancedSymbolEntryAddress(uintptr_t CurrentAddress,
433 uint32_t Distance);
434
435 static bool classof(const Binary *B) { return B->isXCOFF(); }
436}; // XCOFFObjectFile
437
438typedef struct {
439 uint8_t LanguageId;
440 uint8_t CpuTypeId;
441} CFileLanguageIdAndTypeIdType;
442
443struct XCOFFSymbolEntry32 {
444 typedef struct {
445 support::big32_t Magic; // Zero indicates name in string table.
446 support::ubig32_t Offset;
447 } NameInStrTblType;
448
449 union {
450 char SymbolName[XCOFF::NameSize];
451 NameInStrTblType NameInStrTbl;
452 };
453
454 support::ubig32_t Value; // Symbol value; storage class-dependent.
455 support::big16_t SectionNumber;
456
457 union {
458 support::ubig16_t SymbolType;
459 CFileLanguageIdAndTypeIdType CFileLanguageIdAndTypeId;
460 };
461
462 XCOFF::StorageClass StorageClass;
463 uint8_t NumberOfAuxEntries;
464};
465
466struct XCOFFSymbolEntry64 {
467 support::ubig64_t Value; // Symbol value; storage class-dependent.
468 support::ubig32_t Offset;
469 support::big16_t SectionNumber;
470
471 union {
472 support::ubig16_t SymbolType;
473 CFileLanguageIdAndTypeIdType CFileLanguageIdAndTypeId;
474 };
475
476 XCOFF::StorageClass StorageClass;
477 uint8_t NumberOfAuxEntries;
478};
479
480class XCOFFSymbolRef {
481public:
482 enum { NAME_IN_STR_TBL_MAGIC = 0x0 };
483
484 XCOFFSymbolRef(DataRefImpl SymEntDataRef,
485 const XCOFFObjectFile *OwningObjectPtr)
486 : OwningObjectPtr(OwningObjectPtr) {
487 assert(OwningObjectPtr && "OwningObjectPtr cannot be nullptr!")((void)0);
488 assert(SymEntDataRef.p != 0 &&((void)0)
489 "Symbol table entry pointer cannot be nullptr!")((void)0);
490
491 if (OwningObjectPtr->is64Bit())
4
Taking false branch
492 Entry64 = reinterpret_cast<const XCOFFSymbolEntry64 *>(SymEntDataRef.p);
493 else
494 Entry32 = reinterpret_cast<const XCOFFSymbolEntry32 *>(SymEntDataRef.p);
495 }
496
497 uint64_t getValue() const { return Entry32 ? getValue32() : getValue64(); }
8
Assuming field 'Entry32' is null
9
'?' condition is false
10
Calling 'XCOFFSymbolRef::getValue64'
498
499 uint32_t getValue32() const { return Entry32->Value; }
500
501 uint64_t getValue64() const { return Entry64->Value; }
11
Called C++ object pointer is null
502
503#define GETVALUE(X) Entry32 ? Entry32->X : Entry64->X
504
505 int16_t getSectionNumber() const { return GETVALUE(SectionNumber); }
506
507 uint16_t getSymbolType() const { return GETVALUE(SymbolType); }
508
509 uint8_t getLanguageIdForCFile() const {
510 assert(getStorageClass() == XCOFF::C_FILE &&((void)0)
511 "This interface is for C_FILE only.")((void)0);
512 return GETVALUE(CFileLanguageIdAndTypeId.LanguageId);
513 }
514
515 uint8_t getCPUTypeIddForCFile() const {
516 assert(getStorageClass() == XCOFF::C_FILE &&((void)0)
517 "This interface is for C_FILE only.")((void)0);
518 return GETVALUE(CFileLanguageIdAndTypeId.CpuTypeId);
519 }
520
521 XCOFF::StorageClass getStorageClass() const { return GETVALUE(StorageClass); }
522
523 uint8_t getNumberOfAuxEntries() const { return GETVALUE(NumberOfAuxEntries); }
524
525#undef GETVALUE
526
527 uintptr_t getEntryAddress() const {
528 return Entry32 ? reinterpret_cast<uintptr_t>(Entry32)
529 : reinterpret_cast<uintptr_t>(Entry64);
530 }
531
532 Expected<StringRef> getName() const;
533 bool isFunction() const;
534 bool isCsectSymbol() const;
535 Expected<XCOFFCsectAuxRef> getXCOFFCsectAuxRef() const;
536
537private:
538 const XCOFFObjectFile *OwningObjectPtr;
539 const XCOFFSymbolEntry32 *Entry32 = nullptr;
540 const XCOFFSymbolEntry64 *Entry64 = nullptr;
3
Null pointer value stored to field 'Entry64'
541};
542
543class TBVectorExt {
544 uint16_t Data;
545 SmallString<32> VecParmsInfo;
546
547 TBVectorExt(StringRef TBvectorStrRef, Error &Err);
548
549public:
550 static Expected<TBVectorExt> create(StringRef TBvectorStrRef);
551 uint8_t getNumberOfVRSaved() const;
552 bool isVRSavedOnStack() const;
553 bool hasVarArgs() const;
554 uint8_t getNumberOfVectorParms() const;
555 bool hasVMXInstruction() const;
556 SmallString<32> getVectorParmsInfo() const { return VecParmsInfo; };
557};
558
559/// This class provides methods to extract traceback table data from a buffer.
560/// The various accessors may reference the buffer provided via the constructor.
561
562class XCOFFTracebackTable {
563 const uint8_t *const TBPtr;
564 Optional<SmallString<32>> ParmsType;
565 Optional<uint32_t> TraceBackTableOffset;
566 Optional<uint32_t> HandlerMask;
567 Optional<uint32_t> NumOfCtlAnchors;
568 Optional<SmallVector<uint32_t, 8>> ControlledStorageInfoDisp;
569 Optional<StringRef> FunctionName;
570 Optional<uint8_t> AllocaRegister;
571 Optional<TBVectorExt> VecExt;
572 Optional<uint8_t> ExtensionTable;
573
574 XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size, Error &Err);
575public:
576 /// Parse an XCOFF Traceback Table from \a Ptr with \a Size bytes.
577 /// Returns an XCOFFTracebackTable upon successful parsing, otherwise an
578 /// Error is returned.
579 ///
580 /// \param[in] Ptr
581 /// A pointer that points just past the initial 4 bytes of zeros at the
582 /// beginning of an XCOFF Traceback Table.
583 ///
584 /// \param[in, out] Size
585 /// A pointer that points to the length of the XCOFF Traceback Table.
586 /// If the XCOFF Traceback Table is not parsed successfully or there are
587 /// extra bytes that are not recognized, \a Size will be updated to be the
588 /// size up to the end of the last successfully parsed field of the table.
589 static Expected<XCOFFTracebackTable> create(const uint8_t *Ptr,
590 uint64_t &Size);
591 uint8_t getVersion() const;
592 uint8_t getLanguageID() const;
593
594 bool isGlobalLinkage() const;
595 bool isOutOfLineEpilogOrPrologue() const;
596 bool hasTraceBackTableOffset() const;
597 bool isInternalProcedure() const;
598 bool hasControlledStorage() const;
599 bool isTOCless() const;
600 bool isFloatingPointPresent() const;
601 bool isFloatingPointOperationLogOrAbortEnabled() const;
602
603 bool isInterruptHandler() const;
604 bool isFuncNamePresent() const;
605 bool isAllocaUsed() const;
606 uint8_t getOnConditionDirective() const;
607 bool isCRSaved() const;
608 bool isLRSaved() const;
609
610 bool isBackChainStored() const;
611 bool isFixup() const;
612 uint8_t getNumOfFPRsSaved() const;
613
614 bool hasVectorInfo() const;
615 bool hasExtensionTable() const;
616 uint8_t getNumOfGPRsSaved() const;
617
618 uint8_t getNumberOfFixedParms() const;
619
620 uint8_t getNumberOfFPParms() const;
621 bool hasParmsOnStack() const;
622
623 const Optional<SmallString<32>> &getParmsType() const { return ParmsType; }
624 const Optional<uint32_t> &getTraceBackTableOffset() const {
625 return TraceBackTableOffset;
626 }
627 const Optional<uint32_t> &getHandlerMask() const { return HandlerMask; }
628 const Optional<uint32_t> &getNumOfCtlAnchors() { return NumOfCtlAnchors; }
629 const Optional<SmallVector<uint32_t, 8>> &getControlledStorageInfoDisp() {
630 return ControlledStorageInfoDisp;
631 }
632 const Optional<StringRef> &getFunctionName() const { return FunctionName; }
633 const Optional<uint8_t> &getAllocaRegister() const { return AllocaRegister; }
634 const Optional<TBVectorExt> &getVectorExt() const { return VecExt; }
635 const Optional<uint8_t> &getExtensionTable() const { return ExtensionTable; }
636};
637
638bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes);
639} // namespace object
640} // namespace llvm
641
642#endif // LLVM_OBJECT_XCOFFOBJECTFILE_H