1 //===- COFFObjectFile.cpp - COFF object file implementation ---------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file declares the COFFObjectFile class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/iterator_range.h"
18 #include "llvm/BinaryFormat/COFF.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/BinaryStreamReader.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
36 #include <system_error>
39 using namespace object;
41 using support::ulittle16_t;
42 using support::ulittle32_t;
43 using support::ulittle64_t;
44 using support::little16_t;
46 // Returns false if size is greater than the buffer size. And sets ec.
47 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
48 if (M.getBufferSize() < Size) {
49 EC = object_error::unexpected_eof;
55 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
56 // Returns unexpected_eof if error.
58 static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr,
59 const uint64_t Size = sizeof(T)) {
60 uintptr_t Addr = uintptr_t(Ptr);
61 if (Error E = Binary::checkOffset(M, Addr, Size))
63 Obj = reinterpret_cast<const T *>(Addr);
64 return Error::success();
67 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
69 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
70 assert(Str.size() <= 6 && "String too long, possible overflow.");
75 while (!Str.empty()) {
77 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
78 CharVal = Str[0] - 'A';
79 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
80 CharVal = Str[0] - 'a' + 26;
81 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
82 CharVal = Str[0] - '0' + 52;
83 else if (Str[0] == '+') // 62
85 else if (Str[0] == '/') // 63
90 Value = (Value * 64) + CharVal;
94 if (Value > std::numeric_limits<uint32_t>::max())
97 Result = static_cast<uint32_t>(Value);
101 template <typename coff_symbol_type>
102 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
103 const coff_symbol_type *Addr =
104 reinterpret_cast<const coff_symbol_type *>(Ref.p);
106 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
108 // Verify that the symbol points to a valid entry in the symbol table.
109 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
111 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
112 "Symbol did not point to the beginning of a symbol");
118 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
119 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
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.");
126 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
127 assert(Offset % sizeof(coff_section) == 0 &&
128 "Section did not point to the beginning of a section");
134 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
135 auto End = reinterpret_cast<uintptr_t>(StringTable);
137 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
138 Symb += 1 + Symb->NumberOfAuxSymbols;
139 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
140 } else if (SymbolTable32) {
141 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
142 Symb += 1 + Symb->NumberOfAuxSymbols;
143 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
145 llvm_unreachable("no symbol table pointer!");
149 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
150 return getSymbolName(getCOFFSymbol(Ref));
153 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
154 return getCOFFSymbol(Ref).getValue();
157 uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
158 // MSVC/link.exe seems to align symbols to the next-power-of-2
160 COFFSymbolRef Symb = getCOFFSymbol(Ref);
161 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
164 Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
165 uint64_t Result = cantFail(getSymbolValue(Ref));
166 COFFSymbolRef Symb = getCOFFSymbol(Ref);
167 int32_t SectionNumber = Symb.getSectionNumber();
169 if (Symb.isAnyUndefined() || Symb.isCommon() ||
170 COFF::isReservedSectionNumber(SectionNumber))
173 Expected<const coff_section *> Section = getSection(SectionNumber);
175 return Section.takeError();
176 Result += (*Section)->VirtualAddress;
178 // The section VirtualAddress does not include ImageBase, and we want to
179 // return virtual addresses.
180 Result += getImageBase();
185 Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
186 COFFSymbolRef Symb = getCOFFSymbol(Ref);
187 int32_t SectionNumber = Symb.getSectionNumber();
189 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
190 return SymbolRef::ST_Function;
191 if (Symb.isAnyUndefined())
192 return SymbolRef::ST_Unknown;
194 return SymbolRef::ST_Data;
195 if (Symb.isFileRecord())
196 return SymbolRef::ST_File;
198 // TODO: perhaps we need a new symbol type ST_Section.
199 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
200 return SymbolRef::ST_Debug;
202 if (!COFF::isReservedSectionNumber(SectionNumber))
203 return SymbolRef::ST_Data;
205 return SymbolRef::ST_Other;
208 Expected<uint32_t> COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
209 COFFSymbolRef Symb = getCOFFSymbol(Ref);
210 uint32_t Result = SymbolRef::SF_None;
212 if (Symb.isExternal() || Symb.isWeakExternal())
213 Result |= SymbolRef::SF_Global;
215 if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
216 Result |= SymbolRef::SF_Weak;
217 if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
218 Result |= SymbolRef::SF_Undefined;
221 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
222 Result |= SymbolRef::SF_Absolute;
224 if (Symb.isFileRecord())
225 Result |= SymbolRef::SF_FormatSpecific;
227 if (Symb.isSectionDefinition())
228 Result |= SymbolRef::SF_FormatSpecific;
231 Result |= SymbolRef::SF_Common;
233 if (Symb.isUndefined())
234 Result |= SymbolRef::SF_Undefined;
239 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
240 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 return Symb.getValue();
244 Expected<section_iterator>
245 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
246 COFFSymbolRef Symb = getCOFFSymbol(Ref);
247 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
248 return section_end();
249 Expected<const coff_section *> Sec = getSection(Symb.getSectionNumber());
251 return Sec.takeError();
253 Ret.p = reinterpret_cast<uintptr_t>(*Sec);
254 return section_iterator(SectionRef(Ret, this));
257 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
258 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
259 return Symb.getSectionNumber();
262 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
263 const coff_section *Sec = toSec(Ref);
265 Ref.p = reinterpret_cast<uintptr_t>(Sec);
268 Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const {
269 const coff_section *Sec = toSec(Ref);
270 return getSectionName(Sec);
273 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
274 const coff_section *Sec = toSec(Ref);
275 uint64_t Result = Sec->VirtualAddress;
277 // The section VirtualAddress does not include ImageBase, and we want to
278 // return virtual addresses.
279 Result += getImageBase();
283 uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
284 return toSec(Sec) - SectionTable;
287 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
288 return getSectionSize(toSec(Ref));
291 Expected<ArrayRef<uint8_t>>
292 COFFObjectFile::getSectionContents(DataRefImpl Ref) const {
293 const coff_section *Sec = toSec(Ref);
294 ArrayRef<uint8_t> Res;
295 if (Error E = getSectionContents(Sec, Res))
300 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
301 const coff_section *Sec = toSec(Ref);
302 return Sec->getAlignment();
305 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
309 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
310 const coff_section *Sec = toSec(Ref);
311 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
314 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
315 const coff_section *Sec = toSec(Ref);
316 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
319 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
320 const coff_section *Sec = toSec(Ref);
321 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
322 COFF::IMAGE_SCN_MEM_READ |
323 COFF::IMAGE_SCN_MEM_WRITE;
324 return (Sec->Characteristics & BssFlags) == BssFlags;
327 // The .debug sections are the only debug sections for COFF
328 // (\see MCObjectFileInfo.cpp).
329 bool COFFObjectFile::isDebugSection(StringRef SectionName) const {
330 return SectionName.startswith(".debug");
333 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
335 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
336 assert((Offset % sizeof(coff_section)) == 0);
337 return (Offset / sizeof(coff_section)) + 1;
340 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
341 const coff_section *Sec = toSec(Ref);
342 // In COFF, a virtual section won't have any in-file
343 // content, so the file pointer to the content will be zero.
344 return Sec->PointerToRawData == 0;
347 static uint32_t getNumberOfRelocations(const coff_section *Sec,
348 MemoryBufferRef M, const uint8_t *base) {
349 // The field for the number of relocations in COFF section table is only
350 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
351 // NumberOfRelocations field, and the actual relocation count is stored in the
352 // VirtualAddress field in the first relocation entry.
353 if (Sec->hasExtendedRelocations()) {
354 const coff_relocation *FirstReloc;
355 if (Error E = getObject(FirstReloc, M,
356 reinterpret_cast<const coff_relocation *>(
357 base + Sec->PointerToRelocations))) {
358 consumeError(std::move(E));
361 // -1 to exclude this first relocation entry.
362 return FirstReloc->VirtualAddress - 1;
364 return Sec->NumberOfRelocations;
367 static const coff_relocation *
368 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
369 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
372 auto begin = reinterpret_cast<const coff_relocation *>(
373 Base + Sec->PointerToRelocations);
374 if (Sec->hasExtendedRelocations()) {
375 // Skip the first relocation entry repurposed to store the number of
379 if (auto E = Binary::checkOffset(M, uintptr_t(begin),
380 sizeof(coff_relocation) * NumRelocs)) {
381 consumeError(std::move(E));
387 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
388 const coff_section *Sec = toSec(Ref);
389 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
390 if (begin && Sec->VirtualAddress != 0)
391 report_fatal_error("Sections with relocations should have an address of 0");
393 Ret.p = reinterpret_cast<uintptr_t>(begin);
394 return relocation_iterator(RelocationRef(Ret, this));
397 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
398 const coff_section *Sec = toSec(Ref);
399 const coff_relocation *I = getFirstReloc(Sec, Data, base());
401 I += getNumberOfRelocations(Sec, Data, base());
403 Ret.p = reinterpret_cast<uintptr_t>(I);
404 return relocation_iterator(RelocationRef(Ret, this));
407 // Initialize the pointer to the symbol table.
408 Error COFFObjectFile::initSymbolTablePtr() {
410 if (Error E = getObject(
411 SymbolTable16, Data, base() + getPointerToSymbolTable(),
412 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
415 if (COFFBigObjHeader)
416 if (Error E = getObject(
417 SymbolTable32, Data, base() + getPointerToSymbolTable(),
418 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
421 // Find string table. The first four byte of the string table contains the
422 // total size of the string table, including the size field itself. If the
423 // string table is empty, the value of the first four byte would be 4.
424 uint32_t StringTableOffset = getPointerToSymbolTable() +
425 getNumberOfSymbols() * getSymbolTableEntrySize();
426 const uint8_t *StringTableAddr = base() + StringTableOffset;
427 const ulittle32_t *StringTableSizePtr;
428 if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr))
430 StringTableSize = *StringTableSizePtr;
431 if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize))
434 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
435 // tools like cvtres write a size of 0 for an empty table instead of 4.
436 if (StringTableSize < 4)
439 // Check that the string table is null terminated if has any in it.
440 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
441 return errorCodeToError(object_error::parse_failed);
442 return Error::success();
445 uint64_t COFFObjectFile::getImageBase() const {
447 return PE32Header->ImageBase;
448 else if (PE32PlusHeader)
449 return PE32PlusHeader->ImageBase;
450 // This actually comes up in practice.
454 // Returns the file offset for the given VA.
455 Error COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
456 uint64_t ImageBase = getImageBase();
457 uint64_t Rva = Addr - ImageBase;
458 assert(Rva <= UINT32_MAX);
459 return getRvaPtr((uint32_t)Rva, Res);
462 // Returns the file offset for the given RVA.
463 Error COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
464 for (const SectionRef &S : sections()) {
465 const coff_section *Section = getCOFFSection(S);
466 uint32_t SectionStart = Section->VirtualAddress;
467 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
468 if (SectionStart <= Addr && Addr < SectionEnd) {
469 uint32_t Offset = Addr - SectionStart;
470 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
471 return Error::success();
474 return errorCodeToError(object_error::parse_failed);
477 Error COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
478 ArrayRef<uint8_t> &Contents) const {
479 for (const SectionRef &S : sections()) {
480 const coff_section *Section = getCOFFSection(S);
481 uint32_t SectionStart = Section->VirtualAddress;
482 // Check if this RVA is within the section bounds. Be careful about integer
484 uint32_t OffsetIntoSection = RVA - SectionStart;
485 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
486 Size <= Section->VirtualSize - OffsetIntoSection) {
488 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
490 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
491 return Error::success();
494 return errorCodeToError(object_error::parse_failed);
497 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
499 Error COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
500 StringRef &Name) const {
501 uintptr_t IntPtr = 0;
502 if (Error E = getRvaPtr(Rva, IntPtr))
504 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
505 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
506 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
507 return Error::success();
510 Error COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
511 const codeview::DebugInfo *&PDBInfo,
512 StringRef &PDBFileName) const {
513 ArrayRef<uint8_t> InfoBytes;
514 if (Error E = getRvaAndSizeAsBytes(
515 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
517 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
518 return errorCodeToError(object_error::parse_failed);
519 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
520 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
521 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
523 // Truncate the name at the first null byte. Ignore any padding.
524 PDBFileName = PDBFileName.split('\0').first;
525 return Error::success();
528 Error COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
529 StringRef &PDBFileName) const {
530 for (const debug_directory &D : debug_directories())
531 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
532 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
533 // If we get here, there is no PDB info to return.
535 PDBFileName = StringRef();
536 return Error::success();
539 // Find the import table.
540 Error COFFObjectFile::initImportTablePtr() {
541 // First, we get the RVA of the import table. If the file lacks a pointer to
542 // the import table, do nothing.
543 const data_directory *DataEntry = getDataDirectory(COFF::IMPORT_TABLE);
545 return Error::success();
547 // Do nothing if the pointer to import table is NULL.
548 if (DataEntry->RelativeVirtualAddress == 0)
549 return Error::success();
551 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
553 // Find the section that contains the RVA. This is needed because the RVA is
554 // the import table's memory address which is different from its file offset.
555 uintptr_t IntPtr = 0;
556 if (Error E = getRvaPtr(ImportTableRva, IntPtr))
558 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
560 ImportDirectory = reinterpret_cast<
561 const coff_import_directory_table_entry *>(IntPtr);
562 return Error::success();
565 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
566 Error COFFObjectFile::initDelayImportTablePtr() {
567 const data_directory *DataEntry =
568 getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR);
570 return Error::success();
571 if (DataEntry->RelativeVirtualAddress == 0)
572 return Error::success();
574 uint32_t RVA = DataEntry->RelativeVirtualAddress;
575 NumberOfDelayImportDirectory = DataEntry->Size /
576 sizeof(delay_import_directory_table_entry) - 1;
578 uintptr_t IntPtr = 0;
579 if (Error E = getRvaPtr(RVA, IntPtr))
581 DelayImportDirectory = reinterpret_cast<
582 const delay_import_directory_table_entry *>(IntPtr);
583 return Error::success();
586 // Find the export table.
587 Error COFFObjectFile::initExportTablePtr() {
588 // First, we get the RVA of the export table. If the file lacks a pointer to
589 // the export table, do nothing.
590 const data_directory *DataEntry = getDataDirectory(COFF::EXPORT_TABLE);
592 return Error::success();
594 // Do nothing if the pointer to export table is NULL.
595 if (DataEntry->RelativeVirtualAddress == 0)
596 return Error::success();
598 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
599 uintptr_t IntPtr = 0;
600 if (Error E = getRvaPtr(ExportTableRva, IntPtr))
603 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
604 return Error::success();
607 Error COFFObjectFile::initBaseRelocPtr() {
608 const data_directory *DataEntry =
609 getDataDirectory(COFF::BASE_RELOCATION_TABLE);
611 return Error::success();
612 if (DataEntry->RelativeVirtualAddress == 0)
613 return Error::success();
615 uintptr_t IntPtr = 0;
616 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
618 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
620 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
621 IntPtr + DataEntry->Size);
622 // FIXME: Verify the section containing BaseRelocHeader has at least
623 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
624 return Error::success();
627 Error COFFObjectFile::initDebugDirectoryPtr() {
628 // Get the RVA of the debug directory. Do nothing if it does not exist.
629 const data_directory *DataEntry = getDataDirectory(COFF::DEBUG_DIRECTORY);
631 return Error::success();
633 // Do nothing if the RVA is NULL.
634 if (DataEntry->RelativeVirtualAddress == 0)
635 return Error::success();
637 // Check that the size is a multiple of the entry size.
638 if (DataEntry->Size % sizeof(debug_directory) != 0)
639 return errorCodeToError(object_error::parse_failed);
641 uintptr_t IntPtr = 0;
642 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
644 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
645 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
646 IntPtr + DataEntry->Size);
647 // FIXME: Verify the section containing DebugDirectoryBegin has at least
648 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
649 return Error::success();
652 Error COFFObjectFile::initLoadConfigPtr() {
653 // Get the RVA of the debug directory. Do nothing if it does not exist.
654 const data_directory *DataEntry = getDataDirectory(COFF::LOAD_CONFIG_TABLE);
656 return Error::success();
658 // Do nothing if the RVA is NULL.
659 if (DataEntry->RelativeVirtualAddress == 0)
660 return Error::success();
661 uintptr_t IntPtr = 0;
662 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
665 LoadConfig = (const void *)IntPtr;
666 return Error::success();
669 Expected<std::unique_ptr<COFFObjectFile>>
670 COFFObjectFile::create(MemoryBufferRef Object) {
671 std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
672 if (Error E = Obj->initialize())
674 return std::move(Obj);
677 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object)
678 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
679 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
680 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
681 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
682 ImportDirectory(nullptr), DelayImportDirectory(nullptr),
683 NumberOfDelayImportDirectory(0), ExportDirectory(nullptr),
684 BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
685 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {}
687 Error COFFObjectFile::initialize() {
688 // Check that we at least have enough room for a header.
690 if (!checkSize(Data, EC, sizeof(coff_file_header)))
691 return errorCodeToError(EC);
693 // The current location in the file where we are looking at.
696 // PE header is optional and is present only in executables. If it exists,
697 // it is placed right after COFF header.
698 bool HasPEHeader = false;
700 // Check if this is a PE/COFF file.
701 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
702 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
703 // PE signature to find 'normal' COFF header.
704 const auto *DH = reinterpret_cast<const dos_header *>(base());
705 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
706 CurPtr = DH->AddressOfNewExeHeader;
707 // Check the PE magic bytes. ("PE\0\0")
708 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
709 return errorCodeToError(object_error::parse_failed);
711 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
716 if (Error E = getObject(COFFHeader, Data, base() + CurPtr))
719 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
720 // import libraries share a common prefix but bigobj is more restrictive.
721 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
722 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
723 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
724 if (Error E = getObject(COFFBigObjHeader, Data, base() + CurPtr))
727 // Verify that we are dealing with bigobj.
728 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
729 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
730 sizeof(COFF::BigObjMagic)) == 0) {
731 COFFHeader = nullptr;
732 CurPtr += sizeof(coff_bigobj_file_header);
734 // It's not a bigobj.
735 COFFBigObjHeader = nullptr;
739 // The prior checkSize call may have failed. This isn't a hard error
740 // because we were just trying to sniff out bigobj.
741 EC = std::error_code();
742 CurPtr += sizeof(coff_file_header);
744 if (COFFHeader->isImportLibrary())
745 return errorCodeToError(EC);
749 const pe32_header *Header;
750 if (Error E = getObject(Header, Data, base() + CurPtr))
753 const uint8_t *DataDirAddr;
754 uint64_t DataDirSize;
755 if (Header->Magic == COFF::PE32Header::PE32) {
757 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
758 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
759 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
760 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
761 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
762 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
764 // It's neither PE32 nor PE32+.
765 return errorCodeToError(object_error::parse_failed);
767 if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))
772 CurPtr += COFFHeader->SizeOfOptionalHeader;
774 assert(COFFHeader || COFFBigObjHeader);
777 getObject(SectionTable, Data, base() + CurPtr,
778 (uint64_t)getNumberOfSections() * sizeof(coff_section)))
781 // Initialize the pointer to the symbol table.
782 if (getPointerToSymbolTable() != 0) {
783 if (Error E = initSymbolTablePtr()) {
784 // Recover from errors reading the symbol table.
785 consumeError(std::move(E));
786 SymbolTable16 = nullptr;
787 SymbolTable32 = nullptr;
788 StringTable = nullptr;
792 // We had better not have any symbols if we don't have a symbol table.
793 if (getNumberOfSymbols() != 0) {
794 return errorCodeToError(object_error::parse_failed);
798 // Initialize the pointer to the beginning of the import table.
799 if (Error E = initImportTablePtr())
801 if (Error E = initDelayImportTablePtr())
804 // Initialize the pointer to the export table.
805 if (Error E = initExportTablePtr())
808 // Initialize the pointer to the base relocation table.
809 if (Error E = initBaseRelocPtr())
812 // Initialize the pointer to the export table.
813 if (Error E = initDebugDirectoryPtr())
816 if (Error E = initLoadConfigPtr())
819 return Error::success();
822 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
824 Ret.p = getSymbolTable();
825 return basic_symbol_iterator(SymbolRef(Ret, this));
828 basic_symbol_iterator COFFObjectFile::symbol_end() const {
829 // The symbol table ends where the string table begins.
831 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
832 return basic_symbol_iterator(SymbolRef(Ret, this));
835 import_directory_iterator COFFObjectFile::import_directory_begin() const {
836 if (!ImportDirectory)
837 return import_directory_end();
838 if (ImportDirectory->isNull())
839 return import_directory_end();
840 return import_directory_iterator(
841 ImportDirectoryEntryRef(ImportDirectory, 0, this));
844 import_directory_iterator COFFObjectFile::import_directory_end() const {
845 return import_directory_iterator(
846 ImportDirectoryEntryRef(nullptr, -1, this));
849 delay_import_directory_iterator
850 COFFObjectFile::delay_import_directory_begin() const {
851 return delay_import_directory_iterator(
852 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
855 delay_import_directory_iterator
856 COFFObjectFile::delay_import_directory_end() const {
857 return delay_import_directory_iterator(
858 DelayImportDirectoryEntryRef(
859 DelayImportDirectory, NumberOfDelayImportDirectory, this));
862 export_directory_iterator COFFObjectFile::export_directory_begin() const {
863 return export_directory_iterator(
864 ExportDirectoryEntryRef(ExportDirectory, 0, this));
867 export_directory_iterator COFFObjectFile::export_directory_end() const {
868 if (!ExportDirectory)
869 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
870 ExportDirectoryEntryRef Ref(ExportDirectory,
871 ExportDirectory->AddressTableEntries, this);
872 return export_directory_iterator(Ref);
875 section_iterator COFFObjectFile::section_begin() const {
877 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
878 return section_iterator(SectionRef(Ret, this));
881 section_iterator COFFObjectFile::section_end() const {
884 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
885 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
886 return section_iterator(SectionRef(Ret, this));
889 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
890 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
893 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
894 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
897 uint8_t COFFObjectFile::getBytesInAddress() const {
898 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
901 StringRef COFFObjectFile::getFileFormatName() const {
902 switch(getMachine()) {
903 case COFF::IMAGE_FILE_MACHINE_I386:
905 case COFF::IMAGE_FILE_MACHINE_AMD64:
906 return "COFF-x86-64";
907 case COFF::IMAGE_FILE_MACHINE_ARMNT:
909 case COFF::IMAGE_FILE_MACHINE_ARM64:
912 return "COFF-<unknown arch>";
916 Triple::ArchType COFFObjectFile::getArch() const {
917 switch (getMachine()) {
918 case COFF::IMAGE_FILE_MACHINE_I386:
920 case COFF::IMAGE_FILE_MACHINE_AMD64:
921 return Triple::x86_64;
922 case COFF::IMAGE_FILE_MACHINE_ARMNT:
923 return Triple::thumb;
924 case COFF::IMAGE_FILE_MACHINE_ARM64:
925 return Triple::aarch64;
927 return Triple::UnknownArch;
931 Expected<uint64_t> COFFObjectFile::getStartAddress() const {
933 return PE32Header->AddressOfEntryPoint;
937 iterator_range<import_directory_iterator>
938 COFFObjectFile::import_directories() const {
939 return make_range(import_directory_begin(), import_directory_end());
942 iterator_range<delay_import_directory_iterator>
943 COFFObjectFile::delay_import_directories() const {
944 return make_range(delay_import_directory_begin(),
945 delay_import_directory_end());
948 iterator_range<export_directory_iterator>
949 COFFObjectFile::export_directories() const {
950 return make_range(export_directory_begin(), export_directory_end());
953 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
954 return make_range(base_reloc_begin(), base_reloc_end());
957 const data_directory *COFFObjectFile::getDataDirectory(uint32_t Index) const {
960 assert(PE32Header || PE32PlusHeader);
961 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
962 : PE32PlusHeader->NumberOfRvaAndSize;
965 return &DataDirectory[Index];
968 Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const {
969 // Perhaps getting the section of a reserved section index should be an error,
970 // but callers rely on this to return null.
971 if (COFF::isReservedSectionNumber(Index))
972 return (const coff_section *)nullptr;
973 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
974 // We already verified the section table data, so no need to check again.
975 return SectionTable + (Index - 1);
977 return errorCodeToError(object_error::parse_failed);
980 Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
981 if (StringTableSize <= 4)
982 // Tried to get a string from an empty string table.
983 return errorCodeToError(object_error::parse_failed);
984 if (Offset >= StringTableSize)
985 return errorCodeToError(object_error::unexpected_eof);
986 return StringRef(StringTable + Offset);
989 Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const {
990 return getSymbolName(Symbol.getGeneric());
994 COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const {
995 // Check for string table entry. First 4 bytes are 0.
996 if (Symbol->Name.Offset.Zeroes == 0)
997 return getString(Symbol->Name.Offset.Offset);
999 // Null terminated, let ::strlen figure out the length.
1000 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1001 return StringRef(Symbol->Name.ShortName);
1003 // Not null terminated, use all 8 bytes.
1004 return StringRef(Symbol->Name.ShortName, COFF::NameSize);
1008 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1009 const uint8_t *Aux = nullptr;
1011 size_t SymbolSize = getSymbolTableEntrySize();
1012 if (Symbol.getNumberOfAuxSymbols() > 0) {
1013 // AUX data comes immediately after the symbol in COFF
1014 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1016 // Verify that the Aux symbol points to a valid entry in the symbol table.
1017 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1018 if (Offset < getPointerToSymbolTable() ||
1020 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1021 report_fatal_error("Aux Symbol data was outside of symbol table.");
1023 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1024 "Aux Symbol data did not point to the beginning of a symbol");
1027 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1030 uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const {
1032 reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
1033 assert(Offset % getSymbolTableEntrySize() == 0 &&
1034 "Symbol did not point to the beginning of a symbol");
1035 size_t Index = Offset / getSymbolTableEntrySize();
1036 assert(Index < getNumberOfSymbols());
1041 COFFObjectFile::getSectionName(const coff_section *Sec) const {
1043 if (Sec->Name[COFF::NameSize - 1] == 0)
1044 // Null terminated, let ::strlen figure out the length.
1047 // Not null terminated, use all 8 bytes.
1048 Name = StringRef(Sec->Name, COFF::NameSize);
1050 // Check for string table entry. First byte is '/'.
1051 if (Name.startswith("/")) {
1053 if (Name.startswith("//")) {
1054 if (decodeBase64StringEntry(Name.substr(2), Offset))
1055 return createStringError(object_error::parse_failed,
1056 "invalid section name");
1058 if (Name.substr(1).getAsInteger(10, Offset))
1059 return createStringError(object_error::parse_failed,
1060 "invalid section name");
1062 return getString(Offset);
1068 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1069 // SizeOfRawData and VirtualSize change what they represent depending on
1070 // whether or not we have an executable image.
1072 // For object files, SizeOfRawData contains the size of section's data;
1073 // VirtualSize should be zero but isn't due to buggy COFF writers.
1075 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1076 // actual section size is in VirtualSize. It is possible for VirtualSize to
1077 // be greater than SizeOfRawData; the contents past that point should be
1078 // considered to be zero.
1080 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1081 return Sec->SizeOfRawData;
1084 Error COFFObjectFile::getSectionContents(const coff_section *Sec,
1085 ArrayRef<uint8_t> &Res) const {
1086 // In COFF, a virtual section won't have any in-file
1087 // content, so the file pointer to the content will be zero.
1088 if (Sec->PointerToRawData == 0)
1089 return Error::success();
1090 // The only thing that we need to verify is that the contents is contained
1091 // within the file bounds. We don't need to make sure it doesn't cover other
1092 // data, as there's nothing that says that is not allowed.
1093 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1094 uint32_t SectionSize = getSectionSize(Sec);
1095 if (Error E = checkOffset(Data, ConStart, SectionSize))
1097 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1098 return Error::success();
1101 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1102 return reinterpret_cast<const coff_relocation*>(Rel.p);
1105 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1106 Rel.p = reinterpret_cast<uintptr_t>(
1107 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1110 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1111 const coff_relocation *R = toRel(Rel);
1112 return R->VirtualAddress;
1115 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1116 const coff_relocation *R = toRel(Rel);
1118 if (R->SymbolTableIndex >= getNumberOfSymbols())
1119 return symbol_end();
1121 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1122 else if (SymbolTable32)
1123 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1125 llvm_unreachable("no symbol table pointer!");
1126 return symbol_iterator(SymbolRef(Ref, this));
1129 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1130 const coff_relocation* R = toRel(Rel);
1134 const coff_section *
1135 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1136 return toSec(Section.getRawDataRefImpl());
1139 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1141 return toSymb<coff_symbol16>(Ref);
1143 return toSymb<coff_symbol32>(Ref);
1144 llvm_unreachable("no symbol table pointer!");
1147 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1148 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1151 const coff_relocation *
1152 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1153 return toRel(Reloc.getRawDataRefImpl());
1156 ArrayRef<coff_relocation>
1157 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1158 return {getFirstReloc(Sec, Data, base()),
1159 getNumberOfRelocations(Sec, Data, base())};
1162 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1163 case COFF::reloc_type: \
1166 StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
1167 switch (getMachine()) {
1168 case COFF::IMAGE_FILE_MACHINE_AMD64:
1170 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1171 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1172 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1173 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1174 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1175 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1176 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1177 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1178 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1179 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1180 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1181 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1182 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1183 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1184 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1191 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1193 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1195 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1196 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1197 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1198 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1199 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1200 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1208 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1209 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
1214 case COFF::IMAGE_FILE_MACHINE_ARM64:
1216 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1217 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1218 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1219 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1220 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1221 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1222 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1223 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1224 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1225 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1226 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1227 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1228 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1229 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1230 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1231 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1232 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1233 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
1238 case COFF::IMAGE_FILE_MACHINE_I386:
1240 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1241 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1242 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1243 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1244 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1245 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1246 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1247 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1248 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1249 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1250 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1260 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1262 void COFFObjectFile::getRelocationTypeName(
1263 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1264 const coff_relocation *Reloc = toRel(Rel);
1265 StringRef Res = getRelocationTypeName(Reloc->Type);
1266 Result.append(Res.begin(), Res.end());
1269 bool COFFObjectFile::isRelocatableObject() const {
1270 return !DataDirectory;
1273 StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
1274 return StringSwitch<StringRef>(Name)
1275 .Case("eh_fram", "eh_frame")
1279 bool ImportDirectoryEntryRef::
1280 operator==(const ImportDirectoryEntryRef &Other) const {
1281 return ImportTable == Other.ImportTable && Index == Other.Index;
1284 void ImportDirectoryEntryRef::moveNext() {
1286 if (ImportTable[Index].isNull()) {
1288 ImportTable = nullptr;
1292 Error ImportDirectoryEntryRef::getImportTableEntry(
1293 const coff_import_directory_table_entry *&Result) const {
1294 return getObject(Result, OwningObject->Data, ImportTable + Index);
1297 static imported_symbol_iterator
1298 makeImportedSymbolIterator(const COFFObjectFile *Object,
1299 uintptr_t Ptr, int Index) {
1300 if (Object->getBytesInAddress() == 4) {
1301 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1302 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1304 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1305 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1308 static imported_symbol_iterator
1309 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1310 uintptr_t IntPtr = 0;
1311 // FIXME: Handle errors.
1312 cantFail(Object->getRvaPtr(RVA, IntPtr));
1313 return makeImportedSymbolIterator(Object, IntPtr, 0);
1316 static imported_symbol_iterator
1317 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1318 uintptr_t IntPtr = 0;
1319 // FIXME: Handle errors.
1320 cantFail(Object->getRvaPtr(RVA, IntPtr));
1321 // Forward the pointer to the last entry which is null.
1323 if (Object->getBytesInAddress() == 4) {
1324 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1328 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1332 return makeImportedSymbolIterator(Object, IntPtr, Index);
1335 imported_symbol_iterator
1336 ImportDirectoryEntryRef::imported_symbol_begin() const {
1337 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1341 imported_symbol_iterator
1342 ImportDirectoryEntryRef::imported_symbol_end() const {
1343 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1347 iterator_range<imported_symbol_iterator>
1348 ImportDirectoryEntryRef::imported_symbols() const {
1349 return make_range(imported_symbol_begin(), imported_symbol_end());
1352 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1353 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1357 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1358 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1362 iterator_range<imported_symbol_iterator>
1363 ImportDirectoryEntryRef::lookup_table_symbols() const {
1364 return make_range(lookup_table_begin(), lookup_table_end());
1367 Error ImportDirectoryEntryRef::getName(StringRef &Result) const {
1368 uintptr_t IntPtr = 0;
1369 if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1371 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1372 return Error::success();
1376 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1377 Result = ImportTable[Index].ImportLookupTableRVA;
1378 return Error::success();
1381 Error ImportDirectoryEntryRef::getImportAddressTableRVA(
1382 uint32_t &Result) const {
1383 Result = ImportTable[Index].ImportAddressTableRVA;
1384 return Error::success();
1387 bool DelayImportDirectoryEntryRef::
1388 operator==(const DelayImportDirectoryEntryRef &Other) const {
1389 return Table == Other.Table && Index == Other.Index;
1392 void DelayImportDirectoryEntryRef::moveNext() {
1396 imported_symbol_iterator
1397 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1398 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1402 imported_symbol_iterator
1403 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1404 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1408 iterator_range<imported_symbol_iterator>
1409 DelayImportDirectoryEntryRef::imported_symbols() const {
1410 return make_range(imported_symbol_begin(), imported_symbol_end());
1413 Error DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1414 uintptr_t IntPtr = 0;
1415 if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1417 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1418 return Error::success();
1421 Error DelayImportDirectoryEntryRef::getDelayImportTable(
1422 const delay_import_directory_table_entry *&Result) const {
1423 Result = &Table[Index];
1424 return Error::success();
1427 Error DelayImportDirectoryEntryRef::getImportAddress(int AddrIndex,
1428 uint64_t &Result) const {
1429 uint32_t RVA = Table[Index].DelayImportAddressTable +
1430 AddrIndex * (OwningObject->is64() ? 8 : 4);
1431 uintptr_t IntPtr = 0;
1432 if (Error E = OwningObject->getRvaPtr(RVA, IntPtr))
1434 if (OwningObject->is64())
1435 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1437 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1438 return Error::success();
1441 bool ExportDirectoryEntryRef::
1442 operator==(const ExportDirectoryEntryRef &Other) const {
1443 return ExportTable == Other.ExportTable && Index == Other.Index;
1446 void ExportDirectoryEntryRef::moveNext() {
1450 // Returns the name of the current export symbol. If the symbol is exported only
1451 // by ordinal, the empty string is set as a result.
1452 Error ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1453 uintptr_t IntPtr = 0;
1454 if (Error E = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1456 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1457 return Error::success();
1460 // Returns the starting ordinal number.
1461 Error ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1462 Result = ExportTable->OrdinalBase;
1463 return Error::success();
1466 // Returns the export ordinal of the current export symbol.
1467 Error ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1468 Result = ExportTable->OrdinalBase + Index;
1469 return Error::success();
1472 // Returns the address of the current export symbol.
1473 Error ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1474 uintptr_t IntPtr = 0;
1476 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1478 const export_address_table_entry *entry =
1479 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1480 Result = entry[Index].ExportRVA;
1481 return Error::success();
1484 // Returns the name of the current export symbol. If the symbol is exported only
1485 // by ordinal, the empty string is set as a result.
1487 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1488 uintptr_t IntPtr = 0;
1490 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1492 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1494 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1496 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1497 I < E; ++I, ++Offset) {
1501 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1503 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1504 if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1506 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1507 return Error::success();
1510 return Error::success();
1513 Error ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1514 const data_directory *DataEntry =
1515 OwningObject->getDataDirectory(COFF::EXPORT_TABLE);
1517 return errorCodeToError(object_error::parse_failed);
1519 if (auto EC = getExportRVA(RVA))
1521 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1522 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1523 Result = (Begin <= RVA && RVA < End);
1524 return Error::success();
1527 Error ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1529 if (auto EC = getExportRVA(RVA))
1531 uintptr_t IntPtr = 0;
1532 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1534 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1535 return Error::success();
1538 bool ImportedSymbolRef::
1539 operator==(const ImportedSymbolRef &Other) const {
1540 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1541 && Index == Other.Index;
1544 void ImportedSymbolRef::moveNext() {
1548 Error ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1551 // If a symbol is imported only by ordinal, it has no name.
1552 if (Entry32[Index].isOrdinal())
1553 return Error::success();
1554 RVA = Entry32[Index].getHintNameRVA();
1556 if (Entry64[Index].isOrdinal())
1557 return Error::success();
1558 RVA = Entry64[Index].getHintNameRVA();
1560 uintptr_t IntPtr = 0;
1561 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
1563 // +2 because the first two bytes is hint.
1564 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1565 return Error::success();
1568 Error ImportedSymbolRef::isOrdinal(bool &Result) const {
1570 Result = Entry32[Index].isOrdinal();
1572 Result = Entry64[Index].isOrdinal();
1573 return Error::success();
1576 Error ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1578 Result = Entry32[Index].getHintNameRVA();
1580 Result = Entry64[Index].getHintNameRVA();
1581 return Error::success();
1584 Error ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1587 if (Entry32[Index].isOrdinal()) {
1588 Result = Entry32[Index].getOrdinal();
1589 return Error::success();
1591 RVA = Entry32[Index].getHintNameRVA();
1593 if (Entry64[Index].isOrdinal()) {
1594 Result = Entry64[Index].getOrdinal();
1595 return Error::success();
1597 RVA = Entry64[Index].getHintNameRVA();
1599 uintptr_t IntPtr = 0;
1600 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
1602 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1603 return Error::success();
1606 Expected<std::unique_ptr<COFFObjectFile>>
1607 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1608 return COFFObjectFile::create(Object);
1611 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1612 return Header == Other.Header && Index == Other.Index;
1615 void BaseRelocRef::moveNext() {
1616 // Header->BlockSize is the size of the current block, including the
1617 // size of the header itself.
1618 uint32_t Size = sizeof(*Header) +
1619 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1620 if (Size == Header->BlockSize) {
1621 // .reloc contains a list of base relocation blocks. Each block
1622 // consists of the header followed by entries. The header contains
1623 // how many entories will follow. When we reach the end of the
1624 // current block, proceed to the next block.
1625 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1626 reinterpret_cast<const uint8_t *>(Header) + Size);
1633 Error BaseRelocRef::getType(uint8_t &Type) const {
1634 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1635 Type = Entry[Index].getType();
1636 return Error::success();
1639 Error BaseRelocRef::getRVA(uint32_t &Result) const {
1640 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1641 Result = Header->PageRVA + Entry[Index].getOffset();
1642 return Error::success();
1645 #define RETURN_IF_ERROR(Expr) \
1649 return std::move(E); \
1652 Expected<ArrayRef<UTF16>>
1653 ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1654 BinaryStreamReader Reader = BinaryStreamReader(BBS);
1655 Reader.setOffset(Offset);
1657 RETURN_IF_ERROR(Reader.readInteger(Length));
1658 ArrayRef<UTF16> RawDirString;
1659 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1660 return RawDirString;
1663 Expected<ArrayRef<UTF16>>
1664 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1665 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1668 Expected<const coff_resource_dir_table &>
1669 ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1670 const coff_resource_dir_table *Table = nullptr;
1672 BinaryStreamReader Reader(BBS);
1673 Reader.setOffset(Offset);
1674 RETURN_IF_ERROR(Reader.readObject(Table));
1675 assert(Table != nullptr);
1679 Expected<const coff_resource_dir_entry &>
1680 ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
1681 const coff_resource_dir_entry *Entry = nullptr;
1683 BinaryStreamReader Reader(BBS);
1684 Reader.setOffset(Offset);
1685 RETURN_IF_ERROR(Reader.readObject(Entry));
1686 assert(Entry != nullptr);
1690 Expected<const coff_resource_data_entry &>
1691 ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
1692 const coff_resource_data_entry *Entry = nullptr;
1694 BinaryStreamReader Reader(BBS);
1695 Reader.setOffset(Offset);
1696 RETURN_IF_ERROR(Reader.readObject(Entry));
1697 assert(Entry != nullptr);
1701 Expected<const coff_resource_dir_table &>
1702 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1703 assert(Entry.Offset.isSubDir());
1704 return getTableAtOffset(Entry.Offset.value());
1707 Expected<const coff_resource_data_entry &>
1708 ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) {
1709 assert(!Entry.Offset.isSubDir());
1710 return getDataEntryAtOffset(Entry.Offset.value());
1713 Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1714 return getTableAtOffset(0);
1717 Expected<const coff_resource_dir_entry &>
1718 ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table,
1720 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1721 return createStringError(object_error::parse_failed, "index out of range");
1722 const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
1723 ptrdiff_t TableOffset = TablePtr - BBS.data().data();
1724 return getTableEntryAtOffset(TableOffset + sizeof(Table) +
1725 Index * sizeof(coff_resource_dir_entry));
1728 Error ResourceSectionRef::load(const COFFObjectFile *O) {
1729 for (const SectionRef &S : O->sections()) {
1730 Expected<StringRef> Name = S.getName();
1732 return Name.takeError();
1734 if (*Name == ".rsrc" || *Name == ".rsrc$01")
1737 return createStringError(object_error::parse_failed,
1738 "no resource section found");
1741 Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) {
1744 Expected<StringRef> Contents = Section.getContents();
1746 return Contents.takeError();
1747 BBS = BinaryByteStream(*Contents, support::little);
1748 const coff_section *COFFSect = Obj->getCOFFSection(Section);
1749 ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect);
1750 Relocs.reserve(OrigRelocs.size());
1751 for (const coff_relocation &R : OrigRelocs)
1752 Relocs.push_back(&R);
1753 std::sort(Relocs.begin(), Relocs.end(),
1754 [](const coff_relocation *A, const coff_relocation *B) {
1755 return A->VirtualAddress < B->VirtualAddress;
1757 return Error::success();
1761 ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) {
1763 return createStringError(object_error::parse_failed, "no object provided");
1765 // Find a potential relocation at the DataRVA field (first member of
1766 // the coff_resource_data_entry struct).
1767 const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
1768 ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
1769 coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0),
1771 auto RelocsForOffset =
1772 std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget,
1773 [](const coff_relocation *A, const coff_relocation *B) {
1774 return A->VirtualAddress < B->VirtualAddress;
1777 if (RelocsForOffset.first != RelocsForOffset.second) {
1778 // We found a relocation with the right offset. Check that it does have
1779 // the expected type.
1780 const coff_relocation &R = **RelocsForOffset.first;
1782 switch (Obj->getMachine()) {
1783 case COFF::IMAGE_FILE_MACHINE_I386:
1784 RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
1786 case COFF::IMAGE_FILE_MACHINE_AMD64:
1787 RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
1789 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1790 RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
1792 case COFF::IMAGE_FILE_MACHINE_ARM64:
1793 RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
1796 return createStringError(object_error::parse_failed,
1797 "unsupported architecture");
1799 if (R.Type != RVAReloc)
1800 return createStringError(object_error::parse_failed,
1801 "unexpected relocation type");
1802 // Get the relocation's symbol
1803 Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
1805 return Sym.takeError();
1806 // And the symbol's section
1807 Expected<const coff_section *> Section =
1808 Obj->getSection(Sym->getSectionNumber());
1810 return Section.takeError();
1811 // Add the initial value of DataRVA to the symbol's offset to find the
1812 // data it points at.
1813 uint64_t Offset = Entry.DataRVA + Sym->getValue();
1814 ArrayRef<uint8_t> Contents;
1815 if (Error E = Obj->getSectionContents(*Section, Contents))
1816 return std::move(E);
1817 if (Offset + Entry.DataSize > Contents.size())
1818 return createStringError(object_error::parse_failed,
1819 "data outside of section");
1820 // Return a reference to the data inside the section.
1821 return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
1824 // Relocatable objects need a relocation for the DataRVA field.
1825 if (Obj->isRelocatableObject())
1826 return createStringError(object_error::parse_failed,
1827 "no relocation found for DataRVA");
1829 // Locate the section that contains the address that DataRVA points at.
1830 uint64_t VA = Entry.DataRVA + Obj->getImageBase();
1831 for (const SectionRef &S : Obj->sections()) {
1832 if (VA >= S.getAddress() &&
1833 VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
1834 uint64_t Offset = VA - S.getAddress();
1835 Expected<StringRef> Contents = S.getContents();
1837 return Contents.takeError();
1838 return Contents->slice(Offset, Offset + Entry.DataSize);
1841 return createStringError(object_error::parse_failed,
1842 "address not found in image");