LLVM 17.0.0git
COFFObjectFile.cpp
Go to the documentation of this file.
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"
18#include "llvm/Object/Binary.h"
19#include "llvm/Object/COFF.h"
20#include "llvm/Object/Error.h"
23#include "llvm/Support/Endian.h"
24#include "llvm/Support/Error.h"
29#include <algorithm>
30#include <cassert>
31#include <cinttypes>
32#include <cstddef>
33#include <cstring>
34#include <limits>
35#include <memory>
36#include <system_error>
37
38using namespace llvm;
39using namespace object;
40
45
46// Returns false if size is greater than the buffer size. And sets ec.
47static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
48 if (M.getBufferSize() < Size) {
49 EC = object_error::unexpected_eof;
50 return false;
51 }
52 return true;
53}
54
55// Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
56// Returns unexpected_eof if error.
57template <typename T>
58static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr,
59 const uint64_t Size = sizeof(T)) {
60 uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
62 return E;
63 Obj = reinterpret_cast<const T *>(Addr);
64 return Error::success();
65}
66
67// Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
68// prefixed slashes.
69static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
70 assert(Str.size() <= 6 && "String too long, possible overflow.");
71 if (Str.size() > 6)
72 return true;
73
74 uint64_t Value = 0;
75 while (!Str.empty()) {
76 unsigned CharVal;
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
84 CharVal = 62;
85 else if (Str[0] == '/') // 63
86 CharVal = 63;
87 else
88 return true;
89
90 Value = (Value * 64) + CharVal;
91 Str = Str.substr(1);
92 }
93
94 if (Value > std::numeric_limits<uint32_t>::max())
95 return true;
96
97 Result = static_cast<uint32_t>(Value);
98 return false;
99}
100
101template <typename coff_symbol_type>
102const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
103 const coff_symbol_type *Addr =
104 reinterpret_cast<const coff_symbol_type *>(Ref.p);
105
106 assert(!checkOffset(Data, reinterpret_cast<uintptr_t>(Addr), sizeof(*Addr)));
107#ifndef NDEBUG
108 // Verify that the symbol points to a valid entry in the symbol table.
109 uintptr_t Offset =
110 reinterpret_cast<uintptr_t>(Addr) - reinterpret_cast<uintptr_t>(base());
111
112 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
113 "Symbol did not point to the beginning of a symbol");
114#endif
115
116 return Addr;
117}
118
119const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
120 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
121
122#ifndef NDEBUG
123 // Verify that the section points to a valid entry in the section table.
124 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
125 report_fatal_error("Section was outside of section table.");
126
127 uintptr_t Offset = reinterpret_cast<uintptr_t>(Addr) -
128 reinterpret_cast<uintptr_t>(SectionTable);
129 assert(Offset % sizeof(coff_section) == 0 &&
130 "Section did not point to the beginning of a section");
131#endif
132
133 return Addr;
134}
135
137 auto End = reinterpret_cast<uintptr_t>(StringTable);
138 if (SymbolTable16) {
139 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
140 Symb += 1 + Symb->NumberOfAuxSymbols;
141 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
142 } else if (SymbolTable32) {
143 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
144 Symb += 1 + Symb->NumberOfAuxSymbols;
145 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
146 } else {
147 llvm_unreachable("no symbol table pointer!");
148 }
149}
150
153}
154
156 return getCOFFSymbol(Ref).getValue();
157}
158
160 // MSVC/link.exe seems to align symbols to the next-power-of-2
161 // up to 32 bytes.
163 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
164}
165
169 int32_t SectionNumber = Symb.getSectionNumber();
170
171 if (Symb.isAnyUndefined() || Symb.isCommon() ||
172 COFF::isReservedSectionNumber(SectionNumber))
173 return Result;
174
175 Expected<const coff_section *> Section = getSection(SectionNumber);
176 if (!Section)
177 return Section.takeError();
178 Result += (*Section)->VirtualAddress;
179
180 // The section VirtualAddress does not include ImageBase, and we want to
181 // return virtual addresses.
182 Result += getImageBase();
183
184 return Result;
185}
186
189 int32_t SectionNumber = Symb.getSectionNumber();
190
193 if (Symb.isAnyUndefined())
195 if (Symb.isCommon())
196 return SymbolRef::ST_Data;
197 if (Symb.isFileRecord())
198 return SymbolRef::ST_File;
199
200 // TODO: perhaps we need a new symbol type ST_Section.
201 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
202 return SymbolRef::ST_Debug;
203
204 if (!COFF::isReservedSectionNumber(SectionNumber))
205 return SymbolRef::ST_Data;
206
207 return SymbolRef::ST_Other;
208}
209
213
214 if (Symb.isExternal() || Symb.isWeakExternal())
215 Result |= SymbolRef::SF_Global;
216
217 if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
218 Result |= SymbolRef::SF_Weak;
219 if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
220 Result |= SymbolRef::SF_Undefined;
221 }
222
224 Result |= SymbolRef::SF_Absolute;
225
226 if (Symb.isFileRecord())
228
229 if (Symb.isSectionDefinition())
231
232 if (Symb.isCommon())
233 Result |= SymbolRef::SF_Common;
234
235 if (Symb.isUndefined())
236 Result |= SymbolRef::SF_Undefined;
237
238 return Result;
239}
240
243 return Symb.getValue();
244}
245
250 return section_end();
252 if (!Sec)
253 return Sec.takeError();
254 DataRefImpl Ret;
255 Ret.p = reinterpret_cast<uintptr_t>(*Sec);
256 return section_iterator(SectionRef(Ret, this));
257}
258
260 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
261 return Symb.getSectionNumber();
262}
263
265 const coff_section *Sec = toSec(Ref);
266 Sec += 1;
267 Ref.p = reinterpret_cast<uintptr_t>(Sec);
268}
269
271 const coff_section *Sec = toSec(Ref);
272 return getSectionName(Sec);
273}
274
276 const coff_section *Sec = toSec(Ref);
277 uint64_t Result = Sec->VirtualAddress;
278
279 // The section VirtualAddress does not include ImageBase, and we want to
280 // return virtual addresses.
281 Result += getImageBase();
282 return Result;
283}
284
286 return toSec(Sec) - SectionTable;
287}
288
290 return getSectionSize(toSec(Ref));
291}
292
295 const coff_section *Sec = toSec(Ref);
297 if (Error E = getSectionContents(Sec, Res))
298 return std::move(E);
299 return Res;
300}
301
303 const coff_section *Sec = toSec(Ref);
304 return Sec->getAlignment();
305}
306
308 return false;
309}
310
312 const coff_section *Sec = toSec(Ref);
314}
315
317 const coff_section *Sec = toSec(Ref);
319}
320
322 const coff_section *Sec = toSec(Ref);
326 return (Sec->Characteristics & BssFlags) == BssFlags;
327}
328
329// The .debug sections are the only debug sections for COFF
330// (\see MCObjectFileInfo.cpp).
332 Expected<StringRef> SectionNameOrErr = getSectionName(Ref);
333 if (!SectionNameOrErr) {
334 // TODO: Report the error message properly.
335 consumeError(SectionNameOrErr.takeError());
336 return false;
337 }
338 StringRef SectionName = SectionNameOrErr.get();
339 return SectionName.startswith(".debug");
340}
341
343 uintptr_t Offset =
344 Sec.getRawDataRefImpl().p - reinterpret_cast<uintptr_t>(SectionTable);
345 assert((Offset % sizeof(coff_section)) == 0);
346 return (Offset / sizeof(coff_section)) + 1;
347}
348
350 const coff_section *Sec = toSec(Ref);
351 // In COFF, a virtual section won't have any in-file
352 // content, so the file pointer to the content will be zero.
353 return Sec->PointerToRawData == 0;
354}
355
357 MemoryBufferRef M, const uint8_t *base) {
358 // The field for the number of relocations in COFF section table is only
359 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
360 // NumberOfRelocations field, and the actual relocation count is stored in the
361 // VirtualAddress field in the first relocation entry.
362 if (Sec->hasExtendedRelocations()) {
363 const coff_relocation *FirstReloc;
364 if (Error E = getObject(FirstReloc, M,
365 reinterpret_cast<const coff_relocation *>(
366 base + Sec->PointerToRelocations))) {
367 consumeError(std::move(E));
368 return 0;
369 }
370 // -1 to exclude this first relocation entry.
371 return FirstReloc->VirtualAddress - 1;
372 }
373 return Sec->NumberOfRelocations;
374}
375
376static const coff_relocation *
377getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
378 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
379 if (!NumRelocs)
380 return nullptr;
381 auto begin = reinterpret_cast<const coff_relocation *>(
383 if (Sec->hasExtendedRelocations()) {
384 // Skip the first relocation entry repurposed to store the number of
385 // relocations.
386 begin++;
387 }
388 if (auto E = Binary::checkOffset(M, reinterpret_cast<uintptr_t>(begin),
389 sizeof(coff_relocation) * NumRelocs)) {
390 consumeError(std::move(E));
391 return nullptr;
392 }
393 return begin;
394}
395
397 const coff_section *Sec = toSec(Ref);
398 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
399 if (begin && Sec->VirtualAddress != 0)
400 report_fatal_error("Sections with relocations should have an address of 0");
401 DataRefImpl Ret;
402 Ret.p = reinterpret_cast<uintptr_t>(begin);
403 return relocation_iterator(RelocationRef(Ret, this));
404}
405
407 const coff_section *Sec = toSec(Ref);
408 const coff_relocation *I = getFirstReloc(Sec, Data, base());
409 if (I)
410 I += getNumberOfRelocations(Sec, Data, base());
411 DataRefImpl Ret;
412 Ret.p = reinterpret_cast<uintptr_t>(I);
413 return relocation_iterator(RelocationRef(Ret, this));
414}
415
416// Initialize the pointer to the symbol table.
417Error COFFObjectFile::initSymbolTablePtr() {
418 if (COFFHeader)
419 if (Error E = getObject(
420 SymbolTable16, Data, base() + getPointerToSymbolTable(),
422 return E;
423
424 if (COFFBigObjHeader)
425 if (Error E = getObject(
426 SymbolTable32, Data, base() + getPointerToSymbolTable(),
428 return E;
429
430 // Find string table. The first four byte of the string table contains the
431 // total size of the string table, including the size field itself. If the
432 // string table is empty, the value of the first four byte would be 4.
435 const uint8_t *StringTableAddr = base() + StringTableOffset;
436 const ulittle32_t *StringTableSizePtr;
437 if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr))
438 return E;
439 StringTableSize = *StringTableSizePtr;
440 if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize))
441 return E;
442
443 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
444 // tools like cvtres write a size of 0 for an empty table instead of 4.
445 if (StringTableSize < 4)
446 StringTableSize = 4;
447
448 // Check that the string table is null terminated if has any in it.
449 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
451 "string table missing null terminator");
452 return Error::success();
453}
454
456 if (PE32Header)
457 return PE32Header->ImageBase;
458 else if (PE32PlusHeader)
459 return PE32PlusHeader->ImageBase;
460 // This actually comes up in practice.
461 return 0;
462}
463
464// Returns the file offset for the given VA.
466 uint64_t ImageBase = getImageBase();
467 uint64_t Rva = Addr - ImageBase;
468 assert(Rva <= UINT32_MAX);
469 return getRvaPtr((uint32_t)Rva, Res);
470}
471
472// Returns the file offset for the given RVA.
474 const char *ErrorContext) const {
475 for (const SectionRef &S : sections()) {
476 const coff_section *Section = getCOFFSection(S);
477 uint32_t SectionStart = Section->VirtualAddress;
478 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
479 if (SectionStart <= Addr && Addr < SectionEnd) {
480 // A table/directory entry can be pointing to somewhere in a stripped
481 // section, in an object that went through `objcopy --only-keep-debug`.
482 // In this case we don't want to cause the parsing of the object file to
483 // fail, otherwise it will be impossible to use this object as debug info
484 // in LLDB. Return SectionStrippedError here so that
485 // COFFObjectFile::initialize can ignore the error.
486 // Somewhat common binaries may have RVAs pointing outside of the
487 // provided raw data. Instead of rejecting the binaries, just
488 // treat the section as stripped for these purposes.
489 if (Section->SizeOfRawData < Section->VirtualSize &&
490 Addr >= SectionStart + Section->SizeOfRawData) {
491 return make_error<SectionStrippedError>();
492 }
493 uint32_t Offset = Addr - SectionStart;
494 Res = reinterpret_cast<uintptr_t>(base()) + Section->PointerToRawData +
495 Offset;
496 return Error::success();
497 }
498 }
499 if (ErrorContext)
501 "RVA 0x%" PRIx32 " for %s not found", Addr,
502 ErrorContext);
504 "RVA 0x%" PRIx32 " not found", Addr);
505}
506
508 ArrayRef<uint8_t> &Contents,
509 const char *ErrorContext) const {
510 for (const SectionRef &S : sections()) {
511 const coff_section *Section = getCOFFSection(S);
512 uint32_t SectionStart = Section->VirtualAddress;
513 // Check if this RVA is within the section bounds. Be careful about integer
514 // overflow.
515 uint32_t OffsetIntoSection = RVA - SectionStart;
516 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
517 Size <= Section->VirtualSize - OffsetIntoSection) {
518 uintptr_t Begin = reinterpret_cast<uintptr_t>(base()) +
519 Section->PointerToRawData + OffsetIntoSection;
520 Contents =
521 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
522 return Error::success();
523 }
524 }
525 if (ErrorContext)
527 "RVA 0x%" PRIx32 " for %s not found", RVA,
528 ErrorContext);
530 "RVA 0x%" PRIx32 " not found", RVA);
531}
532
533// Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
534// table entry.
536 StringRef &Name) const {
537 uintptr_t IntPtr = 0;
538 if (Error E = getRvaPtr(Rva, IntPtr))
539 return E;
540 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
541 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
542 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
543 return Error::success();
544}
545
547 const codeview::DebugInfo *&PDBInfo,
548 StringRef &PDBFileName) const {
549 ArrayRef<uint8_t> InfoBytes;
550 if (Error E =
552 InfoBytes, "PDB info"))
553 return E;
554 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
555 return createStringError(object_error::parse_failed, "PDB info too small");
556 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
557 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
558 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
559 InfoBytes.size());
560 // Truncate the name at the first null byte. Ignore any padding.
561 PDBFileName = PDBFileName.split('\0').first;
562 return Error::success();
563}
564
566 StringRef &PDBFileName) const {
567 for (const debug_directory &D : debug_directories())
569 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
570 // If we get here, there is no PDB info to return.
571 PDBInfo = nullptr;
572 PDBFileName = StringRef();
573 return Error::success();
574}
575
576// Find the import table.
577Error COFFObjectFile::initImportTablePtr() {
578 // First, we get the RVA of the import table. If the file lacks a pointer to
579 // the import table, do nothing.
581 if (!DataEntry)
582 return Error::success();
583
584 // Do nothing if the pointer to import table is NULL.
585 if (DataEntry->RelativeVirtualAddress == 0)
586 return Error::success();
587
588 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
589
590 // Find the section that contains the RVA. This is needed because the RVA is
591 // the import table's memory address which is different from its file offset.
592 uintptr_t IntPtr = 0;
593 if (Error E = getRvaPtr(ImportTableRva, IntPtr, "import table"))
594 return E;
595 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
596 return E;
597 ImportDirectory = reinterpret_cast<
598 const coff_import_directory_table_entry *>(IntPtr);
599 return Error::success();
600}
601
602// Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
603Error COFFObjectFile::initDelayImportTablePtr() {
604 const data_directory *DataEntry =
606 if (!DataEntry)
607 return Error::success();
608 if (DataEntry->RelativeVirtualAddress == 0)
609 return Error::success();
610
611 uint32_t RVA = DataEntry->RelativeVirtualAddress;
612 NumberOfDelayImportDirectory = DataEntry->Size /
614
615 uintptr_t IntPtr = 0;
616 if (Error E = getRvaPtr(RVA, IntPtr, "delay import table"))
617 return E;
618 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
619 return E;
620
621 DelayImportDirectory = reinterpret_cast<
622 const delay_import_directory_table_entry *>(IntPtr);
623 return Error::success();
624}
625
626// Find the export table.
627Error COFFObjectFile::initExportTablePtr() {
628 // First, we get the RVA of the export table. If the file lacks a pointer to
629 // the export table, do nothing.
631 if (!DataEntry)
632 return Error::success();
633
634 // Do nothing if the pointer to export table is NULL.
635 if (DataEntry->RelativeVirtualAddress == 0)
636 return Error::success();
637
638 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
639 uintptr_t IntPtr = 0;
640 if (Error E = getRvaPtr(ExportTableRva, IntPtr, "export table"))
641 return E;
642 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
643 return E;
644
645 ExportDirectory =
646 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
647 return Error::success();
648}
649
650Error COFFObjectFile::initBaseRelocPtr() {
651 const data_directory *DataEntry =
653 if (!DataEntry)
654 return Error::success();
655 if (DataEntry->RelativeVirtualAddress == 0)
656 return Error::success();
657
658 uintptr_t IntPtr = 0;
659 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
660 "base reloc table"))
661 return E;
662 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
663 return E;
664
665 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
666 IntPtr);
667 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
668 IntPtr + DataEntry->Size);
669 // FIXME: Verify the section containing BaseRelocHeader has at least
670 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
671 return Error::success();
672}
673
674Error COFFObjectFile::initDebugDirectoryPtr() {
675 // Get the RVA of the debug directory. Do nothing if it does not exist.
677 if (!DataEntry)
678 return Error::success();
679
680 // Do nothing if the RVA is NULL.
681 if (DataEntry->RelativeVirtualAddress == 0)
682 return Error::success();
683
684 // Check that the size is a multiple of the entry size.
685 if (DataEntry->Size % sizeof(debug_directory) != 0)
687 "debug directory has uneven size");
688
689 uintptr_t IntPtr = 0;
690 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
691 "debug directory"))
692 return E;
693 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
694 return E;
695
696 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
697 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
698 IntPtr + DataEntry->Size);
699 // FIXME: Verify the section containing DebugDirectoryBegin has at least
700 // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
701 return Error::success();
702}
703
704Error COFFObjectFile::initTLSDirectoryPtr() {
705 // Get the RVA of the TLS directory. Do nothing if it does not exist.
707 if (!DataEntry)
708 return Error::success();
709
710 // Do nothing if the RVA is NULL.
711 if (DataEntry->RelativeVirtualAddress == 0)
712 return Error::success();
713
714 uint64_t DirSize =
715 is64() ? sizeof(coff_tls_directory64) : sizeof(coff_tls_directory32);
716
717 // Check that the size is correct.
718 if (DataEntry->Size != DirSize)
719 return createStringError(
721 "TLS Directory size (%u) is not the expected size (%" PRIu64 ").",
722 static_cast<uint32_t>(DataEntry->Size), DirSize);
723
724 uintptr_t IntPtr = 0;
725 if (Error E =
726 getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, "TLS directory"))
727 return E;
728 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
729 return E;
730
731 if (is64())
732 TLSDirectory64 = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
733 else
734 TLSDirectory32 = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
735
736 return Error::success();
737}
738
739Error COFFObjectFile::initLoadConfigPtr() {
740 // Get the RVA of the debug directory. Do nothing if it does not exist.
742 if (!DataEntry)
743 return Error::success();
744
745 // Do nothing if the RVA is NULL.
746 if (DataEntry->RelativeVirtualAddress == 0)
747 return Error::success();
748 uintptr_t IntPtr = 0;
749 if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
750 "load config table"))
751 return E;
752 if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
753 return E;
754
755 LoadConfig = (const void *)IntPtr;
756 return Error::success();
757}
758
761 std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
762 if (Error E = Obj->initialize())
763 return std::move(E);
764 return std::move(Obj);
765}
766
767COFFObjectFile::COFFObjectFile(MemoryBufferRef Object)
768 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
769 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
770 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
771 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
772 ImportDirectory(nullptr), DelayImportDirectory(nullptr),
773 NumberOfDelayImportDirectory(0), ExportDirectory(nullptr),
774 BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
775 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr),
776 TLSDirectory32(nullptr), TLSDirectory64(nullptr) {}
777
779 if (E.isA<SectionStrippedError>()) {
780 consumeError(std::move(E));
781 return Error::success();
782 }
783 return E;
784}
785
786Error COFFObjectFile::initialize() {
787 // Check that we at least have enough room for a header.
788 std::error_code EC;
789 if (!checkSize(Data, EC, sizeof(coff_file_header)))
790 return errorCodeToError(EC);
791
792 // The current location in the file where we are looking at.
793 uint64_t CurPtr = 0;
794
795 // PE header is optional and is present only in executables. If it exists,
796 // it is placed right after COFF header.
797 bool HasPEHeader = false;
798
799 // Check if this is a PE/COFF file.
800 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
801 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
802 // PE signature to find 'normal' COFF header.
803 const auto *DH = reinterpret_cast<const dos_header *>(base());
804 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
805 CurPtr = DH->AddressOfNewExeHeader;
806 // Check the PE magic bytes. ("PE\0\0")
807 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
809 "incorrect PE magic");
810 }
811 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
812 HasPEHeader = true;
813 }
814 }
815
816 if (Error E = getObject(COFFHeader, Data, base() + CurPtr))
817 return E;
818
819 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
820 // import libraries share a common prefix but bigobj is more restrictive.
821 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
822 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
823 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
824 if (Error E = getObject(COFFBigObjHeader, Data, base() + CurPtr))
825 return E;
826
827 // Verify that we are dealing with bigobj.
828 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
829 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
830 sizeof(COFF::BigObjMagic)) == 0) {
831 COFFHeader = nullptr;
832 CurPtr += sizeof(coff_bigobj_file_header);
833 } else {
834 // It's not a bigobj.
835 COFFBigObjHeader = nullptr;
836 }
837 }
838 if (COFFHeader) {
839 // The prior checkSize call may have failed. This isn't a hard error
840 // because we were just trying to sniff out bigobj.
841 EC = std::error_code();
842 CurPtr += sizeof(coff_file_header);
843
844 if (COFFHeader->isImportLibrary())
845 return errorCodeToError(EC);
846 }
847
848 if (HasPEHeader) {
849 const pe32_header *Header;
850 if (Error E = getObject(Header, Data, base() + CurPtr))
851 return E;
852
853 const uint8_t *DataDirAddr;
854 uint64_t DataDirSize;
855 if (Header->Magic == COFF::PE32Header::PE32) {
856 PE32Header = Header;
857 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
858 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
859 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
860 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
861 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
862 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
863 } else {
864 // It's neither PE32 nor PE32+.
866 "incorrect PE magic");
867 }
868 if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))
869 return E;
870 }
871
872 if (COFFHeader)
873 CurPtr += COFFHeader->SizeOfOptionalHeader;
874
875 assert(COFFHeader || COFFBigObjHeader);
876
877 if (Error E =
878 getObject(SectionTable, Data, base() + CurPtr,
880 return E;
881
882 // Initialize the pointer to the symbol table.
883 if (getPointerToSymbolTable() != 0) {
884 if (Error E = initSymbolTablePtr()) {
885 // Recover from errors reading the symbol table.
886 consumeError(std::move(E));
887 SymbolTable16 = nullptr;
888 SymbolTable32 = nullptr;
889 StringTable = nullptr;
890 StringTableSize = 0;
891 }
892 } else {
893 // We had better not have any symbols if we don't have a symbol table.
894 if (getNumberOfSymbols() != 0) {
896 "symbol table missing");
897 }
898 }
899
900 // Initialize the pointer to the beginning of the import table.
901 if (Error E = ignoreStrippedErrors(initImportTablePtr()))
902 return E;
903 if (Error E = ignoreStrippedErrors(initDelayImportTablePtr()))
904 return E;
905
906 // Initialize the pointer to the export table.
907 if (Error E = ignoreStrippedErrors(initExportTablePtr()))
908 return E;
909
910 // Initialize the pointer to the base relocation table.
911 if (Error E = ignoreStrippedErrors(initBaseRelocPtr()))
912 return E;
913
914 // Initialize the pointer to the debug directory.
915 if (Error E = ignoreStrippedErrors(initDebugDirectoryPtr()))
916 return E;
917
918 // Initialize the pointer to the TLS directory.
919 if (Error E = ignoreStrippedErrors(initTLSDirectoryPtr()))
920 return E;
921
922 if (Error E = ignoreStrippedErrors(initLoadConfigPtr()))
923 return E;
924
925 return Error::success();
926}
927
929 DataRefImpl Ret;
930 Ret.p = getSymbolTable();
931 return basic_symbol_iterator(SymbolRef(Ret, this));
932}
933
935 // The symbol table ends where the string table begins.
936 DataRefImpl Ret;
937 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
938 return basic_symbol_iterator(SymbolRef(Ret, this));
939}
940
942 if (!ImportDirectory)
943 return import_directory_end();
944 if (ImportDirectory->isNull())
945 return import_directory_end();
947 ImportDirectoryEntryRef(ImportDirectory, 0, this));
948}
949
952 ImportDirectoryEntryRef(nullptr, -1, this));
953}
954
958 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
959}
960
965 DelayImportDirectory, NumberOfDelayImportDirectory, this));
966}
967
970 ExportDirectoryEntryRef(ExportDirectory, 0, this));
971}
972
974 if (!ExportDirectory)
975 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
976 ExportDirectoryEntryRef Ref(ExportDirectory,
977 ExportDirectory->AddressTableEntries, this);
979}
980
982 DataRefImpl Ret;
983 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
984 return section_iterator(SectionRef(Ret, this));
985}
986
988 DataRefImpl Ret;
989 int NumSections =
990 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
991 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
992 return section_iterator(SectionRef(Ret, this));
993}
994
996 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
997}
998
1000 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
1001}
1002
1004 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
1005}
1006
1008 switch(getMachine()) {
1010 return "COFF-i386";
1012 return "COFF-x86-64";
1014 return "COFF-ARM";
1016 return "COFF-ARM64";
1018 return "COFF-ARM64EC";
1020 return "COFF-ARM64X";
1021 default:
1022 return "COFF-<unknown arch>";
1023 }
1024}
1025
1027 switch (getMachine()) {
1029 return Triple::x86;
1031 return Triple::x86_64;
1033 return Triple::thumb;
1037 return Triple::aarch64;
1038 default:
1039 return Triple::UnknownArch;
1040 }
1041}
1042
1044 if (PE32Header)
1045 return PE32Header->AddressOfEntryPoint;
1046 return 0;
1047}
1048
1052}
1053
1058}
1059
1063}
1064
1067}
1068
1070 if (!DataDirectory)
1071 return nullptr;
1072 assert(PE32Header || PE32PlusHeader);
1073 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
1074 : PE32PlusHeader->NumberOfRvaAndSize;
1075 if (Index >= NumEnt)
1076 return nullptr;
1077 return &DataDirectory[Index];
1078}
1079
1081 // Perhaps getting the section of a reserved section index should be an error,
1082 // but callers rely on this to return null.
1084 return (const coff_section *)nullptr;
1085 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
1086 // We already verified the section table data, so no need to check again.
1087 return SectionTable + (Index - 1);
1088 }
1090 "section index out of bounds");
1091}
1092
1093Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
1094 if (StringTableSize <= 4)
1095 // Tried to get a string from an empty string table.
1096 return createStringError(object_error::parse_failed, "string table empty");
1097 if (Offset >= StringTableSize)
1099 return StringRef(StringTable + Offset);
1100}
1101
1103 return getSymbolName(Symbol.getGeneric());
1104}
1105
1108 // Check for string table entry. First 4 bytes are 0.
1109 if (Symbol->Name.Offset.Zeroes == 0)
1110 return getString(Symbol->Name.Offset.Offset);
1111
1112 // Null terminated, let ::strlen figure out the length.
1113 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1114 return StringRef(Symbol->Name.ShortName);
1115
1116 // Not null terminated, use all 8 bytes.
1117 return StringRef(Symbol->Name.ShortName, COFF::NameSize);
1118}
1119
1122 const uint8_t *Aux = nullptr;
1123
1124 size_t SymbolSize = getSymbolTableEntrySize();
1125 if (Symbol.getNumberOfAuxSymbols() > 0) {
1126 // AUX data comes immediately after the symbol in COFF
1127 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1128#ifndef NDEBUG
1129 // Verify that the Aux symbol points to a valid entry in the symbol table.
1130 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1132 Offset >=
1133 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1134 report_fatal_error("Aux Symbol data was outside of symbol table.");
1135
1136 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1137 "Aux Symbol data did not point to the beginning of a symbol");
1138#endif
1139 }
1140 return ArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1141}
1142
1144 uintptr_t Offset =
1145 reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
1147 "Symbol did not point to the beginning of a symbol");
1150 return Index;
1151}
1152
1155 StringRef Name = StringRef(Sec->Name, COFF::NameSize).split('\0').first;
1156
1157 // Check for string table entry. First byte is '/'.
1158 if (Name.startswith("/")) {
1160 if (Name.startswith("//")) {
1161 if (decodeBase64StringEntry(Name.substr(2), Offset))
1163 "invalid section name");
1164 } else {
1165 if (Name.substr(1).getAsInteger(10, Offset))
1167 "invalid section name");
1168 }
1169 return getString(Offset);
1170 }
1171
1172 return Name;
1173}
1174
1176 // SizeOfRawData and VirtualSize change what they represent depending on
1177 // whether or not we have an executable image.
1178 //
1179 // For object files, SizeOfRawData contains the size of section's data;
1180 // VirtualSize should be zero but isn't due to buggy COFF writers.
1181 //
1182 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1183 // actual section size is in VirtualSize. It is possible for VirtualSize to
1184 // be greater than SizeOfRawData; the contents past that point should be
1185 // considered to be zero.
1186 if (getDOSHeader())
1187 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1188 return Sec->SizeOfRawData;
1189}
1190
1192 ArrayRef<uint8_t> &Res) const {
1193 // In COFF, a virtual section won't have any in-file
1194 // content, so the file pointer to the content will be zero.
1195 if (Sec->PointerToRawData == 0)
1196 return Error::success();
1197 // The only thing that we need to verify is that the contents is contained
1198 // within the file bounds. We don't need to make sure it doesn't cover other
1199 // data, as there's nothing that says that is not allowed.
1200 uintptr_t ConStart =
1201 reinterpret_cast<uintptr_t>(base()) + Sec->PointerToRawData;
1202 uint32_t SectionSize = getSectionSize(Sec);
1203 if (Error E = checkOffset(Data, ConStart, SectionSize))
1204 return E;
1205 Res = ArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1206 return Error::success();
1207}
1208
1209const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1210 return reinterpret_cast<const coff_relocation*>(Rel.p);
1211}
1212
1214 Rel.p = reinterpret_cast<uintptr_t>(
1215 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1216}
1217
1219 const coff_relocation *R = toRel(Rel);
1220 return R->VirtualAddress;
1221}
1222
1224 const coff_relocation *R = toRel(Rel);
1226 if (R->SymbolTableIndex >= getNumberOfSymbols())
1227 return symbol_end();
1228 if (SymbolTable16)
1229 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1230 else if (SymbolTable32)
1231 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1232 else
1233 llvm_unreachable("no symbol table pointer!");
1234 return symbol_iterator(SymbolRef(Ref, this));
1235}
1236
1238 const coff_relocation* R = toRel(Rel);
1239 return R->Type;
1240}
1241
1242const coff_section *
1244 return toSec(Section.getRawDataRefImpl());
1245}
1246
1248 if (SymbolTable16)
1249 return toSymb<coff_symbol16>(Ref);
1250 if (SymbolTable32)
1251 return toSymb<coff_symbol32>(Ref);
1252 llvm_unreachable("no symbol table pointer!");
1253}
1254
1256 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1257}
1258
1259const coff_relocation *
1261 return toRel(Reloc.getRawDataRefImpl());
1262}
1263
1266 return {getFirstReloc(Sec, Data, base()),
1268}
1269
1270#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1271 case COFF::reloc_type: \
1272 return #reloc_type;
1273
1275 switch (getMachine()) {
1277 switch (Type) {
1278 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1279 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1280 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1281 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1282 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1283 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1284 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1285 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1286 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1287 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1288 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1289 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1290 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1291 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1292 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1293 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1294 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1295 default:
1296 return "Unknown";
1297 }
1298 break;
1300 switch (Type) {
1301 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1302 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1303 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1304 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1305 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1306 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1307 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1308 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1309 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
1310 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1311 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1312 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1313 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1314 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1315 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1316 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1317 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
1318 default:
1319 return "Unknown";
1320 }
1321 break;
1325 switch (Type) {
1326 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1327 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1328 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1329 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1330 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1331 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1332 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1333 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1334 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1335 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1336 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1337 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1338 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1339 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1340 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1341 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1342 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1343 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
1344 default:
1345 return "Unknown";
1346 }
1347 break;
1349 switch (Type) {
1350 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1351 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1352 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1353 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1354 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1355 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1356 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1357 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1358 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1359 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1360 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1361 default:
1362 return "Unknown";
1363 }
1364 break;
1365 default:
1366 return "Unknown";
1367 }
1368}
1369
1370#undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1371
1373 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1374 const coff_relocation *Reloc = toRel(Rel);
1375 StringRef Res = getRelocationTypeName(Reloc->Type);
1376 Result.append(Res.begin(), Res.end());
1377}
1378
1380 return !DataDirectory;
1381}
1382
1385 .Case("eh_fram", "eh_frame")
1386 .Default(Name);
1387}
1388
1391 return ImportTable == Other.ImportTable && Index == Other.Index;
1392}
1393
1395 ++Index;
1396 if (ImportTable[Index].isNull()) {
1397 Index = -1;
1398 ImportTable = nullptr;
1399 }
1400}
1401
1403 const coff_import_directory_table_entry *&Result) const {
1404 return getObject(Result, OwningObject->Data, ImportTable + Index);
1405}
1406
1409 uintptr_t Ptr, int Index) {
1410 if (Object->getBytesInAddress() == 4) {
1411 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1413 }
1414 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1416}
1417
1420 uintptr_t IntPtr = 0;
1421 // FIXME: Handle errors.
1422 cantFail(Object->getRvaPtr(RVA, IntPtr));
1423 return makeImportedSymbolIterator(Object, IntPtr, 0);
1424}
1425
1428 uintptr_t IntPtr = 0;
1429 // FIXME: Handle errors.
1430 cantFail(Object->getRvaPtr(RVA, IntPtr));
1431 // Forward the pointer to the last entry which is null.
1432 int Index = 0;
1433 if (Object->getBytesInAddress() == 4) {
1434 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1435 while (*Entry++)
1436 ++Index;
1437 } else {
1438 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1439 while (*Entry++)
1440 ++Index;
1441 }
1442 return makeImportedSymbolIterator(Object, IntPtr, Index);
1443}
1444
1447 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1448 OwningObject);
1449}
1450
1453 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1454 OwningObject);
1455}
1456
1460}
1461
1463 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1464 OwningObject);
1465}
1466
1468 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1469 OwningObject);
1470}
1471
1475}
1476
1478 uintptr_t IntPtr = 0;
1479 if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr,
1480 "import directory name"))
1481 return E;
1482 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1483 return Error::success();
1484}
1485
1486Error
1488 Result = ImportTable[Index].ImportLookupTableRVA;
1489 return Error::success();
1490}
1491
1493 uint32_t &Result) const {
1494 Result = ImportTable[Index].ImportAddressTableRVA;
1495 return Error::success();
1496}
1497
1500 return Table == Other.Table && Index == Other.Index;
1501}
1502
1504 ++Index;
1505}
1506
1509 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1510 OwningObject);
1511}
1512
1515 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1516 OwningObject);
1517}
1518
1522}
1523
1525 uintptr_t IntPtr = 0;
1526 if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr,
1527 "delay import directory name"))
1528 return E;
1529 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1530 return Error::success();
1531}
1532
1534 const delay_import_directory_table_entry *&Result) const {
1535 Result = &Table[Index];
1536 return Error::success();
1537}
1538
1540 uint64_t &Result) const {
1542 AddrIndex * (OwningObject->is64() ? 8 : 4);
1543 uintptr_t IntPtr = 0;
1544 if (Error E = OwningObject->getRvaPtr(RVA, IntPtr, "import address"))
1545 return E;
1546 if (OwningObject->is64())
1547 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1548 else
1549 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1550 return Error::success();
1551}
1552
1555 return ExportTable == Other.ExportTable && Index == Other.Index;
1556}
1557
1559 ++Index;
1560}
1561
1562// Returns the name of the current export symbol. If the symbol is exported only
1563// by ordinal, the empty string is set as a result.
1565 uintptr_t IntPtr = 0;
1566 if (Error E =
1567 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr, "dll name"))
1568 return E;
1569 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1570 return Error::success();
1571}
1572
1573// Returns the starting ordinal number.
1575 Result = ExportTable->OrdinalBase;
1576 return Error::success();
1577}
1578
1579// Returns the export ordinal of the current export symbol.
1581 Result = ExportTable->OrdinalBase + Index;
1582 return Error::success();
1583}
1584
1585// Returns the address of the current export symbol.
1587 uintptr_t IntPtr = 0;
1588 if (Error EC = OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA,
1589 IntPtr, "export address"))
1590 return EC;
1592 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1593 Result = entry[Index].ExportRVA;
1594 return Error::success();
1595}
1596
1597// Returns the name of the current export symbol. If the symbol is exported only
1598// by ordinal, the empty string is set as a result.
1599Error
1601 uintptr_t IntPtr = 0;
1602 if (Error EC = OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr,
1603 "export ordinal table"))
1604 return EC;
1605 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1606
1607 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1608 int Offset = 0;
1609 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1610 I < E; ++I, ++Offset) {
1611 if (*I != Index)
1612 continue;
1613 if (Error EC = OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr,
1614 "export table entry"))
1615 return EC;
1616 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1617 if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr,
1618 "export symbol name"))
1619 return EC;
1620 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1621 return Error::success();
1622 }
1623 Result = "";
1624 return Error::success();
1625}
1626
1628 const data_directory *DataEntry =
1629 OwningObject->getDataDirectory(COFF::EXPORT_TABLE);
1630 if (!DataEntry)
1632 "export table missing");
1633 uint32_t RVA;
1634 if (auto EC = getExportRVA(RVA))
1635 return EC;
1636 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1637 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1638 Result = (Begin <= RVA && RVA < End);
1639 return Error::success();
1640}
1641
1643 uint32_t RVA;
1644 if (auto EC = getExportRVA(RVA))
1645 return EC;
1646 uintptr_t IntPtr = 0;
1647 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr, "export forward target"))
1648 return EC;
1649 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1650 return Error::success();
1651}
1652
1654operator==(const ImportedSymbolRef &Other) const {
1655 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1656 && Index == Other.Index;
1657}
1658
1660 ++Index;
1661}
1662
1664 uint32_t RVA;
1665 if (Entry32) {
1666 // If a symbol is imported only by ordinal, it has no name.
1667 if (Entry32[Index].isOrdinal())
1668 return Error::success();
1669 RVA = Entry32[Index].getHintNameRVA();
1670 } else {
1671 if (Entry64[Index].isOrdinal())
1672 return Error::success();
1673 RVA = Entry64[Index].getHintNameRVA();
1674 }
1675 uintptr_t IntPtr = 0;
1676 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol name"))
1677 return EC;
1678 // +2 because the first two bytes is hint.
1679 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1680 return Error::success();
1681}
1682
1684 if (Entry32)
1685 Result = Entry32[Index].isOrdinal();
1686 else
1687 Result = Entry64[Index].isOrdinal();
1688 return Error::success();
1689}
1690
1692 if (Entry32)
1693 Result = Entry32[Index].getHintNameRVA();
1694 else
1695 Result = Entry64[Index].getHintNameRVA();
1696 return Error::success();
1697}
1698
1700 uint32_t RVA;
1701 if (Entry32) {
1702 if (Entry32[Index].isOrdinal()) {
1703 Result = Entry32[Index].getOrdinal();
1704 return Error::success();
1705 }
1706 RVA = Entry32[Index].getHintNameRVA();
1707 } else {
1708 if (Entry64[Index].isOrdinal()) {
1709 Result = Entry64[Index].getOrdinal();
1710 return Error::success();
1711 }
1712 RVA = Entry64[Index].getHintNameRVA();
1713 }
1714 uintptr_t IntPtr = 0;
1715 if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol ordinal"))
1716 return EC;
1717 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1718 return Error::success();
1719}
1720
1724}
1725
1727 return Header == Other.Header && Index == Other.Index;
1728}
1729
1731 // Header->BlockSize is the size of the current block, including the
1732 // size of the header itself.
1733 uint32_t Size = sizeof(*Header) +
1734 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1735 if (Size == Header->BlockSize) {
1736 // .reloc contains a list of base relocation blocks. Each block
1737 // consists of the header followed by entries. The header contains
1738 // how many entories will follow. When we reach the end of the
1739 // current block, proceed to the next block.
1740 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1741 reinterpret_cast<const uint8_t *>(Header) + Size);
1742 Index = 0;
1743 } else {
1744 ++Index;
1745 }
1746}
1747
1749 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1750 Type = Entry[Index].getType();
1751 return Error::success();
1752}
1753
1755 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1756 Result = Header->PageRVA + Entry[Index].getOffset();
1757 return Error::success();
1758}
1759
1760#define RETURN_IF_ERROR(Expr) \
1761 do { \
1762 Error E = (Expr); \
1763 if (E) \
1764 return std::move(E); \
1765 } while (0)
1766
1768ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1770 Reader.setOffset(Offset);
1773 ArrayRef<UTF16> RawDirString;
1774 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1775 return RawDirString;
1776}
1777
1780 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1781}
1782
1784ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1785 const coff_resource_dir_table *Table = nullptr;
1786
1787 BinaryStreamReader Reader(BBS);
1788 Reader.setOffset(Offset);
1789 RETURN_IF_ERROR(Reader.readObject(Table));
1790 assert(Table != nullptr);
1791 return *Table;
1792}
1793
1795ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
1796 const coff_resource_dir_entry *Entry = nullptr;
1797
1798 BinaryStreamReader Reader(BBS);
1799 Reader.setOffset(Offset);
1800 RETURN_IF_ERROR(Reader.readObject(Entry));
1801 assert(Entry != nullptr);
1802 return *Entry;
1803}
1804
1806ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
1807 const coff_resource_data_entry *Entry = nullptr;
1808
1809 BinaryStreamReader Reader(BBS);
1810 Reader.setOffset(Offset);
1811 RETURN_IF_ERROR(Reader.readObject(Entry));
1812 assert(Entry != nullptr);
1813 return *Entry;
1814}
1815
1818 assert(Entry.Offset.isSubDir());
1819 return getTableAtOffset(Entry.Offset.value());
1820}
1821
1824 assert(!Entry.Offset.isSubDir());
1825 return getDataEntryAtOffset(Entry.Offset.value());
1826}
1827
1829 return getTableAtOffset(0);
1830}
1831
1834 uint32_t Index) {
1835 if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1836 return createStringError(object_error::parse_failed, "index out of range");
1837 const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
1838 ptrdiff_t TableOffset = TablePtr - BBS.data().data();
1839 return getTableEntryAtOffset(TableOffset + sizeof(Table) +
1840 Index * sizeof(coff_resource_dir_entry));
1841}
1842
1844 for (const SectionRef &S : O->sections()) {
1845 Expected<StringRef> Name = S.getName();
1846 if (!Name)
1847 return Name.takeError();
1848
1849 if (*Name == ".rsrc" || *Name == ".rsrc$01")
1850 return load(O, S);
1851 }
1853 "no resource section found");
1854}
1855
1857 Obj = O;
1858 Section = S;
1859 Expected<StringRef> Contents = Section.getContents();
1860 if (!Contents)
1861 return Contents.takeError();
1862 BBS = BinaryByteStream(*Contents, support::little);
1863 const coff_section *COFFSect = Obj->getCOFFSection(Section);
1864 ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect);
1865 Relocs.reserve(OrigRelocs.size());
1866 for (const coff_relocation &R : OrigRelocs)
1867 Relocs.push_back(&R);
1868 llvm::sort(Relocs, [](const coff_relocation *A, const coff_relocation *B) {
1869 return A->VirtualAddress < B->VirtualAddress;
1870 });
1871 return Error::success();
1872}
1873
1876 if (!Obj)
1877 return createStringError(object_error::parse_failed, "no object provided");
1878
1879 // Find a potential relocation at the DataRVA field (first member of
1880 // the coff_resource_data_entry struct).
1881 const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
1882 ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
1883 coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0),
1884 ulittle16_t(0)};
1885 auto RelocsForOffset =
1886 std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget,
1887 [](const coff_relocation *A, const coff_relocation *B) {
1888 return A->VirtualAddress < B->VirtualAddress;
1889 });
1890
1891 if (RelocsForOffset.first != RelocsForOffset.second) {
1892 // We found a relocation with the right offset. Check that it does have
1893 // the expected type.
1894 const coff_relocation &R = **RelocsForOffset.first;
1895 uint16_t RVAReloc;
1896 switch (Obj->getMachine()) {
1899 break;
1902 break;
1905 break;
1910 break;
1911 default:
1913 "unsupported architecture");
1914 }
1915 if (R.Type != RVAReloc)
1917 "unexpected relocation type");
1918 // Get the relocation's symbol
1919 Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
1920 if (!Sym)
1921 return Sym.takeError();
1922 // And the symbol's section
1924 Obj->getSection(Sym->getSectionNumber());
1925 if (!Section)
1926 return Section.takeError();
1927 // Add the initial value of DataRVA to the symbol's offset to find the
1928 // data it points at.
1929 uint64_t Offset = Entry.DataRVA + Sym->getValue();
1930 ArrayRef<uint8_t> Contents;
1931 if (Error E = Obj->getSectionContents(*Section, Contents))
1932 return std::move(E);
1933 if (Offset + Entry.DataSize > Contents.size())
1935 "data outside of section");
1936 // Return a reference to the data inside the section.
1937 return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
1938 Entry.DataSize);
1939 } else {
1940 // Relocatable objects need a relocation for the DataRVA field.
1941 if (Obj->isRelocatableObject())
1943 "no relocation found for DataRVA");
1944
1945 // Locate the section that contains the address that DataRVA points at.
1946 uint64_t VA = Entry.DataRVA + Obj->getImageBase();
1947 for (const SectionRef &S : Obj->sections()) {
1948 if (VA >= S.getAddress() &&
1949 VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
1950 uint64_t Offset = VA - S.getAddress();
1951 Expected<StringRef> Contents = S.getContents();
1952 if (!Contents)
1953 return Contents.takeError();
1954 return Contents->slice(Offset, Offset + Entry.DataSize);
1955 }
1956 }
1958 "address not found in image");
1959 }
1960}
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static imported_symbol_iterator importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object)
static uint32_t getNumberOfRelocations(const coff_section *Sec, MemoryBufferRef M, const uint8_t *base)
static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr, const uint64_t Size=sizeof(T))
static imported_symbol_iterator makeImportedSymbolIterator(const COFFObjectFile *Object, uintptr_t Ptr, int Index)
#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)
static const coff_relocation * getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base)
static imported_symbol_iterator importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object)
static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size)
#define RETURN_IF_ERROR(Expr)
static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result)
static Error ignoreStrippedErrors(Error E)
uint64_t Addr
std::string Name
uint64_t Size
bool End
Definition: ELF_riscv.cpp:464
Symbol * Sym
Definition: ELF_riscv.cpp:463
#define I(x, y, z)
Definition: MD5.cpp:58
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:953
print Instructions which execute on loop entry
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:202
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:163
const T * data() const
Definition: ArrayRef.h:160
An implementation of BinaryStream which holds its entire data set in a single contiguous buffer.
ArrayRef< uint8_t > data() const
Provides read only access to a subclass of BinaryStream.
Error readInteger(T &Dest)
Read an integer of the specified endianness into Dest and update the stream's offset.
void setOffset(uint64_t Off)
Error readArray(ArrayRef< T > &Array, uint32_t NumElements)
Get a reference to a NumElements element array of objects of type T from the underlying stream as if ...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
static ErrorSuccess success()
Create a success value.
Definition: Error.h:330
Tagged union holding either a T or a Error.
Definition: Error.h:470
Error takeError()
Take ownership of the stored error.
Definition: Error.h:597
reference get()
Returns a reference to the stored T value.
Definition: Error.h:567
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:577
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:698
iterator begin() const
Definition: StringRef.h:111
iterator end() const
Definition: StringRef.h:113
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
@ UnknownArch
Definition: Triple.h:47
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
LLVM Value Representation.
Definition: Value.h:74
A range adaptor for a pair of iterators.
Error getType(uint8_t &Type) const
bool operator==(const BaseRelocRef &Other) const
Error getRVA(uint32_t &Result) const
MemoryBufferRef Data
Definition: Binary.h:37
static Error checkOffset(MemoryBufferRef M, uintptr_t Addr, const uint64_t Size)
Definition: Binary.h:175
const dos_header * getDOSHeader() const
Definition: COFF.h:1020
uint64_t getSectionSize(DataRefImpl Sec) const override
Expected< StringRef > getSectionName(DataRefImpl Sec) const override
uint64_t getSectionIndex(DataRefImpl Sec) const override
uint32_t getSymbolAlignment(DataRefImpl Symb) const override
bool isSectionCompressed(DataRefImpl Sec) const override
void moveRelocationNext(DataRefImpl &Rel) const override
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
uint8_t getBytesInAddress() const override
The number of bytes used to represent an address in this object file format.
export_directory_iterator export_directory_begin() const
delay_import_directory_iterator delay_import_directory_end() const
base_reloc_iterator base_reloc_begin() const
section_iterator section_end() const override
Error getVaPtr(uint64_t VA, uintptr_t &Res) const
uint64_t getRelocationType(DataRefImpl Rel) const override
void moveSymbolNext(DataRefImpl &Symb) const override
uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override
iterator_range< delay_import_directory_iterator > delay_import_directories() const
import_directory_iterator import_directory_end() const
uint32_t getPointerToSymbolTable() const
Definition: COFF.h:892
const coff_relocation * getCOFFRelocation(const RelocationRef &Reloc) const
Expected< StringRef > getSymbolName(DataRefImpl Symb) const override
bool isDebugSection(DataRefImpl Sec) const override
iterator_range< const debug_directory * > debug_directories() const
Definition: COFF.h:1009
StringRef getRelocationTypeName(uint16_t Type) const
bool isSectionBSS(DataRefImpl Sec) const override
base_reloc_iterator base_reloc_end() const
uint64_t getSectionAddress(DataRefImpl Sec) const override
Expected< uint64_t > getSymbolAddress(DataRefImpl Symb) const override
uint32_t getNumberOfSymbols() const
Definition: COFF.h:909
section_iterator section_begin() const override
Expected< SymbolRef::Type > getSymbolType(DataRefImpl Symb) const override
size_t getSymbolTableEntrySize() const
Definition: COFF.h:1062
friend class ImportDirectoryEntryRef
Definition: COFF.h:792
export_directory_iterator export_directory_end() const
Error getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const
uintptr_t getSymbolTable() const
Definition: COFF.h:840
static Expected< std::unique_ptr< COFFObjectFile > > create(MemoryBufferRef Object)
bool isSectionVirtual(DataRefImpl Sec) const override
unsigned getSectionID(SectionRef Sec) const
relocation_iterator section_rel_begin(DataRefImpl Sec) const override
iterator_range< import_directory_iterator > import_directories() const
delay_import_directory_iterator delay_import_directory_begin() const
basic_symbol_iterator symbol_end() const override
Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, ArrayRef< uint8_t > &Contents, const char *ErrorContext=nullptr) const
Given an RVA base and size, returns a valid array of bytes or an error code if the RVA and size is no...
iterator_range< export_directory_iterator > export_directories() const
uint32_t getNumberOfSections() const
Definition: COFF.h:884
uint64_t getRelocationOffset(DataRefImpl Rel) const override
basic_symbol_iterator symbol_begin() const override
Triple::ArchType getArch() const override
bool isRelocatableObject() const override
True if this is a relocatable object (.o/.obj).
Expected< uint32_t > getSymbolFlags(DataRefImpl Symb) const override
Expected< const coff_section * > getSection(int32_t index) const
bool isSectionText(DataRefImpl Sec) const override
Expected< ArrayRef< uint8_t > > getSectionContents(DataRefImpl Sec) const override
const data_directory * getDataDirectory(uint32_t index) const
StringRef mapDebugSectionName(StringRef Name) const override
Maps a debug section name to a standard DWARF section name.
ArrayRef< uint8_t > getSymbolAuxData(COFFSymbolRef Symbol) const
const coff_section * getCOFFSection(const SectionRef &Section) const
import_directory_iterator import_directory_begin() const
void moveSectionNext(DataRefImpl &Sec) const override
relocation_iterator section_rel_end(DataRefImpl Sec) const override
ArrayRef< coff_relocation > getRelocations(const coff_section *Sec) const
uint64_t getSymbolValueImpl(DataRefImpl Symb) const override
Error getRvaPtr(uint32_t Rva, uintptr_t &Res, const char *ErrorContext=nullptr) const
unsigned getSymbolSectionID(SymbolRef Sym) const
Error getDebugPDBInfo(const debug_directory *DebugDir, const codeview::DebugInfo *&Info, StringRef &PDBFileName) const
Get PDB information out of a codeview debug directory entry.
friend class ExportDirectoryEntryRef
Definition: COFF.h:793
symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override
uint64_t getSectionAlignment(DataRefImpl Sec) const override
uint32_t getSymbolIndex(COFFSymbolRef Symbol) const
uint16_t getMachine() const
Definition: COFF.h:848
COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const
Expected< uint64_t > getStartAddress() const override
iterator_range< base_reloc_iterator > base_relocs() const
bool isSectionData(DataRefImpl Sec) const override
StringRef getFileFormatName() const override
bool isCommon() const
Definition: COFF.h:381
bool isAnyUndefined() const
Definition: COFF.h:405
bool isFileRecord() const
Definition: COFF.h:409
const coff_aux_weak_external * getWeakExternal() const
Definition: COFF.h:366
bool isSectionDefinition() const
Definition: COFF.h:417
uint8_t getComplexType() const
Definition: COFF.h:350
bool isExternal() const
Definition: COFF.h:377
uint32_t getValue() const
Definition: COFF.h:317
bool isWeakExternal() const
Definition: COFF.h:391
int32_t getSectionNumber() const
Definition: COFF.h:322
bool isUndefined() const
Definition: COFF.h:386
bool operator==(const DelayImportDirectoryEntryRef &Other) const
imported_symbol_iterator imported_symbol_begin() const
Error getImportAddress(int AddrIndex, uint64_t &Result) const
iterator_range< imported_symbol_iterator > imported_symbols() const
imported_symbol_iterator imported_symbol_end() const
Error getDelayImportTable(const delay_import_directory_table_entry *&Result) const
Error getName(StringRef &Result) const
bool operator==(const ExportDirectoryEntryRef &Other) const
Error getDllName(StringRef &Result) const
Error getExportRVA(uint32_t &Result) const
Error getOrdinalBase(uint32_t &Result) const
Error getOrdinal(uint32_t &Result) const
Error isForwarder(bool &Result) const
Error getForwardTo(StringRef &Result) const
Error getSymbolName(StringRef &Result) const
bool operator==(const ImportDirectoryEntryRef &Other) const
imported_symbol_iterator imported_symbol_end() const
imported_symbol_iterator imported_symbol_begin() const
Error getImportLookupTableRVA(uint32_t &Result) const
Error getImportTableEntry(const coff_import_directory_table_entry *&Result) const
imported_symbol_iterator lookup_table_end() const
iterator_range< imported_symbol_iterator > lookup_table_symbols() const
iterator_range< imported_symbol_iterator > imported_symbols() const
imported_symbol_iterator lookup_table_begin() const
Error getImportAddressTableRVA(uint32_t &Result) const
Error getName(StringRef &Result) const
bool operator==(const ImportedSymbolRef &Other) const
Error getHintNameRVA(uint32_t &Result) const
Error getOrdinal(uint16_t &Result) const
Error getSymbolName(StringRef &Result) const
Error isOrdinal(bool &Result) const
This class is the base class for all object file types.
Definition: ObjectFile.h:228
friend class RelocationRef
Definition: ObjectFile.h:286
friend class SymbolRef
Definition: ObjectFile.h:246
static Expected< std::unique_ptr< COFFObjectFile > > createCOFFObjectFile(MemoryBufferRef Object)
section_iterator_range sections() const
Definition: ObjectFile.h:327
friend class SectionRef
Definition: ObjectFile.h:260
Expected< uint64_t > getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:56
const uint8_t * base() const
Definition: ObjectFile.h:234
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:51
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:582
Expected< const coff_resource_dir_table & > getBaseTable()
Expected< const coff_resource_dir_table & > getEntrySubDir(const coff_resource_dir_entry &Entry)
Expected< const coff_resource_data_entry & > getEntryData(const coff_resource_dir_entry &Entry)
Error load(const COFFObjectFile *O)
Expected< ArrayRef< UTF16 > > getEntryNameString(const coff_resource_dir_entry &Entry)
Expected< StringRef > getContents(const coff_resource_data_entry &Entry)
Expected< const coff_resource_dir_entry & > getTableEntry(const coff_resource_dir_table &Table, uint32_t Index)
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:544
Expected< StringRef > getContents() const
Definition: ObjectFile.h:479
This is a value type class that represents a single symbol in the list of symbols in the object file.
Definition: ObjectFile.h:167
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ IMAGE_FILE_MACHINE_ARM64
Definition: COFF.h:100
@ IMAGE_FILE_MACHINE_UNKNOWN
Definition: COFF.h:95
@ IMAGE_FILE_MACHINE_AMD64
Definition: COFF.h:97
@ IMAGE_FILE_MACHINE_ARM64EC
Definition: COFF.h:101
@ IMAGE_FILE_MACHINE_I386
Definition: COFF.h:104
@ IMAGE_FILE_MACHINE_ARM64X
Definition: COFF.h:102
@ IMAGE_FILE_MACHINE_ARMNT
Definition: COFF.h:99
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:298
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:331
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:300
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:299
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:332
@ IMAGE_DEBUG_TYPE_CODEVIEW
Definition: COFF.h:665
@ IMAGE_REL_ARM64_ADDR32NB
Definition: COFF.h:398
@ IMAGE_REL_AMD64_ADDR32NB
Definition: COFF.h:359
@ TLS_TABLE
Definition: COFF.h:602
@ EXPORT_TABLE
Definition: COFF.h:593
@ LOAD_CONFIG_TABLE
Definition: COFF.h:603
@ IMPORT_TABLE
Definition: COFF.h:594
@ DELAY_IMPORT_DESCRIPTOR
Definition: COFF.h:606
@ DEBUG_DIRECTORY
Definition: COFF.h:599
@ BASE_RELOCATION_TABLE
Definition: COFF.h:598
@ NameSize
Definition: COFF.h:57
@ IMAGE_WEAK_EXTERN_SEARCH_ALIAS
Definition: COFF.h:452
@ IMAGE_REL_ARM_ADDR32NB
Definition: COFF.h:378
bool isReservedSectionNumber(int32_t SectionNumber)
Definition: COFF.h:802
@ IMAGE_REL_I386_DIR32NB
Definition: COFF.h:346
static const char BigObjMagic[]
Definition: COFF.h:37
static const char PEMagic[]
Definition: COFF.h:35
@ IMAGE_SYM_DEBUG
Definition: COFF.h:207
@ IMAGE_SYM_ABSOLUTE
Definition: COFF.h:208
@ IMAGE_SYM_DTYPE_FUNCTION
A function that returns a base type.
Definition: COFF.h:271
static Expected< const T * > getObject(MemoryBufferRef M, const void *Ptr, const uint64_t Size=sizeof(T))
content_iterator< ImportDirectoryEntryRef > import_directory_iterator
Definition: COFF.h:45
content_iterator< ImportedSymbolRef > imported_symbol_iterator
Definition: COFF.h:49
content_iterator< ExportDirectoryEntryRef > export_directory_iterator
Definition: COFF.h:48
content_iterator< BaseRelocRef > base_reloc_iterator
Definition: COFF.h:50
coff_tls_directory< support::little64_t > coff_tls_directory64
Definition: COFF.h:598
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:47
content_iterator< RelocationRef > relocation_iterator
Definition: ObjectFile.h:76
content_iterator< BasicSymbolRef > basic_symbol_iterator
Definition: SymbolicFile.h:143
content_iterator< DelayImportDirectoryEntryRef > delay_import_directory_iterator
Definition: COFF.h:47
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:440
@ Length
Definition: DWP.cpp:440
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1246
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:469
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1744
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:145
@ Ref
The access may reference the value stored in memory.
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:745
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:92
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1043
Definition: COFF.h:736
support::ulittle16_t Version
Definition: COFF.h:90
support::ulittle16_t Machine
Definition: COFF.h:76
support::ulittle16_t NumberOfSections
Definition: COFF.h:77
bool isImportLibrary() const
Definition: COFF.h:84
support::ulittle16_t SizeOfOptionalHeader
Definition: COFF.h:81
Definition: COFF.h:555
support::ulittle32_t ImportAddressTableRVA
Definition: COFF.h:560
bool isNull() const
Definition: COFF.h:562
support::ulittle32_t NameRVA
Definition: COFF.h:559
support::ulittle32_t ImportLookupTableRVA
Definition: COFF.h:556
support::ulittle16_t Type
Definition: COFF.h:477
support::ulittle32_t VirtualAddress
Definition: COFF.h:475
Definition: COFF.h:766
Definition: COFF.h:743
support::ulittle16_t NumberOfNameEntries
Definition: COFF.h:778
support::ulittle16_t NumberOfIDEntries
Definition: COFF.h:779
support::ulittle32_t PointerToRawData
Definition: COFF.h:445
char Name[COFF::NameSize]
Definition: COFF.h:441
support::ulittle32_t VirtualSize
Definition: COFF.h:442
bool hasExtendedRelocations() const
Definition: COFF.h:454
uint32_t getAlignment() const
Definition: COFF.h:459
support::ulittle32_t Characteristics
Definition: COFF.h:450
support::ulittle32_t SizeOfRawData
Definition: COFF.h:444
support::ulittle32_t VirtualAddress
Definition: COFF.h:443
support::ulittle32_t PointerToRelocations
Definition: COFF.h:446
support::ulittle16_t NumberOfRelocations
Definition: COFF.h:448
uint8_t NumberOfAuxSymbols
Definition: COFF.h:262
support::ulittle32_t RelativeVirtualAddress
Definition: COFF.h:173
support::ulittle32_t Size
Definition: COFF.h:174
support::ulittle32_t SizeOfData
Definition: COFF.h:183
support::ulittle32_t AddressOfRawData
Definition: COFF.h:184
Definition: COFF.h:210
support::ulittle32_t DelayImportAddressTable
Definition: COFF.h:215
support::ulittle32_t Name
Definition: COFF.h:213
The DOS compatible header at the front of all PE/COFF executables.
Definition: COFF.h:53
Definition: COFF.h:222
support::ulittle32_t OrdinalBase
Definition: COFF.h:228
support::ulittle32_t ExportAddressTableRVA
Definition: COFF.h:231
support::ulittle32_t NameRVA
Definition: COFF.h:227
support::ulittle32_t NumberOfNamePointers
Definition: COFF.h:230
support::ulittle32_t NamePointerRVA
Definition: COFF.h:232
support::ulittle32_t AddressTableEntries
Definition: COFF.h:229
support::ulittle32_t OrdinalTableRVA
Definition: COFF.h:233
Definition: COFF.h:189
bool isOrdinal() const
Definition: COFF.h:192
uint32_t getHintNameRVA() const
Definition: COFF.h:199
uint16_t getOrdinal() const
Definition: COFF.h:194
The 32-bit PE header that follows the COFF header.
Definition: COFF.h:104
support::ulittle32_t NumberOfRvaAndSize
Definition: COFF.h:136
support::ulittle32_t AddressOfEntryPoint
Definition: COFF.h:111
support::ulittle32_t ImageBase
Definition: COFF.h:114
The 64-bit PE header that follows the COFF header.
Definition: COFF.h:140
support::ulittle64_t ImageBase
Definition: COFF.h:149
support::ulittle32_t NumberOfRvaAndSize
Definition: COFF.h:169
Definition: COFF.h:236