1//===- COFFObjectFile.cpp - COFF 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 declares the COFFObjectFile class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm/ADT/ArrayRef.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/StringSwitch.h"
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Object/Binary.h"
18#include "llvm/Object/COFF.h"
19#include "llvm/Object/Error.h"
20#include "llvm/Object/ObjectFile.h"
21#include "llvm/Object/WindowsMachineFlag.h"
22#include "llvm/Support/BinaryStreamReader.h"
23#include "llvm/Support/Endian.h"
24#include "llvm/Support/Error.h"
25#include "llvm/Support/ErrorHandling.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemoryBufferRef.h"
28#include <algorithm>
29#include <cassert>
30#include <cinttypes>
31#include <cstddef>
32#include <cstring>
33#include <limits>
34#include <memory>
35#include <system_error>
36
37using namespace llvm;
38using namespace object;
39
40using support::ulittle16_t;
41using support::ulittle32_t;
42using support::ulittle64_t;
43using support::little16_t;
44
45// Returns false if size is greater than the buffer size. And sets ec.
46static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
47 if (M.getBufferSize() < Size) {
48 EC = object_error::unexpected_eof;
49 return false;
50 }
51 return true;
52}
53
54// Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
55// Returns unexpected_eof if error.
56template <typename T>
57static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr,
58 const uint64_t Size = sizeof(T)) {
59 uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
60 if (Error E = Binary::checkOffset(M, Addr, Size))
61 return E;
62 Obj = reinterpret_cast<const T *>(Addr);
63 return Error::success();
64}
65
66// Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67// prefixed slashes.
68static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69 assert(Str.size() <= 6 && "String too long, possible overflow.");
70 if (Str.size() > 6)
71 return true;
72
73 uint64_t Value = 0;
74 while (!Str.empty()) {
75 unsigned CharVal;
76 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77 CharVal = Str[0] - 'A';
78 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79 CharVal = Str[0] - 'a' + 26;
80 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81 CharVal = Str[0] - '0' + 52;
82 else if (Str[0] == '+') // 62
83 CharVal = 62;
84 else if (Str[0] == '/') // 63
85 CharVal = 63;
86 else
87 return true;
88
89 Value = (Value * 64) + CharVal;
90 Str = Str.substr(Start: 1);
91 }
92
93 if (Value > std::numeric_limits<uint32_t>::max())
94 return true;
95
96 Result = static_cast<uint32_t>(Value);
97 return false;
98}
99
100template <typename coff_symbol_type>
101const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102 const coff_symbol_type *Addr =
103 reinterpret_cast<const coff_symbol_type *>(Ref.p);
104
105 assert(!checkOffset(Data, reinterpret_cast<uintptr_t>(Addr), sizeof(*Addr)));
106#ifndef NDEBUG
107 // Verify that the symbol points to a valid entry in the symbol table.
108 uintptr_t Offset =
109 reinterpret_cast<uintptr_t>(Addr) - reinterpret_cast<uintptr_t>(base());
110
111 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
112 "Symbol did not point to the beginning of a symbol");
113#endif
114
115 return Addr;
116}
117
118const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
119 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120
121#ifndef NDEBUG
122 // Verify that the section points to a valid entry in the section table.
123 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
124 report_fatal_error("Section was outside of section table.");
125
126 uintptr_t Offset = reinterpret_cast<uintptr_t>(Addr) -
127 reinterpret_cast<uintptr_t>(SectionTable);
128 assert(Offset % sizeof(coff_section) == 0 &&
129 "Section did not point to the beginning of a section");
130#endif
131
132 return Addr;
133}
134
135void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
136 auto End = reinterpret_cast<uintptr_t>(StringTable);
137 if (SymbolTable16) {
138 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
139 Symb += 1 + Symb->NumberOfAuxSymbols;
140 Ref.p = std::min(a: reinterpret_cast<uintptr_t>(Symb), b: End);
141 } else if (SymbolTable32) {
142 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
143 Symb += 1 + Symb->NumberOfAuxSymbols;
144 Ref.p = std::min(a: reinterpret_cast<uintptr_t>(Symb), b: End);
145 } else {
146 llvm_unreachable("no symbol table pointer!");
147 }
148}
149
150Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
151 return getSymbolName(Symbol: getCOFFSymbol(Ref));
152}
153
154uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
155 return getCOFFSymbol(Ref).getValue();
156}
157
158uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
159 // MSVC/link.exe seems to align symbols to the next-power-of-2
160 // up to 32 bytes.
161 COFFSymbolRef Symb = getCOFFSymbol(Ref);
162 return std::min(a: uint64_t(32), b: PowerOf2Ceil(A: Symb.getValue()));
163}
164
165Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
166 uint64_t Result = cantFail(ValOrErr: getSymbolValue(Symb: Ref));
167 COFFSymbolRef Symb = getCOFFSymbol(Ref);
168 int32_t SectionNumber = Symb.getSectionNumber();
169
170 if (Symb.isAnyUndefined() || Symb.isCommon() ||
171 COFF::isReservedSectionNumber(SectionNumber))
172 return Result;
173
174 Expected<const coff_section *> Section = getSection(index: SectionNumber);
175 if (!Section)
176 return Section.takeError();
177 Result += (*Section)->VirtualAddress;
178
179 // The section VirtualAddress does not include ImageBase, and we want to
180 // return virtual addresses.
181 Result += getImageBase();
182
183 return Result;
184}
185
186Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
187 COFFSymbolRef Symb = getCOFFSymbol(Ref);
188 int32_t SectionNumber = Symb.getSectionNumber();
189
190 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
191 return SymbolRef::ST_Function;
192 if (Symb.isAnyUndefined())
193 return SymbolRef::ST_Unknown;
194 if (Symb.isCommon())
195 return SymbolRef::ST_Data;
196 if (Symb.isFileRecord())
197 return SymbolRef::ST_File;
198
199 // TODO: perhaps we need a new symbol type ST_Section.
200 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
201 return SymbolRef::ST_Debug;
202
203 if (!COFF::isReservedSectionNumber(SectionNumber))
204 return SymbolRef::ST_Data;
205
206 return SymbolRef::ST_Other;
207}
208
209Expected<uint32_t> COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
210 COFFSymbolRef Symb = getCOFFSymbol(Ref);
211 uint32_t Result = SymbolRef::SF_None;
212
213 if (Symb.isExternal() || Symb.isWeakExternal())
214 Result |= SymbolRef::SF_Global;
215
216 if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
217 Result |= SymbolRef::SF_Weak;
218 if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
219 Result |= SymbolRef::SF_Undefined;
220 }
221
222 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
223 Result |= SymbolRef::SF_Absolute;
224
225 if (Symb.isFileRecord())
226 Result |= SymbolRef::SF_FormatSpecific;
227
228 if (Symb.isSectionDefinition())
229 Result |= SymbolRef::SF_FormatSpecific;
230
231 if (Symb.isCommon())
232 Result |= SymbolRef::SF_Common;
233
234 if (Symb.isUndefined())
235 Result |= SymbolRef::SF_Undefined;
236
237 return Result;
238}
239
240uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
241 COFFSymbolRef Symb = getCOFFSymbol(Ref);
242 return Symb.getValue();
243}
244
245Expected<section_iterator>
246COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
247 COFFSymbolRef Symb = getCOFFSymbol(Ref);
248 if (COFF::isReservedSectionNumber(SectionNumber: Symb.getSectionNumber()))
249 return section_end();
250 Expected<const coff_section *> Sec = getSection(index: Symb.getSectionNumber());
251 if (!Sec)
252 return Sec.takeError();
253 DataRefImpl Ret;
254 Ret.p = reinterpret_cast<uintptr_t>(*Sec);
255 return section_iterator(SectionRef(Ret, this));
256}
257
258unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
259 COFFSymbolRef Symb = getCOFFSymbol(Ref: Sym.getRawDataRefImpl());
260 return Symb.getSectionNumber();
261}
262
263void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
264 const coff_section *Sec = toSec(Ref);
265 Sec += 1;
266 Ref.p = reinterpret_cast<uintptr_t>(Sec);
267}
268
269Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const {
270 const coff_section *Sec = toSec(Ref);
271 return getSectionName(Sec);
272}
273
274uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
275 const coff_section *Sec = toSec(Ref);
276 uint64_t Result = Sec->VirtualAddress;
277
278 // The section VirtualAddress does not include ImageBase, and we want to
279 // return virtual addresses.
280 Result += getImageBase();
281 return Result;
282}
283
284uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
285 return toSec(Ref: Sec) - SectionTable;
286}
287
288uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
289 return getSectionSize(Sec: toSec(Ref));
290}
291
292Expected<ArrayRef<uint8_t>>
293COFFObjectFile::getSectionContents(DataRefImpl Ref) const {
294 const coff_section *Sec = toSec(Ref);
295 ArrayRef<uint8_t> Res;
296 if (Error E = getSectionContents(Sec, Res))
297 return E;
298 return Res;
299}
300
301uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
302 const coff_section *Sec = toSec(Ref);
303 return Sec->getAlignment();
304}
305
306bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
307 return false;
308}
309
310bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
311 const coff_section *Sec = toSec(Ref);
312 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
313}
314
315bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
316 const coff_section *Sec = toSec(Ref);
317 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
318}
319
320bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
321 const coff_section *Sec = toSec(Ref);
322 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
323 COFF::IMAGE_SCN_MEM_READ |
324 COFF::IMAGE_SCN_MEM_WRITE;
325 return (Sec->Characteristics & BssFlags) == BssFlags;
326}
327
328// The .debug sections are the only debug sections for COFF
329// (\see MCObjectFileInfo.cpp).
330bool COFFObjectFile::isDebugSection(DataRefImpl Ref) const {
331 Expected<StringRef> SectionNameOrErr = getSectionName(Ref);
332 if (!SectionNameOrErr) {
333 // TODO: Report the error message properly.
334 consumeError(Err: SectionNameOrErr.takeError());
335 return false;
336 }
337 StringRef SectionName = SectionNameOrErr.get();
338 return SectionName.starts_with(Prefix: ".debug");
339}
340
341unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
342 uintptr_t Offset =
343 Sec.getRawDataRefImpl().p - reinterpret_cast<uintptr_t>(SectionTable);
344 assert((Offset % sizeof(coff_section)) == 0);
345 return (Offset / sizeof(coff_section)) + 1;
346}
347
348bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
349 const coff_section *Sec = toSec(Ref);
350 // In COFF, a virtual section won't have any in-file
351 // content, so the file pointer to the content will be zero.
352 return Sec->PointerToRawData == 0;
353}
354
355static uint32_t getNumberOfRelocations(const coff_section *Sec,
356 MemoryBufferRef M, const uint8_t *base) {
357 // The field for the number of relocations in COFF section table is only
358 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
359 // NumberOfRelocations field, and the actual relocation count is stored in the
360 // VirtualAddress field in the first relocation entry.
361 if (Sec->hasExtendedRelocations()) {
362 const coff_relocation *FirstReloc;
363 if (Error E = getObject(Obj&: FirstReloc, M,
364 Ptr: reinterpret_cast<const coff_relocation *>(
365 base + Sec->PointerToRelocations))) {
366 consumeError(Err: std::move(E));
367 return 0;
368 }
369 // -1 to exclude this first relocation entry.
370 return FirstReloc->VirtualAddress - 1;
371 }
372 return Sec->NumberOfRelocations;
373}
374
375static const coff_relocation *
376getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
377 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, base: Base);
378 if (!NumRelocs)
379 return nullptr;
380 auto begin = reinterpret_cast<const coff_relocation *>(
381 Base + Sec->PointerToRelocations);
382 if (Sec->hasExtendedRelocations()) {
383 // Skip the first relocation entry repurposed to store the number of
384 // relocations.
385 begin++;
386 }
387 if (auto E = Binary::checkOffset(M, Addr: reinterpret_cast<uintptr_t>(begin),
388 Size: sizeof(coff_relocation) * NumRelocs)) {
389 consumeError(Err: std::move(E));
390 return nullptr;
391 }
392 return begin;
393}
394
395relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
396 const coff_section *Sec = toSec(Ref);
397 const coff_relocation *begin = getFirstReloc(Sec, M: Data, Base: base());
398 if (begin && Sec->VirtualAddress != 0)
399 report_fatal_error(reason: "sections with relocations should have an address of 0");
400 DataRefImpl Ret;
401 Ret.p = reinterpret_cast<uintptr_t>(begin);
402 return relocation_iterator(RelocationRef(Ret, this));
403}
404
405relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
406 const coff_section *Sec = toSec(Ref);
407 const coff_relocation *I = getFirstReloc(Sec, M: Data, Base: base());
408 if (I)
409 I += getNumberOfRelocations(Sec, M: Data, base: base());
410 DataRefImpl Ret;
411 Ret.p = reinterpret_cast<uintptr_t>(I);
412 return relocation_iterator(RelocationRef(Ret, this));
413}
414
415// Initialize the pointer to the symbol table.
416Error COFFObjectFile::initSymbolTablePtr() {
417 if (COFFHeader)
418 if (Error E = getObject(
419 Obj&: SymbolTable16, M: Data, Ptr: base() + getPointerToSymbolTable(),
420 Size: (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
421 return E;
422
423 if (COFFBigObjHeader)
424 if (Error E = getObject(
425 Obj&: SymbolTable32, M: Data, Ptr: base() + getPointerToSymbolTable(),
426 Size: (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
427 return E;
428
429 // Find string table. The first four byte of the string table contains the
430 // total size of the string table, including the size field itself. If the
431 // string table is empty, the value of the first four byte would be 4.
432 uint32_t StringTableOffset = getPointerToSymbolTable() +
433 getNumberOfSymbols() * getSymbolTableEntrySize();
434 const uint8_t *StringTableAddr = base() + StringTableOffset;
435 const ulittle32_t *StringTableSizePtr;
436 if (Error E = getObject(Obj&: StringTableSizePtr, M: Data, Ptr: StringTableAddr))
437 return E;
438 StringTableSize = *StringTableSizePtr;
439 if (Error E = getObject(Obj&: StringTable, M: Data, Ptr: StringTableAddr, Size: StringTableSize))
440 return E;
441
442 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
443 // tools like cvtres write a size of 0 for an empty table instead of 4.
444 if (StringTableSize < 4)
445 StringTableSize = 4;
446
447 // Check that the string table is null terminated if has any in it.
448 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
449 return createStringError(EC: object_error::parse_failed,
450 S: "string table missing null terminator");
451 return Error::success();
452}
453
454uint64_t COFFObjectFile::getImageBase() const {
455 if (PE32Header)
456 return PE32Header->ImageBase;
457 else if (PE32PlusHeader)
458 return PE32PlusHeader->ImageBase;
459 // This actually comes up in practice.
460 return 0;
461}
462
463// Returns the file offset for the given VA.
464Error COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
465 uint64_t ImageBase = getImageBase();
466 uint64_t Rva = Addr - ImageBase;
467 assert(Rva <= UINT32_MAX);
468 return getRvaPtr(Rva: (uint32_t)Rva, Res);
469}
470
471// Returns the file offset for the given RVA.
472Error COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res,
473 const char *ErrorContext) const {
474 for (const SectionRef &S : sections()) {
475 const coff_section *Section = getCOFFSection(Section: S);
476 uint32_t SectionStart = Section->VirtualAddress;
477 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
478 if (SectionStart <= Addr && Addr < SectionEnd) {
479 // A table/directory entry can be pointing to somewhere in a stripped
480 // section, in an object that went through `objcopy --only-keep-debug`.
481 // In this case we don't want to cause the parsing of the object file to
482 // fail, otherwise it will be impossible to use this object as debug info
483 // in LLDB. Return SectionStrippedError here so that
484 // COFFObjectFile::initialize can ignore the error.
485 // Somewhat common binaries may have RVAs pointing outside of the
486 // provided raw data. Instead of rejecting the binaries, just
487 // treat the section as stripped for these purposes.
488 if (Section->SizeOfRawData < Section->VirtualSize &&
489 Addr >= SectionStart + Section->SizeOfRawData) {
490 return make_error<SectionStrippedError>();
491 }
492 uint32_t Offset = Addr - SectionStart;
493 Res = reinterpret_cast<uintptr_t>(base()) + Section->PointerToRawData +
494 Offset;
495 return Error::success();
496 }
497 }
498 if (ErrorContext)
499 return createStringError(EC: object_error::parse_failed,
500 Fmt: "RVA 0x%" PRIx32 " for %s not found", Vals: Addr,
501 Vals: ErrorContext);
502 return createStringError(EC: object_error::parse_failed,
503 Fmt: "RVA 0x%" PRIx32 " not found", Vals: Addr);
504}
505
506Error COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
507 ArrayRef<uint8_t> &Contents,
508 const char *ErrorContext) const {
509 for (const SectionRef &S : sections()) {
510 const coff_section *Section = getCOFFSection(Section: S);
511 uint32_t SectionStart = Section->VirtualAddress;
512 // Check if this RVA is within the section bounds. Be careful about integer
513 // overflow.
514 uint32_t OffsetIntoSection = RVA - SectionStart;
515 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
516 Size <= Section->VirtualSize - OffsetIntoSection) {
517 uintptr_t Begin = reinterpret_cast<uintptr_t>(base()) +
518 Section->PointerToRawData + OffsetIntoSection;
519 Contents =
520 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
521 return Error::success();
522 }
523 }
524 if (ErrorContext)
525 return createStringError(EC: object_error::parse_failed,
526 Fmt: "RVA 0x%" PRIx32 " for %s not found", Vals: RVA,
527 Vals: ErrorContext);
528 return createStringError(EC: object_error::parse_failed,
529 Fmt: "RVA 0x%" PRIx32 " not found", Vals: RVA);
530}
531
532// Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
533// table entry.
534Error COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
535 StringRef &Name) const {
536 uintptr_t IntPtr = 0;
537 if (Error E = getRvaPtr(Addr: Rva, Res&: IntPtr))
538 return E;
539 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
540 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
541 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
542 return Error::success();
543}
544
545Error COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
546 const codeview::DebugInfo *&PDBInfo,
547 StringRef &PDBFileName) const {
548 ArrayRef<uint8_t> InfoBytes;
549 if (Error E =
550 getRvaAndSizeAsBytes(RVA: DebugDir->AddressOfRawData, Size: DebugDir->SizeOfData,
551 Contents&: InfoBytes, ErrorContext: "PDB info"))
552 return E;
553 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
554 return createStringError(EC: object_error::parse_failed, S: "PDB info too small");
555 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
556 InfoBytes = InfoBytes.drop_front(N: sizeof(*PDBInfo));
557 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
558 InfoBytes.size());
559 // Truncate the name at the first null byte. Ignore any padding.
560 PDBFileName = PDBFileName.split(Separator: '\0').first;
561 return Error::success();
562}
563
564Error COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
565 StringRef &PDBFileName) const {
566 for (const debug_directory &D : debug_directories())
567 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
568 return getDebugPDBInfo(DebugDir: &D, PDBInfo, PDBFileName);
569 // If we get here, there is no PDB info to return.
570 PDBInfo = nullptr;
571 PDBFileName = StringRef();
572 return Error::success();
573}
574
575// Find the import table.
576Error COFFObjectFile::initImportTablePtr() {
577 // First, we get the RVA of the import table. If the file lacks a pointer to
578 // the import table, do nothing.
579 const data_directory *DataEntry = getDataDirectory(index: COFF::IMPORT_TABLE);
580 if (!DataEntry)
581 return Error::success();
582
583 // Do nothing if the pointer to import table is NULL.
584 if (DataEntry->RelativeVirtualAddress == 0)
585 return Error::success();
586
587 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
588
589 // Find the section that contains the RVA. This is needed because the RVA is
590 // the import table's memory address which is different from its file offset.
591 uintptr_t IntPtr = 0;
592 if (Error E = getRvaPtr(Addr: ImportTableRva, Res&: IntPtr, ErrorContext: "import table"))
593 return E;
594 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
595 return E;
596 ImportDirectory = reinterpret_cast<
597 const coff_import_directory_table_entry *>(IntPtr);
598 return Error::success();
599}
600
601// Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
602Error COFFObjectFile::initDelayImportTablePtr() {
603 const data_directory *DataEntry =
604 getDataDirectory(index: COFF::DELAY_IMPORT_DESCRIPTOR);
605 if (!DataEntry)
606 return Error::success();
607 if (DataEntry->RelativeVirtualAddress == 0)
608 return Error::success();
609
610 uint32_t RVA = DataEntry->RelativeVirtualAddress;
611 NumberOfDelayImportDirectory = DataEntry->Size /
612 sizeof(delay_import_directory_table_entry) - 1;
613
614 uintptr_t IntPtr = 0;
615 if (Error E = getRvaPtr(Addr: RVA, Res&: IntPtr, ErrorContext: "delay import table"))
616 return E;
617 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
618 return E;
619
620 DelayImportDirectory = reinterpret_cast<
621 const delay_import_directory_table_entry *>(IntPtr);
622 return Error::success();
623}
624
625// Find the export table.
626Error COFFObjectFile::initExportTablePtr() {
627 // First, we get the RVA of the export table. If the file lacks a pointer to
628 // the export table, do nothing.
629 const data_directory *DataEntry = getDataDirectory(index: COFF::EXPORT_TABLE);
630 if (!DataEntry)
631 return Error::success();
632
633 // Do nothing if the pointer to export table is NULL.
634 if (DataEntry->RelativeVirtualAddress == 0)
635 return Error::success();
636
637 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
638 uintptr_t IntPtr = 0;
639 if (Error E = getRvaPtr(Addr: ExportTableRva, Res&: IntPtr, ErrorContext: "export table"))
640 return E;
641 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
642 return E;
643
644 ExportDirectory =
645 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
646 return Error::success();
647}
648
649Error COFFObjectFile::initBaseRelocPtr() {
650 const data_directory *DataEntry =
651 getDataDirectory(index: COFF::BASE_RELOCATION_TABLE);
652 if (!DataEntry)
653 return Error::success();
654 if (DataEntry->RelativeVirtualAddress == 0)
655 return Error::success();
656
657 uintptr_t IntPtr = 0;
658 if (Error E = getRvaPtr(Addr: DataEntry->RelativeVirtualAddress, Res&: IntPtr,
659 ErrorContext: "base reloc table"))
660 return E;
661 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
662 return E;
663
664 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
665 IntPtr);
666 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
667 IntPtr + DataEntry->Size);
668 // FIXME: Verify the section containing BaseRelocHeader has at least
669 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
670 return Error::success();
671}
672
673Error COFFObjectFile::initDebugDirectoryPtr() {
674 // Get the RVA of the debug directory. Do nothing if it does not exist.
675 const data_directory *DataEntry = getDataDirectory(index: COFF::DEBUG_DIRECTORY);
676 if (!DataEntry)
677 return Error::success();
678
679 // Do nothing if the RVA is NULL.
680 if (DataEntry->RelativeVirtualAddress == 0)
681 return Error::success();
682
683 // Check that the size is a multiple of the entry size.
684 if (DataEntry->Size % sizeof(debug_directory) != 0)
685 return createStringError(EC: object_error::parse_failed,
686 S: "debug directory has uneven size");
687
688 uintptr_t IntPtr = 0;
689 if (Error E = getRvaPtr(Addr: DataEntry->RelativeVirtualAddress, Res&: IntPtr,
690 ErrorContext: "debug directory"))
691 return E;
692 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
693 return E;
694
695 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
696 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
697 IntPtr + DataEntry->Size);
698 // FIXME: Verify the section containing DebugDirectoryBegin has at least
699 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
700 return Error::success();
701}
702
703Error COFFObjectFile::initTLSDirectoryPtr() {
704 // Get the RVA of the TLS directory. Do nothing if it does not exist.
705 const data_directory *DataEntry = getDataDirectory(index: COFF::TLS_TABLE);
706 if (!DataEntry)
707 return Error::success();
708
709 // Do nothing if the RVA is NULL.
710 if (DataEntry->RelativeVirtualAddress == 0)
711 return Error::success();
712
713 uint64_t DirSize =
714 is64() ? sizeof(coff_tls_directory64) : sizeof(coff_tls_directory32);
715
716 // Check that the size is correct.
717 if (DataEntry->Size != DirSize)
718 return createStringError(
719 EC: object_error::parse_failed,
720 Fmt: "TLS Directory size (%u) is not the expected size (%" PRIu64 ").",
721 Vals: static_cast<uint32_t>(DataEntry->Size), Vals: DirSize);
722
723 uintptr_t IntPtr = 0;
724 if (Error E =
725 getRvaPtr(Addr: DataEntry->RelativeVirtualAddress, Res&: IntPtr, ErrorContext: "TLS directory"))
726 return E;
727 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
728 return E;
729
730 if (is64())
731 TLSDirectory64 = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
732 else
733 TLSDirectory32 = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
734
735 return Error::success();
736}
737
738Error COFFObjectFile::initLoadConfigPtr() {
739 // Get the RVA of the debug directory. Do nothing if it does not exist.
740 const data_directory *DataEntry = getDataDirectory(index: COFF::LOAD_CONFIG_TABLE);
741 if (!DataEntry)
742 return Error::success();
743
744 // Do nothing if the RVA is NULL.
745 if (DataEntry->RelativeVirtualAddress == 0)
746 return Error::success();
747 uintptr_t IntPtr = 0;
748 if (Error E = getRvaPtr(Addr: DataEntry->RelativeVirtualAddress, Res&: IntPtr,
749 ErrorContext: "load config table"))
750 return E;
751 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: DataEntry->Size))
752 return E;
753
754 LoadConfig = (const void *)IntPtr;
755
756 if (is64()) {
757 auto Config = getLoadConfig64();
758 if (Config->Size >=
759 offsetof(coff_load_configuration64, CHPEMetadataPointer) +
760 sizeof(Config->CHPEMetadataPointer) &&
761 Config->CHPEMetadataPointer) {
762 uint64_t ChpeOff = Config->CHPEMetadataPointer;
763 if (Error E =
764 getRvaPtr(Addr: ChpeOff - getImageBase(), Res&: IntPtr, ErrorContext: "CHPE metadata"))
765 return E;
766 if (Error E = checkOffset(M: Data, Addr: IntPtr, Size: sizeof(*CHPEMetadata)))
767 return E;
768
769 CHPEMetadata = reinterpret_cast<const chpe_metadata *>(IntPtr);
770
771 // Validate CHPE metadata
772 if (CHPEMetadata->CodeMapCount) {
773 if (Error E = getRvaPtr(Addr: CHPEMetadata->CodeMap, Res&: IntPtr, ErrorContext: "CHPE code map"))
774 return E;
775 if (Error E = checkOffset(M: Data, Addr: IntPtr,
776 Size: CHPEMetadata->CodeMapCount *
777 sizeof(chpe_range_entry)))
778 return E;
779 }
780
781 if (CHPEMetadata->CodeRangesToEntryPointsCount) {
782 if (Error E = getRvaPtr(Addr: CHPEMetadata->CodeRangesToEntryPoints, Res&: IntPtr,
783 ErrorContext: "CHPE entry point ranges"))
784 return E;
785 if (Error E = checkOffset(M: Data, Addr: IntPtr,
786 Size: CHPEMetadata->CodeRangesToEntryPointsCount *
787 sizeof(chpe_code_range_entry)))
788 return E;
789 }
790
791 if (CHPEMetadata->RedirectionMetadataCount) {
792 if (Error E = getRvaPtr(Addr: CHPEMetadata->RedirectionMetadata, Res&: IntPtr,
793 ErrorContext: "CHPE redirection metadata"))
794 return E;
795 if (Error E = checkOffset(M: Data, Addr: IntPtr,
796 Size: CHPEMetadata->RedirectionMetadataCount *
797 sizeof(chpe_redirection_entry)))
798 return E;
799 }
800 }
801
802 if (Config->Size >=
803 offsetof(coff_load_configuration64, DynamicValueRelocTableSection) +
804 sizeof(Config->DynamicValueRelocTableSection))
805 if (Error E = initDynamicRelocPtr(SectionIndex: Config->DynamicValueRelocTableSection,
806 SectionOffset: Config->DynamicValueRelocTableOffset))
807 return E;
808 } else {
809 auto Config = getLoadConfig32();
810 if (Config->Size >=
811 offsetof(coff_load_configuration32, DynamicValueRelocTableSection) +
812 sizeof(Config->DynamicValueRelocTableSection)) {
813 if (Error E = initDynamicRelocPtr(SectionIndex: Config->DynamicValueRelocTableSection,
814 SectionOffset: Config->DynamicValueRelocTableOffset))
815 return E;
816 }
817 }
818 return Error::success();
819}
820
821Error COFFObjectFile::initDynamicRelocPtr(uint32_t SectionIndex,
822 uint32_t SectionOffset) {
823 Expected<const coff_section *> Section = getSection(index: SectionIndex);
824 if (!Section)
825 return Section.takeError();
826 if (!*Section)
827 return Error::success();
828
829 // Interpret and validate dynamic relocations.
830 ArrayRef<uint8_t> Contents;
831 if (Error E = getSectionContents(Sec: *Section, Res&: Contents))
832 return E;
833
834 Contents = Contents.drop_front(N: SectionOffset);
835 if (Contents.size() < sizeof(coff_dynamic_reloc_table))
836 return createStringError(EC: object_error::parse_failed,
837 S: "Too large DynamicValueRelocTableOffset (" +
838 Twine(SectionOffset) + ")");
839
840 DynamicRelocTable =
841 reinterpret_cast<const coff_dynamic_reloc_table *>(Contents.data());
842
843 if (DynamicRelocTable->Version != 1 && DynamicRelocTable->Version != 2)
844 return createStringError(EC: object_error::parse_failed,
845 S: "Unsupported dynamic relocations table version (" +
846 Twine(DynamicRelocTable->Version) + ")");
847 if (DynamicRelocTable->Size > Contents.size() - sizeof(*DynamicRelocTable))
848 return createStringError(EC: object_error::parse_failed,
849 S: "Indvalid dynamic relocations directory size (" +
850 Twine(DynamicRelocTable->Size) + ")");
851
852 for (auto DynReloc : dynamic_relocs()) {
853 if (Error e = DynReloc.validate())
854 return e;
855 }
856
857 return Error::success();
858}
859
860Expected<std::unique_ptr<COFFObjectFile>>
861COFFObjectFile::create(MemoryBufferRef Object) {
862 std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
863 if (Error E = Obj->initialize())
864 return E;
865 return std::move(Obj);
866}
867
868COFFObjectFile::COFFObjectFile(MemoryBufferRef Object)
869 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
870 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
871 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
872 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
873 ImportDirectory(nullptr), DelayImportDirectory(nullptr),
874 NumberOfDelayImportDirectory(0), ExportDirectory(nullptr),
875 BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
876 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr),
877 TLSDirectory32(nullptr), TLSDirectory64(nullptr) {}
878
879static Error ignoreStrippedErrors(Error E) {
880 if (E.isA<SectionStrippedError>()) {
881 consumeError(Err: std::move(E));
882 return Error::success();
883 }
884 return E;
885}
886
887Error COFFObjectFile::initialize() {
888 // Check that we at least have enough room for a header.
889 std::error_code EC;
890 if (!checkSize(M: Data, EC, Size: sizeof(coff_file_header)))
891 return errorCodeToError(EC);
892
893 // The current location in the file where we are looking at.
894 uint64_t CurPtr = 0;
895
896 // PE header is optional and is present only in executables. If it exists,
897 // it is placed right after COFF header.
898 bool HasPEHeader = false;
899
900 // Check if this is a PE/COFF file.
901 if (checkSize(M: Data, EC, Size: sizeof(dos_header) + sizeof(COFF::PEMagic))) {
902 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
903 // PE signature to find 'normal' COFF header.
904 const auto *DH = reinterpret_cast<const dos_header *>(base());
905 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
906 CurPtr = DH->AddressOfNewExeHeader;
907 // Check the PE magic bytes. ("PE\0\0")
908 if (memcmp(s1: base() + CurPtr, s2: COFF::PEMagic, n: sizeof(COFF::PEMagic)) != 0) {
909 return createStringError(EC: object_error::parse_failed,
910 S: "incorrect PE magic");
911 }
912 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
913 HasPEHeader = true;
914 }
915 }
916
917 if (Error E = getObject(Obj&: COFFHeader, M: Data, Ptr: base() + CurPtr))
918 return E;
919
920 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
921 // import libraries share a common prefix but bigobj is more restrictive.
922 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
923 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
924 checkSize(M: Data, EC, Size: sizeof(coff_bigobj_file_header))) {
925 if (Error E = getObject(Obj&: COFFBigObjHeader, M: Data, Ptr: base() + CurPtr))
926 return E;
927
928 // Verify that we are dealing with bigobj.
929 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
930 std::memcmp(s1: COFFBigObjHeader->UUID, s2: COFF::BigObjMagic,
931 n: sizeof(COFF::BigObjMagic)) == 0) {
932 COFFHeader = nullptr;
933 CurPtr += sizeof(coff_bigobj_file_header);
934 } else {
935 // It's not a bigobj.
936 COFFBigObjHeader = nullptr;
937 }
938 }
939 if (COFFHeader) {
940 // The prior checkSize call may have failed. This isn't a hard error
941 // because we were just trying to sniff out bigobj.
942 EC = std::error_code();
943 CurPtr += sizeof(coff_file_header);
944
945 if (COFFHeader->isImportLibrary())
946 return errorCodeToError(EC);
947 }
948
949 if (HasPEHeader) {
950 const pe32_header *Header;
951 if (Error E = getObject(Obj&: Header, M: Data, Ptr: base() + CurPtr))
952 return E;
953
954 const uint8_t *DataDirAddr;
955 uint64_t DataDirSize;
956 if (Header->Magic == COFF::PE32Header::PE32) {
957 PE32Header = Header;
958 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
959 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
960 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
961 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
962 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
963 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
964 } else {
965 // It's neither PE32 nor PE32+.
966 return createStringError(EC: object_error::parse_failed,
967 S: "incorrect PE magic");
968 }
969 if (Error E = getObject(Obj&: DataDirectory, M: Data, Ptr: DataDirAddr, Size: DataDirSize))
970 return E;
971 }
972
973 if (COFFHeader)
974 CurPtr += COFFHeader->SizeOfOptionalHeader;
975
976 assert(COFFHeader || COFFBigObjHeader);
977
978 if (Error E =
979 getObject(Obj&: SectionTable, M: Data, Ptr: base() + CurPtr,
980 Size: (uint64_t)getNumberOfSections() * sizeof(coff_section)))
981 return E;
982
983 // Initialize the pointer to the symbol table.
984 if (getPointerToSymbolTable() != 0) {
985 if (Error E = initSymbolTablePtr()) {
986 // Recover from errors reading the symbol table.
987 consumeError(Err: std::move(E));
988 SymbolTable16 = nullptr;
989 SymbolTable32 = nullptr;
990 StringTable = nullptr;
991 StringTableSize = 0;
992 }
993 } else {
994 // We had better not have any symbols if we don't have a symbol table.
995 if (getNumberOfSymbols() != 0) {
996 return createStringError(EC: object_error::parse_failed,
997 S: "symbol table missing");
998 }
999 }
1000
1001 // Initialize the pointer to the beginning of the import table.
1002 if (Error E = ignoreStrippedErrors(E: initImportTablePtr()))
1003 return E;
1004 if (Error E = ignoreStrippedErrors(E: initDelayImportTablePtr()))
1005 return E;
1006
1007 // Initialize the pointer to the export table.
1008 if (Error E = ignoreStrippedErrors(E: initExportTablePtr()))
1009 return E;
1010
1011 // Initialize the pointer to the base relocation table.
1012 if (Error E = ignoreStrippedErrors(E: initBaseRelocPtr()))
1013 return E;
1014
1015 // Initialize the pointer to the debug directory.
1016 if (Error E = ignoreStrippedErrors(E: initDebugDirectoryPtr()))
1017 return E;
1018
1019 // Initialize the pointer to the TLS directory.
1020 if (Error E = ignoreStrippedErrors(E: initTLSDirectoryPtr()))
1021 return E;
1022
1023 if (Error E = ignoreStrippedErrors(E: initLoadConfigPtr()))
1024 return E;
1025
1026 return Error::success();
1027}
1028
1029basic_symbol_iterator COFFObjectFile::symbol_begin() const {
1030 DataRefImpl Ret;
1031 Ret.p = getSymbolTable();
1032 return basic_symbol_iterator(SymbolRef(Ret, this));
1033}
1034
1035basic_symbol_iterator COFFObjectFile::symbol_end() const {
1036 // The symbol table ends where the string table begins.
1037 DataRefImpl Ret;
1038 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
1039 return basic_symbol_iterator(SymbolRef(Ret, this));
1040}
1041
1042import_directory_iterator COFFObjectFile::import_directory_begin() const {
1043 if (!ImportDirectory)
1044 return import_directory_end();
1045 if (ImportDirectory->isNull())
1046 return import_directory_end();
1047 return import_directory_iterator(
1048 ImportDirectoryEntryRef(ImportDirectory, 0, this));
1049}
1050
1051import_directory_iterator COFFObjectFile::import_directory_end() const {
1052 return import_directory_iterator(
1053 ImportDirectoryEntryRef(nullptr, -1, this));
1054}
1055
1056delay_import_directory_iterator
1057COFFObjectFile::delay_import_directory_begin() const {
1058 return delay_import_directory_iterator(
1059 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
1060}
1061
1062delay_import_directory_iterator
1063COFFObjectFile::delay_import_directory_end() const {
1064 return delay_import_directory_iterator(
1065 DelayImportDirectoryEntryRef(
1066 DelayImportDirectory, NumberOfDelayImportDirectory, this));
1067}
1068
1069export_directory_iterator COFFObjectFile::export_directory_begin() const {
1070 return export_directory_iterator(
1071 ExportDirectoryEntryRef(ExportDirectory, 0, this));
1072}
1073
1074export_directory_iterator COFFObjectFile::export_directory_end() const {
1075 if (!ExportDirectory)
1076 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
1077 ExportDirectoryEntryRef Ref(ExportDirectory,
1078 ExportDirectory->AddressTableEntries, this);
1079 return export_directory_iterator(Ref);
1080}
1081
1082section_iterator COFFObjectFile::section_begin() const {
1083 DataRefImpl Ret;
1084 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
1085 return section_iterator(SectionRef(Ret, this));
1086}
1087
1088section_iterator COFFObjectFile::section_end() const {
1089 DataRefImpl Ret;
1090 int NumSections =
1091 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
1092 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
1093 return section_iterator(SectionRef(Ret, this));
1094}
1095
1096base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
1097 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
1098}
1099
1100base_reloc_iterator COFFObjectFile::base_reloc_end() const {
1101 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
1102}
1103
1104dynamic_reloc_iterator COFFObjectFile::dynamic_reloc_begin() const {
1105 const void *Header = DynamicRelocTable ? DynamicRelocTable + 1 : nullptr;
1106 return dynamic_reloc_iterator(DynamicRelocRef(Header, this));
1107}
1108
1109dynamic_reloc_iterator COFFObjectFile::dynamic_reloc_end() const {
1110 const void *Header = nullptr;
1111 if (DynamicRelocTable)
1112 Header = reinterpret_cast<const uint8_t *>(DynamicRelocTable + 1) +
1113 DynamicRelocTable->Size;
1114 return dynamic_reloc_iterator(DynamicRelocRef(Header, this));
1115}
1116
1117uint8_t COFFObjectFile::getBytesInAddress() const {
1118 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
1119}
1120
1121StringRef COFFObjectFile::getFileFormatName() const {
1122 switch(getMachine()) {
1123 case COFF::IMAGE_FILE_MACHINE_I386:
1124 return "COFF-i386";
1125 case COFF::IMAGE_FILE_MACHINE_AMD64:
1126 return "COFF-x86-64";
1127 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1128 return "COFF-ARM";
1129 case COFF::IMAGE_FILE_MACHINE_ARM64:
1130 return "COFF-ARM64";
1131 case COFF::IMAGE_FILE_MACHINE_ARM64EC:
1132 return "COFF-ARM64EC";
1133 case COFF::IMAGE_FILE_MACHINE_ARM64X:
1134 return "COFF-ARM64X";
1135 case COFF::IMAGE_FILE_MACHINE_R4000:
1136 return "COFF-MIPS";
1137 default:
1138 return "COFF-<unknown arch>";
1139 }
1140}
1141
1142Triple::ArchType COFFObjectFile::getArch() const {
1143 return getMachineArchType(machine: getMachine());
1144}
1145
1146Expected<uint64_t> COFFObjectFile::getStartAddress() const {
1147 if (PE32Header)
1148 return PE32Header->AddressOfEntryPoint;
1149 return 0;
1150}
1151
1152iterator_range<import_directory_iterator>
1153COFFObjectFile::import_directories() const {
1154 return make_range(x: import_directory_begin(), y: import_directory_end());
1155}
1156
1157iterator_range<delay_import_directory_iterator>
1158COFFObjectFile::delay_import_directories() const {
1159 return make_range(x: delay_import_directory_begin(),
1160 y: delay_import_directory_end());
1161}
1162
1163iterator_range<export_directory_iterator>
1164COFFObjectFile::export_directories() const {
1165 return make_range(x: export_directory_begin(), y: export_directory_end());
1166}
1167
1168iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
1169 return make_range(x: base_reloc_begin(), y: base_reloc_end());
1170}
1171
1172iterator_range<dynamic_reloc_iterator> COFFObjectFile::dynamic_relocs() const {
1173 return make_range(x: dynamic_reloc_begin(), y: dynamic_reloc_end());
1174}
1175
1176const data_directory *COFFObjectFile::getDataDirectory(uint32_t Index) const {
1177 if (!DataDirectory)
1178 return nullptr;
1179 assert(PE32Header || PE32PlusHeader);
1180 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
1181 : PE32PlusHeader->NumberOfRvaAndSize;
1182 if (Index >= NumEnt)
1183 return nullptr;
1184 return &DataDirectory[Index];
1185}
1186
1187Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const {
1188 // Perhaps getting the section of a reserved section index should be an error,
1189 // but callers rely on this to return null.
1190 if (COFF::isReservedSectionNumber(SectionNumber: Index))
1191 return (const coff_section *)nullptr;
1192 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
1193 // We already verified the section table data, so no need to check again.
1194 return SectionTable + (Index - 1);
1195 }
1196 return createStringError(EC: object_error::parse_failed,
1197 S: "section index out of bounds");
1198}
1199
1200Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
1201 if (StringTableSize <= 4)
1202 // Tried to get a string from an empty string table.
1203 return createStringError(EC: object_error::parse_failed, S: "string table empty");
1204 if (Offset >= StringTableSize)
1205 return errorCodeToError(EC: object_error::unexpected_eof);
1206 return StringRef(StringTable + Offset);
1207}
1208
1209Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const {
1210 return getSymbolName(Symbol: Symbol.getGeneric());
1211}
1212
1213Expected<StringRef>
1214COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const {
1215 // Check for string table entry. First 4 bytes are 0.
1216 if (Symbol->Name.Offset.Zeroes == 0)
1217 return getString(Offset: Symbol->Name.Offset.Offset);
1218
1219 // Null terminated, let ::strlen figure out the length.
1220 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1221 return StringRef(Symbol->Name.ShortName);
1222
1223 // Not null terminated, use all 8 bytes.
1224 return StringRef(Symbol->Name.ShortName, COFF::NameSize);
1225}
1226
1227ArrayRef<uint8_t>
1228COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1229 const uint8_t *Aux = nullptr;
1230
1231 size_t SymbolSize = getSymbolTableEntrySize();
1232 if (Symbol.getNumberOfAuxSymbols() > 0) {
1233 // AUX data comes immediately after the symbol in COFF
1234 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1235#ifndef NDEBUG
1236 // Verify that the Aux symbol points to a valid entry in the symbol table.
1237 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1238 if (Offset < getPointerToSymbolTable() ||
1239 Offset >=
1240 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1241 report_fatal_error("Aux Symbol data was outside of symbol table.");
1242
1243 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1244 "Aux Symbol data did not point to the beginning of a symbol");
1245#endif
1246 }
1247 return ArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1248}
1249
1250uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const {
1251 uintptr_t Offset =
1252 reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
1253 assert(Offset % getSymbolTableEntrySize() == 0 &&
1254 "Symbol did not point to the beginning of a symbol");
1255 size_t Index = Offset / getSymbolTableEntrySize();
1256 assert(Index < getNumberOfSymbols());
1257 return Index;
1258}
1259
1260Expected<StringRef>
1261COFFObjectFile::getSectionName(const coff_section *Sec) const {
1262 StringRef Name = StringRef(Sec->Name, COFF::NameSize).split(Separator: '\0').first;
1263
1264 // Check for string table entry. First byte is '/'.
1265 if (Name.starts_with(Prefix: "/")) {
1266 uint32_t Offset;
1267 if (Name.starts_with(Prefix: "//")) {
1268 if (decodeBase64StringEntry(Str: Name.substr(Start: 2), Result&: Offset))
1269 return createStringError(EC: object_error::parse_failed,
1270 S: "invalid section name");
1271 } else {
1272 if (Name.substr(Start: 1).getAsInteger(Radix: 10, Result&: Offset))
1273 return createStringError(EC: object_error::parse_failed,
1274 S: "invalid section name");
1275 }
1276 return getString(Offset);
1277 }
1278
1279 return Name;
1280}
1281
1282uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1283 // SizeOfRawData and VirtualSize change what they represent depending on
1284 // whether or not we have an executable image.
1285 //
1286 // For object files, SizeOfRawData contains the size of section's data;
1287 // VirtualSize should be zero but isn't due to buggy COFF writers.
1288 //
1289 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1290 // actual section size is in VirtualSize. It is possible for VirtualSize to
1291 // be greater than SizeOfRawData; the contents past that point should be
1292 // considered to be zero.
1293 if (getDOSHeader())
1294 return std::min(a: Sec->VirtualSize, b: Sec->SizeOfRawData);
1295 return Sec->SizeOfRawData;
1296}
1297
1298Error COFFObjectFile::getSectionContents(const coff_section *Sec,
1299 ArrayRef<uint8_t> &Res) const {
1300 // In COFF, a virtual section won't have any in-file
1301 // content, so the file pointer to the content will be zero.
1302 if (Sec->PointerToRawData == 0)
1303 return Error::success();
1304 // The only thing that we need to verify is that the contents is contained
1305 // within the file bounds. We don't need to make sure it doesn't cover other
1306 // data, as there's nothing that says that is not allowed.
1307 uintptr_t ConStart =
1308 reinterpret_cast<uintptr_t>(base()) + Sec->PointerToRawData;
1309 uint32_t SectionSize = getSectionSize(Sec);
1310 if (Error E = checkOffset(M: Data, Addr: ConStart, Size: SectionSize))
1311 return E;
1312 Res = ArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1313 return Error::success();
1314}
1315
1316const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1317 return reinterpret_cast<const coff_relocation*>(Rel.p);
1318}
1319
1320void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1321 Rel.p = reinterpret_cast<uintptr_t>(
1322 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1323}
1324
1325uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1326 const coff_relocation *R = toRel(Rel);
1327 return R->VirtualAddress;
1328}
1329
1330symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1331 const coff_relocation *R = toRel(Rel);
1332 DataRefImpl Ref;
1333 if (R->SymbolTableIndex >= getNumberOfSymbols())
1334 return symbol_end();
1335 if (SymbolTable16)
1336 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1337 else if (SymbolTable32)
1338 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1339 else
1340 llvm_unreachable("no symbol table pointer!");
1341 return symbol_iterator(SymbolRef(Ref, this));
1342}
1343
1344uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1345 const coff_relocation* R = toRel(Rel);
1346 return R->Type;
1347}
1348
1349const coff_section *
1350COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1351 return toSec(Ref: Section.getRawDataRefImpl());
1352}
1353
1354COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1355 if (SymbolTable16)
1356 return toSymb<coff_symbol16>(Ref);
1357 if (SymbolTable32)
1358 return toSymb<coff_symbol32>(Ref);
1359 llvm_unreachable("no symbol table pointer!");
1360}
1361
1362COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1363 return getCOFFSymbol(Ref: Symbol.getRawDataRefImpl());
1364}
1365
1366const coff_relocation *
1367COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1368 return toRel(Rel: Reloc.getRawDataRefImpl());
1369}
1370
1371ArrayRef<coff_relocation>
1372COFFObjectFile::getRelocations(const coff_section *Sec) const {
1373 return {getFirstReloc(Sec, M: Data, Base: base()),
1374 getNumberOfRelocations(Sec, M: Data, base: base())};
1375}
1376
1377#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1378 case COFF::reloc_type: \
1379 return #reloc_type;
1380
1381StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
1382 switch (getArch()) {
1383 case Triple::x86_64:
1384 switch (Type) {
1385 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1386 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1387 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1388 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1389 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1390 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1391 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1392 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1393 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1394 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1395 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1396 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1397 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1398 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1399 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1400 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1401 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1402 default:
1403 return "Unknown";
1404 }
1405 break;
1406 case Triple::thumb:
1407 switch (Type) {
1408 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1409 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1410 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1411 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1412 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1413 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1414 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1415 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1416 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
1417 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1418 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1419 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1420 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1421 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1422 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1423 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1424 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
1425 default:
1426 return "Unknown";
1427 }
1428 break;
1429 case Triple::aarch64:
1430 switch (Type) {
1431 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1432 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1433 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1434 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1435 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1436 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1437 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1438 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1439 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1440 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1441 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1442 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1443 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1444 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1445 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1446 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1447 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1448 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
1449 default:
1450 return "Unknown";
1451 }
1452 break;
1453 case Triple::x86:
1454 switch (Type) {
1455 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1456 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1457 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1458 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1459 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1460 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1461 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1462 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1463 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1464 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1465 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1466 default:
1467 return "Unknown";
1468 }
1469 break;
1470 case Triple::mipsel:
1471 switch (Type) {
1472 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_ABSOLUTE);
1473 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFHALF);
1474 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFWORD);
1475 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_JMPADDR);
1476 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFHI);
1477 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFLO);
1478 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_GPREL);
1479 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_LITERAL);
1480 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECTION);
1481 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECREL);
1482 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECRELLO);
1483 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_SECRELHI);
1484 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_JMPADDR16);
1485 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_REFWORDNB);
1486 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_MIPS_PAIR);
1487 default:
1488 return "Unknown";
1489 }
1490 break;
1491 default:
1492 return "Unknown";
1493 }
1494}
1495
1496#undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1497
1498void COFFObjectFile::getRelocationTypeName(
1499 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1500 const coff_relocation *Reloc = toRel(Rel);
1501 StringRef Res = getRelocationTypeName(Type: Reloc->Type);
1502 Result.append(in_start: Res.begin(), in_end: Res.end());
1503}
1504
1505bool COFFObjectFile::isRelocatableObject() const {
1506 return !DataDirectory;
1507}
1508
1509StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
1510 return StringSwitch<StringRef>(Name)
1511 .Case(S: "eh_fram", Value: "eh_frame")
1512 .Default(Value: Name);
1513}
1514
1515std::unique_ptr<MemoryBuffer> COFFObjectFile::getHybridObjectView() const {
1516 if (getMachine() != COFF::IMAGE_FILE_MACHINE_ARM64X)
1517 return nullptr;
1518
1519 std::unique_ptr<WritableMemoryBuffer> HybridView;
1520
1521 for (auto DynReloc : dynamic_relocs()) {
1522 if (DynReloc.getType() != COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X)
1523 continue;
1524
1525 for (auto reloc : DynReloc.arm64x_relocs()) {
1526 if (!HybridView) {
1527 HybridView =
1528 WritableMemoryBuffer::getNewUninitMemBuffer(Size: Data.getBufferSize());
1529 memcpy(dest: HybridView->getBufferStart(), src: Data.getBufferStart(),
1530 n: Data.getBufferSize());
1531 }
1532
1533 uint32_t RVA = reloc.getRVA();
1534 void *Ptr;
1535 uintptr_t IntPtr;
1536 if (RVA & ~0xfff) {
1537 cantFail(Err: getRvaPtr(Addr: RVA, Res&: IntPtr));
1538 Ptr = HybridView->getBufferStart() + IntPtr -
1539 reinterpret_cast<uintptr_t>(base());
1540 } else {
1541 // PE header relocation.
1542 Ptr = HybridView->getBufferStart() + RVA;
1543 }
1544
1545 switch (reloc.getType()) {
1546 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
1547 memset(s: Ptr, c: 0, n: reloc.getSize());
1548 break;
1549 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: {
1550 auto Value = static_cast<ulittle64_t>(reloc.getValue());
1551 memcpy(dest: Ptr, src: &Value, n: reloc.getSize());
1552 break;
1553 }
1554 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
1555 *reinterpret_cast<ulittle32_t *>(Ptr) += reloc.getValue();
1556 break;
1557 }
1558 }
1559 }
1560 return HybridView;
1561}
1562
1563std::optional<MemoryBufferRef> COFFObjectFile::findHybridObjectSection() const {
1564 if (getDOSHeader() || getMachine() != COFF::IMAGE_FILE_MACHINE_ARM64)
1565 return std::nullopt;
1566
1567 // Search for the .obj.arm64ec section, which may be used to embed a full
1568 // ARM64EC object file into an ARM64 object file.
1569 for (SectionRef S : sections()) {
1570 Expected<StringRef> Name = S.getName();
1571 if (errorToBool(Err: Name.takeError()) || *Name != kArm64ECSectionName)
1572 continue;
1573
1574 Expected<StringRef> ContentsOrErr = S.getContents();
1575 if (errorToBool(Err: ContentsOrErr.takeError()) || ContentsOrErr->empty())
1576 continue;
1577 return MemoryBufferRef(*ContentsOrErr, getFileName());
1578 }
1579
1580 return std::nullopt;
1581}
1582
1583std::unique_ptr<MemoryBuffer> COFFObjectFile::stripHybridSection() const {
1584 if (getDOSHeader() || getMachine() != COFF::IMAGE_FILE_MACHINE_ARM64)
1585 return nullptr;
1586
1587 for (SectionRef S : sections()) {
1588 Expected<StringRef> Name = S.getName();
1589 if (errorToBool(Err: Name.takeError()) || *Name != kArm64ECSectionName)
1590 continue;
1591
1592 const coff_section *HybridSec = getCOFFSection(Section: S);
1593 if (!HybridSec->SizeOfRawData)
1594 continue;
1595
1596 // Copy the original buffer, skipping the hybrid section content.
1597 // The section itself is still present in the COFF headers, so section
1598 // indices are not affected by the change, but its size is reduced
1599 // to 0.
1600 std::unique_ptr<WritableMemoryBuffer> NativeView =
1601 WritableMemoryBuffer::getNewUninitMemBuffer(Size: Data.getBufferSize() -
1602 HybridSec->SizeOfRawData);
1603 uint32_t HybridEnd = HybridSec->PointerToRawData + HybridSec->SizeOfRawData;
1604 memcpy(dest: NativeView->getBufferStart(), src: Data.getBufferStart(),
1605 n: HybridSec->PointerToRawData);
1606 memcpy(dest: NativeView->getBufferStart() + HybridSec->PointerToRawData,
1607 src: Data.getBufferStart() + HybridEnd, n: Data.getBufferSize() - HybridEnd);
1608
1609 auto getTargetPtr = [&](const void *Ptr) {
1610 return NativeView->getBufferStart() +
1611 (reinterpret_cast<const char *>(Ptr) - Data.getBufferStart());
1612 };
1613
1614 // Adjust the COFF header, if necessary.
1615 if (COFFHeader) {
1616 auto Header =
1617 reinterpret_cast<coff_file_header *>(getTargetPtr(COFFHeader));
1618 if (Header->PointerToSymbolTable >= HybridEnd)
1619 Header->PointerToSymbolTable -= HybridSec->SizeOfRawData;
1620 } else {
1621 auto Header = reinterpret_cast<coff_bigobj_file_header *>(
1622 getTargetPtr(COFFBigObjHeader));
1623 if (Header->PointerToSymbolTable >= HybridEnd)
1624 Header->PointerToSymbolTable -= HybridSec->SizeOfRawData;
1625 }
1626
1627 // Adjust section headers.
1628 auto COFFSec = reinterpret_cast<coff_section *>(getTargetPtr(HybridSec));
1629 COFFSec->VirtualSize = 0;
1630 COFFSec->PointerToRawData = 0;
1631 COFFSec->SizeOfRawData = 0;
1632
1633 for (SectionRef Sec : sections()) {
1634 COFFSec =
1635 reinterpret_cast<coff_section *>(getTargetPtr(getCOFFSection(Section: Sec)));
1636 if (COFFSec->PointerToRawData >= HybridEnd)
1637 COFFSec->PointerToRawData -= HybridSec->SizeOfRawData;
1638 if (COFFSec->PointerToRelocations >= HybridEnd)
1639 COFFSec->PointerToRelocations -= HybridSec->SizeOfRawData;
1640 if (COFFSec->PointerToLinenumbers >= HybridEnd)
1641 COFFSec->PointerToLinenumbers -= HybridSec->SizeOfRawData;
1642 }
1643
1644 return NativeView;
1645 }
1646
1647 return nullptr;
1648}
1649
1650bool ImportDirectoryEntryRef::
1651operator==(const ImportDirectoryEntryRef &Other) const {
1652 return ImportTable == Other.ImportTable && Index == Other.Index;
1653}
1654
1655void ImportDirectoryEntryRef::moveNext() {
1656 ++Index;
1657 if (ImportTable[Index].isNull()) {
1658 Index = -1;
1659 ImportTable = nullptr;
1660 }
1661}
1662
1663Error ImportDirectoryEntryRef::getImportTableEntry(
1664 const coff_import_directory_table_entry *&Result) const {
1665 return getObject(Obj&: Result, M: OwningObject->Data, Ptr: ImportTable + Index);
1666}
1667
1668static imported_symbol_iterator
1669makeImportedSymbolIterator(const COFFObjectFile *Object,
1670 uintptr_t Ptr, int Index) {
1671 if (Object->getBytesInAddress() == 4) {
1672 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1673 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1674 }
1675 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1676 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1677}
1678
1679static imported_symbol_iterator
1680importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1681 uintptr_t IntPtr = 0;
1682 // FIXME: Handle errors.
1683 cantFail(Err: Object->getRvaPtr(Addr: RVA, Res&: IntPtr));
1684 return makeImportedSymbolIterator(Object, Ptr: IntPtr, Index: 0);
1685}
1686
1687static imported_symbol_iterator
1688importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1689 uintptr_t IntPtr = 0;
1690 // FIXME: Handle errors.
1691 cantFail(Err: Object->getRvaPtr(Addr: RVA, Res&: IntPtr));
1692 // Forward the pointer to the last entry which is null.
1693 int Index = 0;
1694 if (Object->getBytesInAddress() == 4) {
1695 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1696 while (*Entry++)
1697 ++Index;
1698 } else {
1699 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1700 while (*Entry++)
1701 ++Index;
1702 }
1703 return makeImportedSymbolIterator(Object, Ptr: IntPtr, Index);
1704}
1705
1706imported_symbol_iterator
1707ImportDirectoryEntryRef::imported_symbol_begin() const {
1708 return importedSymbolBegin(RVA: ImportTable[Index].ImportAddressTableRVA,
1709 Object: OwningObject);
1710}
1711
1712imported_symbol_iterator
1713ImportDirectoryEntryRef::imported_symbol_end() const {
1714 return importedSymbolEnd(RVA: ImportTable[Index].ImportAddressTableRVA,
1715 Object: OwningObject);
1716}
1717
1718iterator_range<imported_symbol_iterator>
1719ImportDirectoryEntryRef::imported_symbols() const {
1720 return make_range(x: imported_symbol_begin(), y: imported_symbol_end());
1721}
1722
1723imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1724 return importedSymbolBegin(RVA: ImportTable[Index].ImportLookupTableRVA,
1725 Object: OwningObject);
1726}
1727
1728imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1729 return importedSymbolEnd(RVA: ImportTable[Index].ImportLookupTableRVA,
1730 Object: OwningObject);
1731}
1732
1733iterator_range<imported_symbol_iterator>
1734ImportDirectoryEntryRef::lookup_table_symbols() const {
1735 return make_range(x: lookup_table_begin(), y: lookup_table_end());
1736}
1737
1738Error ImportDirectoryEntryRef::getName(StringRef &Result) const {
1739 uintptr_t IntPtr = 0;
1740 if (Error E = OwningObject->getRvaPtr(Addr: ImportTable[Index].NameRVA, Res&: IntPtr,
1741 ErrorContext: "import directory name"))
1742 return E;
1743 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1744 return Error::success();
1745}
1746
1747Error
1748ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1749 Result = ImportTable[Index].ImportLookupTableRVA;
1750 return Error::success();
1751}
1752
1753Error ImportDirectoryEntryRef::getImportAddressTableRVA(
1754 uint32_t &Result) const {
1755 Result = ImportTable[Index].ImportAddressTableRVA;
1756 return Error::success();
1757}
1758
1759bool DelayImportDirectoryEntryRef::
1760operator==(const DelayImportDirectoryEntryRef &Other) const {
1761 return Table == Other.Table && Index == Other.Index;
1762}
1763
1764void DelayImportDirectoryEntryRef::moveNext() {
1765 ++Index;
1766}
1767
1768imported_symbol_iterator
1769DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1770 return importedSymbolBegin(RVA: Table[Index].DelayImportNameTable,
1771 Object: OwningObject);
1772}
1773
1774imported_symbol_iterator
1775DelayImportDirectoryEntryRef::imported_symbol_end() const {
1776 return importedSymbolEnd(RVA: Table[Index].DelayImportNameTable,
1777 Object: OwningObject);
1778}
1779
1780iterator_range<imported_symbol_iterator>
1781DelayImportDirectoryEntryRef::imported_symbols() const {
1782 return make_range(x: imported_symbol_begin(), y: imported_symbol_end());
1783}
1784
1785Error DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1786 uintptr_t IntPtr = 0;
1787 if (Error E = OwningObject->getRvaPtr(Addr: Table[Index].Name, Res&: IntPtr,
1788 ErrorContext: "delay import directory name"))
1789 return E;
1790 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1791 return Error::success();
1792}
1793
1794Error DelayImportDirectoryEntryRef::getDelayImportTable(
1795 const delay_import_directory_table_entry *&Result) const {
1796 Result = &Table[Index];
1797 return Error::success();
1798}
1799
1800Error DelayImportDirectoryEntryRef::getImportAddress(int AddrIndex,
1801 uint64_t &Result) const {
1802 uint32_t RVA = Table[Index].DelayImportAddressTable +
1803 AddrIndex * (OwningObject->is64() ? 8 : 4);
1804 uintptr_t IntPtr = 0;
1805 if (Error E = OwningObject->getRvaPtr(Addr: RVA, Res&: IntPtr, ErrorContext: "import address"))
1806 return E;
1807 if (OwningObject->is64())
1808 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1809 else
1810 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1811 return Error::success();
1812}
1813
1814bool ExportDirectoryEntryRef::
1815operator==(const ExportDirectoryEntryRef &Other) const {
1816 return ExportTable == Other.ExportTable && Index == Other.Index;
1817}
1818
1819void ExportDirectoryEntryRef::moveNext() {
1820 ++Index;
1821}
1822
1823// Returns the name of the current export symbol. If the symbol is exported only
1824// by ordinal, the empty string is set as a result.
1825Error ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1826 uintptr_t IntPtr = 0;
1827 if (Error E =
1828 OwningObject->getRvaPtr(Addr: ExportTable->NameRVA, Res&: IntPtr, ErrorContext: "dll name"))
1829 return E;
1830 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1831 return Error::success();
1832}
1833
1834// Returns the starting ordinal number.
1835Error ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1836 Result = ExportTable->OrdinalBase;
1837 return Error::success();
1838}
1839
1840// Returns the export ordinal of the current export symbol.
1841Error ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1842 Result = ExportTable->OrdinalBase + Index;
1843 return Error::success();
1844}
1845
1846// Returns the address of the current export symbol.
1847Error ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1848 uintptr_t IntPtr = 0;
1849 if (Error EC = OwningObject->getRvaPtr(Addr: ExportTable->ExportAddressTableRVA,
1850 Res&: IntPtr, ErrorContext: "export address"))
1851 return EC;
1852 const export_address_table_entry *entry =
1853 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1854 Result = entry[Index].ExportRVA;
1855 return Error::success();
1856}
1857
1858// Returns the name of the current export symbol. If the symbol is exported only
1859// by ordinal, the empty string is set as a result.
1860Error
1861ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1862 uintptr_t IntPtr = 0;
1863 if (Error EC = OwningObject->getRvaPtr(Addr: ExportTable->OrdinalTableRVA, Res&: IntPtr,
1864 ErrorContext: "export ordinal table"))
1865 return EC;
1866 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1867
1868 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1869 int Offset = 0;
1870 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1871 I < E; ++I, ++Offset) {
1872 if (*I != Index)
1873 continue;
1874 if (Error EC = OwningObject->getRvaPtr(Addr: ExportTable->NamePointerRVA, Res&: IntPtr,
1875 ErrorContext: "export table entry"))
1876 return EC;
1877 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1878 if (Error EC = OwningObject->getRvaPtr(Addr: NamePtr[Offset], Res&: IntPtr,
1879 ErrorContext: "export symbol name"))
1880 return EC;
1881 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1882 return Error::success();
1883 }
1884 Result = "";
1885 return Error::success();
1886}
1887
1888Error ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1889 const data_directory *DataEntry =
1890 OwningObject->getDataDirectory(Index: COFF::EXPORT_TABLE);
1891 if (!DataEntry)
1892 return createStringError(EC: object_error::parse_failed,
1893 S: "export table missing");
1894 uint32_t RVA;
1895 if (auto EC = getExportRVA(Result&: RVA))
1896 return EC;
1897 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1898 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1899 Result = (Begin <= RVA && RVA < End);
1900 return Error::success();
1901}
1902
1903Error ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1904 uint32_t RVA;
1905 if (auto EC = getExportRVA(Result&: RVA))
1906 return EC;
1907 uintptr_t IntPtr = 0;
1908 if (auto EC = OwningObject->getRvaPtr(Addr: RVA, Res&: IntPtr, ErrorContext: "export forward target"))
1909 return EC;
1910 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1911 return Error::success();
1912}
1913
1914bool ImportedSymbolRef::
1915operator==(const ImportedSymbolRef &Other) const {
1916 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1917 && Index == Other.Index;
1918}
1919
1920void ImportedSymbolRef::moveNext() {
1921 ++Index;
1922}
1923
1924Error ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1925 uint32_t RVA;
1926 if (Entry32) {
1927 // If a symbol is imported only by ordinal, it has no name.
1928 if (Entry32[Index].isOrdinal())
1929 return Error::success();
1930 RVA = Entry32[Index].getHintNameRVA();
1931 } else {
1932 if (Entry64[Index].isOrdinal())
1933 return Error::success();
1934 RVA = Entry64[Index].getHintNameRVA();
1935 }
1936 uintptr_t IntPtr = 0;
1937 if (Error EC = OwningObject->getRvaPtr(Addr: RVA, Res&: IntPtr, ErrorContext: "import symbol name"))
1938 return EC;
1939 // +2 because the first two bytes is hint.
1940 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1941 return Error::success();
1942}
1943
1944Error ImportedSymbolRef::isOrdinal(bool &Result) const {
1945 if (Entry32)
1946 Result = Entry32[Index].isOrdinal();
1947 else
1948 Result = Entry64[Index].isOrdinal();
1949 return Error::success();
1950}
1951
1952Error ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1953 if (Entry32)
1954 Result = Entry32[Index].getHintNameRVA();
1955 else
1956 Result = Entry64[Index].getHintNameRVA();
1957 return Error::success();
1958}
1959
1960Error ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1961 uint32_t RVA;
1962 if (Entry32) {
1963 if (Entry32[Index].isOrdinal()) {
1964 Result = Entry32[Index].getOrdinal();
1965 return Error::success();
1966 }
1967 RVA = Entry32[Index].getHintNameRVA();
1968 } else {
1969 if (Entry64[Index].isOrdinal()) {
1970 Result = Entry64[Index].getOrdinal();
1971 return Error::success();
1972 }
1973 RVA = Entry64[Index].getHintNameRVA();
1974 }
1975 uintptr_t IntPtr = 0;
1976 if (Error EC = OwningObject->getRvaPtr(Addr: RVA, Res&: IntPtr, ErrorContext: "import symbol ordinal"))
1977 return EC;
1978 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1979 return Error::success();
1980}
1981
1982Expected<std::unique_ptr<COFFObjectFile>>
1983ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1984 return COFFObjectFile::create(Object);
1985}
1986
1987bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1988 return Header == Other.Header && Index == Other.Index;
1989}
1990
1991void BaseRelocRef::moveNext() {
1992 // Header->BlockSize is the size of the current block, including the
1993 // size of the header itself.
1994 uint32_t Size = sizeof(*Header) +
1995 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1996 if (Size == Header->BlockSize) {
1997 // .reloc contains a list of base relocation blocks. Each block
1998 // consists of the header followed by entries. The header contains
1999 // how many entories will follow. When we reach the end of the
2000 // current block, proceed to the next block.
2001 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
2002 reinterpret_cast<const uint8_t *>(Header) + Size);
2003 Index = 0;
2004 } else {
2005 ++Index;
2006 }
2007}
2008
2009Error BaseRelocRef::getType(uint8_t &Type) const {
2010 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
2011 Type = Entry[Index].getType();
2012 return Error::success();
2013}
2014
2015Error BaseRelocRef::getRVA(uint32_t &Result) const {
2016 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
2017 Result = Header->PageRVA + Entry[Index].getOffset();
2018 return Error::success();
2019}
2020
2021bool DynamicRelocRef::operator==(const DynamicRelocRef &Other) const {
2022 return Header == Other.Header;
2023}
2024
2025void DynamicRelocRef::moveNext() {
2026 switch (Obj->getDynamicRelocTable()->Version) {
2027 case 1:
2028 if (Obj->is64()) {
2029 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header);
2030 Header += sizeof(*H) + H->BaseRelocSize;
2031 } else {
2032 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header);
2033 Header += sizeof(*H) + H->BaseRelocSize;
2034 }
2035 break;
2036 case 2:
2037 if (Obj->is64()) {
2038 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header);
2039 Header += H->HeaderSize + H->FixupInfoSize;
2040 } else {
2041 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header);
2042 Header += H->HeaderSize + H->FixupInfoSize;
2043 }
2044 break;
2045 }
2046}
2047
2048uint32_t DynamicRelocRef::getType() const {
2049 switch (Obj->getDynamicRelocTable()->Version) {
2050 case 1:
2051 if (Obj->is64()) {
2052 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header);
2053 return H->Symbol;
2054 } else {
2055 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header);
2056 return H->Symbol;
2057 }
2058 break;
2059 case 2:
2060 if (Obj->is64()) {
2061 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header);
2062 return H->Symbol;
2063 } else {
2064 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header);
2065 return H->Symbol;
2066 }
2067 break;
2068 default:
2069 llvm_unreachable("invalid version");
2070 }
2071}
2072
2073void DynamicRelocRef::getContents(ArrayRef<uint8_t> &Ref) const {
2074 switch (Obj->getDynamicRelocTable()->Version) {
2075 case 1:
2076 if (Obj->is64()) {
2077 auto H = reinterpret_cast<const coff_dynamic_relocation64 *>(Header);
2078 Ref = ArrayRef(Header + sizeof(*H), H->BaseRelocSize);
2079 } else {
2080 auto H = reinterpret_cast<const coff_dynamic_relocation32 *>(Header);
2081 Ref = ArrayRef(Header + sizeof(*H), H->BaseRelocSize);
2082 }
2083 break;
2084 case 2:
2085 if (Obj->is64()) {
2086 auto H = reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header);
2087 Ref = ArrayRef(Header + H->HeaderSize, H->FixupInfoSize);
2088 } else {
2089 auto H = reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header);
2090 Ref = ArrayRef(Header + H->HeaderSize, H->FixupInfoSize);
2091 }
2092 break;
2093 }
2094}
2095
2096Error DynamicRelocRef::validate() const {
2097 const coff_dynamic_reloc_table *Table = Obj->getDynamicRelocTable();
2098 size_t ContentsSize =
2099 reinterpret_cast<const uint8_t *>(Table + 1) + Table->Size - Header;
2100 size_t HeaderSize;
2101 if (Table->Version == 1)
2102 HeaderSize = Obj->is64() ? sizeof(coff_dynamic_relocation64)
2103 : sizeof(coff_dynamic_relocation32);
2104 else
2105 HeaderSize = Obj->is64() ? sizeof(coff_dynamic_relocation64_v2)
2106 : sizeof(coff_dynamic_relocation32_v2);
2107 if (HeaderSize > ContentsSize)
2108 return createStringError(EC: object_error::parse_failed,
2109 S: "Unexpected end of dynamic relocations data");
2110
2111 if (Table->Version == 2) {
2112 size_t Size =
2113 Obj->is64()
2114 ? reinterpret_cast<const coff_dynamic_relocation64_v2 *>(Header)
2115 ->HeaderSize
2116 : reinterpret_cast<const coff_dynamic_relocation32_v2 *>(Header)
2117 ->HeaderSize;
2118 if (Size < HeaderSize || Size > ContentsSize)
2119 return createStringError(EC: object_error::parse_failed,
2120 S: "Invalid dynamic relocation header size (" +
2121 Twine(Size) + ")");
2122 HeaderSize = Size;
2123 }
2124
2125 ArrayRef<uint8_t> Contents;
2126 getContents(Ref&: Contents);
2127 if (Contents.size() > ContentsSize - HeaderSize)
2128 return createStringError(EC: object_error::parse_failed,
2129 S: "Too large dynamic relocation size (" +
2130 Twine(Contents.size()) + ")");
2131
2132 switch (getType()) {
2133 case COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X:
2134 for (auto Reloc : arm64x_relocs()) {
2135 if (Error E = Reloc.validate(Obj))
2136 return E;
2137 }
2138 break;
2139 }
2140
2141 return Error::success();
2142}
2143
2144arm64x_reloc_iterator DynamicRelocRef::arm64x_reloc_begin() const {
2145 assert(getType() == COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X);
2146 ArrayRef<uint8_t> Content;
2147 getContents(Ref&: Content);
2148 auto Header =
2149 reinterpret_cast<const coff_base_reloc_block_header *>(Content.begin());
2150 return arm64x_reloc_iterator(Arm64XRelocRef(Header));
2151}
2152
2153arm64x_reloc_iterator DynamicRelocRef::arm64x_reloc_end() const {
2154 assert(getType() == COFF::IMAGE_DYNAMIC_RELOCATION_ARM64X);
2155 ArrayRef<uint8_t> Content;
2156 getContents(Ref&: Content);
2157 auto Header =
2158 reinterpret_cast<const coff_base_reloc_block_header *>(Content.end());
2159 return arm64x_reloc_iterator(Arm64XRelocRef(Header, 0));
2160}
2161
2162iterator_range<arm64x_reloc_iterator> DynamicRelocRef::arm64x_relocs() const {
2163 return make_range(x: arm64x_reloc_begin(), y: arm64x_reloc_end());
2164}
2165
2166bool Arm64XRelocRef::operator==(const Arm64XRelocRef &Other) const {
2167 return Header == Other.Header && Index == Other.Index;
2168}
2169
2170uint8_t Arm64XRelocRef::getEntrySize() const {
2171 switch (getType()) {
2172 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
2173 return (1ull << getArg()) / sizeof(uint16_t) + 1;
2174 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
2175 return 2;
2176 default:
2177 return 1;
2178 }
2179}
2180
2181void Arm64XRelocRef::moveNext() {
2182 Index += getEntrySize();
2183 if (sizeof(*Header) + Index * sizeof(uint16_t) < Header->BlockSize &&
2184 !getReloc())
2185 ++Index; // Skip padding
2186 if (sizeof(*Header) + Index * sizeof(uint16_t) == Header->BlockSize) {
2187 // The end of the block, move to the next one.
2188 Header =
2189 reinterpret_cast<const coff_base_reloc_block_header *>(&getReloc());
2190 Index = 0;
2191 }
2192}
2193
2194uint8_t Arm64XRelocRef::getSize() const {
2195 switch (getType()) {
2196 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
2197 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
2198 return 1 << getArg();
2199 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
2200 return sizeof(uint32_t);
2201 }
2202 llvm_unreachable("Unknown Arm64XFixupType enum");
2203}
2204
2205uint64_t Arm64XRelocRef::getValue() const {
2206 auto Ptr = reinterpret_cast<const ulittle16_t *>(Header + 1) + Index + 1;
2207
2208 switch (getType()) {
2209 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE: {
2210 ulittle64_t Value(0);
2211 memcpy(dest: &Value, src: Ptr, n: getSize());
2212 return Value;
2213 }
2214 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA: {
2215 uint16_t arg = getArg();
2216 int delta = *Ptr;
2217
2218 if (arg & 1)
2219 delta = -delta;
2220 delta *= (arg & 2) ? 8 : 4;
2221 return delta;
2222 }
2223 default:
2224 return 0;
2225 }
2226}
2227
2228Error Arm64XRelocRef::validate(const COFFObjectFile *Obj) const {
2229 if (!Index) {
2230 const coff_dynamic_reloc_table *Table = Obj->getDynamicRelocTable();
2231 size_t ContentsSize = reinterpret_cast<const uint8_t *>(Table + 1) +
2232 Table->Size -
2233 reinterpret_cast<const uint8_t *>(Header);
2234 if (ContentsSize < sizeof(coff_base_reloc_block_header))
2235 return createStringError(EC: object_error::parse_failed,
2236 S: "Unexpected end of ARM64X relocations data");
2237 if (Header->BlockSize <= sizeof(*Header))
2238 return createStringError(EC: object_error::parse_failed,
2239 S: "ARM64X relocations block size (" +
2240 Twine(Header->BlockSize) + ") is too small");
2241 if (Header->BlockSize % sizeof(uint32_t))
2242 return createStringError(EC: object_error::parse_failed,
2243 S: "Unaligned ARM64X relocations block size (" +
2244 Twine(Header->BlockSize) + ")");
2245 if (Header->BlockSize > ContentsSize)
2246 return createStringError(EC: object_error::parse_failed,
2247 S: "ARM64X relocations block size (" +
2248 Twine(Header->BlockSize) + ") is too large");
2249 if (Header->PageRVA & 0xfff)
2250 return createStringError(EC: object_error::parse_failed,
2251 S: "Unaligned ARM64X relocations page RVA (" +
2252 Twine(Header->PageRVA) + ")");
2253 }
2254
2255 switch ((getReloc() >> 12) & 3) {
2256 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_ZEROFILL:
2257 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_DELTA:
2258 break;
2259 case COFF::IMAGE_DVRT_ARM64X_FIXUP_TYPE_VALUE:
2260 if (!getArg())
2261 return createStringError(EC: object_error::parse_failed,
2262 S: "Invalid ARM64X relocation value size (0)");
2263 break;
2264 default:
2265 return createStringError(EC: object_error::parse_failed,
2266 S: "Invalid relocation type");
2267 }
2268
2269 uint32_t RelocsSize =
2270 (Header->BlockSize - sizeof(*Header)) / sizeof(uint16_t);
2271 uint16_t EntrySize = getEntrySize();
2272 if (!getReloc() ||
2273 (Index + EntrySize + 1 < RelocsSize && !getReloc(Offset: EntrySize)))
2274 return createStringError(EC: object_error::parse_failed,
2275 S: "Unexpected ARM64X relocations terminator");
2276 if (Index + EntrySize > RelocsSize)
2277 return createStringError(EC: object_error::parse_failed,
2278 S: "Unexpected end of ARM64X relocations");
2279 if (getRVA() % getSize())
2280 return createStringError(EC: object_error::parse_failed,
2281 S: "Unaligned ARM64X relocation RVA (" +
2282 Twine(getRVA()) + ")");
2283 if (Header->PageRVA) {
2284 uintptr_t IntPtr;
2285 return Obj->getRvaPtr(Addr: getRVA() + getSize(), Res&: IntPtr, ErrorContext: "ARM64X reloc");
2286 }
2287 return Error::success();
2288}
2289
2290#define RETURN_IF_ERROR(Expr) \
2291 do { \
2292 Error E = (Expr); \
2293 if (E) \
2294 return std::move(E); \
2295 } while (0)
2296
2297Expected<ArrayRef<UTF16>>
2298ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
2299 BinaryStreamReader Reader = BinaryStreamReader(BBS);
2300 Reader.setOffset(Offset);
2301 uint16_t Length;
2302 RETURN_IF_ERROR(Reader.readInteger(Length));
2303 ArrayRef<UTF16> RawDirString;
2304 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
2305 return RawDirString;
2306}
2307
2308Expected<ArrayRef<UTF16>>
2309ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
2310 return getDirStringAtOffset(Offset: Entry.Identifier.getNameOffset());
2311}
2312
2313Expected<const coff_resource_dir_table &>
2314ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
2315 const coff_resource_dir_table *Table = nullptr;
2316
2317 BinaryStreamReader Reader(BBS);
2318 Reader.setOffset(Offset);
2319 RETURN_IF_ERROR(Reader.readObject(Table));
2320 assert(Table != nullptr);
2321 return *Table;
2322}
2323
2324Expected<const coff_resource_dir_entry &>
2325ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
2326 const coff_resource_dir_entry *Entry = nullptr;
2327
2328 BinaryStreamReader Reader(BBS);
2329 Reader.setOffset(Offset);
2330 RETURN_IF_ERROR(Reader.readObject(Entry));
2331 assert(Entry != nullptr);
2332 return *Entry;
2333}
2334
2335Expected<const coff_resource_data_entry &>
2336ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
2337 const coff_resource_data_entry *Entry = nullptr;
2338
2339 BinaryStreamReader Reader(BBS);
2340 Reader.setOffset(Offset);
2341 RETURN_IF_ERROR(Reader.readObject(Entry));
2342 assert(Entry != nullptr);
2343 return *Entry;
2344}
2345
2346Expected<const coff_resource_dir_table &>
2347ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
2348 assert(Entry.Offset.isSubDir());
2349 return getTableAtOffset(Offset: Entry.Offset.value());
2350}
2351
2352Expected<const coff_resource_data_entry &>
2353ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) {
2354 assert(!Entry.Offset.isSubDir());
2355 return getDataEntryAtOffset(Offset: Entry.Offset.value());
2356}
2357
2358Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
2359 return getTableAtOffset(Offset: 0);
2360}
2361
2362Expected<const coff_resource_dir_entry &>
2363ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table,
2364 uint32_t Index) {
2365 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
2366 return createStringError(EC: object_error::parse_failed, S: "index out of range");
2367 const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
2368 ptrdiff_t TableOffset = TablePtr - BBS.data().data();
2369 return getTableEntryAtOffset(Offset: TableOffset + sizeof(Table) +
2370 Index * sizeof(coff_resource_dir_entry));
2371}
2372
2373Error ResourceSectionRef::load(const COFFObjectFile *O) {
2374 for (const SectionRef &S : O->sections()) {
2375 Expected<StringRef> Name = S.getName();
2376 if (!Name)
2377 return Name.takeError();
2378
2379 if (*Name == ".rsrc" || *Name == ".rsrc$01")
2380 return load(O, S);
2381 }
2382 return createStringError(EC: object_error::parse_failed,
2383 S: "no resource section found");
2384}
2385
2386Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) {
2387 Obj = O;
2388 Section = S;
2389 Expected<StringRef> Contents = Section.getContents();
2390 if (!Contents)
2391 return Contents.takeError();
2392 BBS = BinaryByteStream(*Contents, llvm::endianness::little);
2393 const coff_section *COFFSect = Obj->getCOFFSection(Section);
2394 ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(Sec: COFFSect);
2395 Relocs.reserve(n: OrigRelocs.size());
2396 for (const coff_relocation &R : OrigRelocs)
2397 Relocs.push_back(x: &R);
2398 llvm::sort(C&: Relocs, Comp: [](const coff_relocation *A, const coff_relocation *B) {
2399 return A->VirtualAddress < B->VirtualAddress;
2400 });
2401 return Error::success();
2402}
2403
2404Expected<StringRef>
2405ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) {
2406 if (!Obj)
2407 return createStringError(EC: object_error::parse_failed, S: "no object provided");
2408
2409 // Find a potential relocation at the DataRVA field (first member of
2410 // the coff_resource_data_entry struct).
2411 const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
2412 ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
2413 coff_relocation RelocTarget{.VirtualAddress: ulittle32_t(EntryOffset), .SymbolTableIndex: ulittle32_t(0),
2414 .Type: ulittle16_t(0)};
2415 auto RelocsForOffset =
2416 std::equal_range(first: Relocs.begin(), last: Relocs.end(), val: &RelocTarget,
2417 comp: [](const coff_relocation *A, const coff_relocation *B) {
2418 return A->VirtualAddress < B->VirtualAddress;
2419 });
2420
2421 if (RelocsForOffset.first != RelocsForOffset.second) {
2422 // We found a relocation with the right offset. Check that it does have
2423 // the expected type.
2424 const coff_relocation &R = **RelocsForOffset.first;
2425 uint16_t RVAReloc;
2426 switch (Obj->getArch()) {
2427 case Triple::x86:
2428 RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
2429 break;
2430 case Triple::x86_64:
2431 RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
2432 break;
2433 case Triple::thumb:
2434 RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
2435 break;
2436 case Triple::aarch64:
2437 RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
2438 break;
2439 case Triple::mipsel:
2440 RVAReloc = COFF::IMAGE_REL_MIPS_REFWORDNB;
2441 break;
2442 default:
2443 return createStringError(EC: object_error::parse_failed,
2444 S: "unsupported architecture");
2445 }
2446 if (R.Type != RVAReloc)
2447 return createStringError(EC: object_error::parse_failed,
2448 S: "unexpected relocation type");
2449 // Get the relocation's symbol
2450 Expected<COFFSymbolRef> Sym = Obj->getSymbol(index: R.SymbolTableIndex);
2451 if (!Sym)
2452 return Sym.takeError();
2453 // And the symbol's section
2454 Expected<const coff_section *> Section =
2455 Obj->getSection(Index: Sym->getSectionNumber());
2456 if (!Section)
2457 return Section.takeError();
2458 // Add the initial value of DataRVA to the symbol's offset to find the
2459 // data it points at.
2460 uint64_t Offset = Entry.DataRVA + Sym->getValue();
2461 ArrayRef<uint8_t> Contents;
2462 if (Error E = Obj->getSectionContents(Sec: *Section, Res&: Contents))
2463 return E;
2464 if (Offset + Entry.DataSize > Contents.size())
2465 return createStringError(EC: object_error::parse_failed,
2466 S: "data outside of section");
2467 // Return a reference to the data inside the section.
2468 return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
2469 Entry.DataSize);
2470 } else {
2471 // Relocatable objects need a relocation for the DataRVA field.
2472 if (Obj->isRelocatableObject())
2473 return createStringError(EC: object_error::parse_failed,
2474 S: "no relocation found for DataRVA");
2475
2476 // Locate the section that contains the address that DataRVA points at.
2477 uint64_t VA = Entry.DataRVA + Obj->getImageBase();
2478 for (const SectionRef &S : Obj->sections()) {
2479 if (VA >= S.getAddress() &&
2480 VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
2481 uint64_t Offset = VA - S.getAddress();
2482 Expected<StringRef> Contents = S.getContents();
2483 if (!Contents)
2484 return Contents.takeError();
2485 return Contents->substr(Start: Offset, N: Entry.DataSize);
2486 }
2487 }
2488 return createStringError(EC: object_error::parse_failed,
2489 S: "address not found in image");
2490 }
2491}
2492