LLVM  12.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"
15 #include "llvm/ADT/StringSwitch.h"
16 #include "llvm/ADT/Triple.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"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Error.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <cstring>
34 #include <limits>
35 #include <memory>
36 #include <system_error>
37 
38 using namespace llvm;
39 using namespace object;
40 
45 
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) {
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.
57 template <typename T>
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))
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.
69 static 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 
95  return true;
96 
97  Result = static_cast<uint32_t>(Value);
98  return false;
99 }
100 
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);
105 
106  assert(!checkOffset(Data, 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 = uintptr_t(Addr) - uintptr_t(base());
110 
111  assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
112  "Symbol did not point to the beginning of a symbol");
113 #endif
114 
115  return Addr;
116 }
117 
118 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
119  const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120 
121 #ifndef NDEBUG
122  // Verify that the section points to a valid entry in the section table.
123  if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
124  report_fatal_error("Section was outside of section table.");
125 
126  uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
127  assert(Offset % sizeof(coff_section) == 0 &&
128  "Section did not point to the beginning of a section");
129 #endif
130 
131  return Addr;
132 }
133 
135  auto End = reinterpret_cast<uintptr_t>(StringTable);
136  if (SymbolTable16) {
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);
144  } else {
145  llvm_unreachable("no symbol table pointer!");
146  }
147 }
148 
150  return getSymbolName(getCOFFSymbol(Ref));
151 }
152 
154  return getCOFFSymbol(Ref).getValue();
155 }
156 
158  // MSVC/link.exe seems to align symbols to the next-power-of-2
159  // up to 32 bytes.
160  COFFSymbolRef Symb = getCOFFSymbol(Ref);
161  return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
162 }
163 
165  uint64_t Result = cantFail(getSymbolValue(Ref));
166  COFFSymbolRef Symb = getCOFFSymbol(Ref);
167  int32_t SectionNumber = Symb.getSectionNumber();
168 
169  if (Symb.isAnyUndefined() || Symb.isCommon() ||
170  COFF::isReservedSectionNumber(SectionNumber))
171  return Result;
172 
174  if (!Section)
175  return Section.takeError();
176  Result += (*Section)->VirtualAddress;
177 
178  // The section VirtualAddress does not include ImageBase, and we want to
179  // return virtual addresses.
180  Result += getImageBase();
181 
182  return Result;
183 }
184 
186  COFFSymbolRef Symb = getCOFFSymbol(Ref);
187  int32_t SectionNumber = Symb.getSectionNumber();
188 
190  return SymbolRef::ST_Function;
191  if (Symb.isAnyUndefined())
192  return SymbolRef::ST_Unknown;
193  if (Symb.isCommon())
194  return SymbolRef::ST_Data;
195  if (Symb.isFileRecord())
196  return SymbolRef::ST_File;
197 
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;
201 
202  if (!COFF::isReservedSectionNumber(SectionNumber))
203  return SymbolRef::ST_Data;
204 
205  return SymbolRef::ST_Other;
206 }
207 
209  COFFSymbolRef Symb = getCOFFSymbol(Ref);
210  uint32_t Result = SymbolRef::SF_None;
211 
212  if (Symb.isExternal() || Symb.isWeakExternal())
213  Result |= SymbolRef::SF_Global;
214 
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;
219  }
220 
222  Result |= SymbolRef::SF_Absolute;
223 
224  if (Symb.isFileRecord())
226 
227  if (Symb.isSectionDefinition())
229 
230  if (Symb.isCommon())
231  Result |= SymbolRef::SF_Common;
232 
233  if (Symb.isUndefined())
234  Result |= SymbolRef::SF_Undefined;
235 
236  return Result;
237 }
238 
240  COFFSymbolRef Symb = getCOFFSymbol(Ref);
241  return Symb.getValue();
242 }
243 
246  COFFSymbolRef Symb = getCOFFSymbol(Ref);
248  return section_end();
250  if (!Sec)
251  return Sec.takeError();
253  Ret.p = reinterpret_cast<uintptr_t>(*Sec);
254  return section_iterator(SectionRef(Ret, this));
255 }
256 
259  return Symb.getSectionNumber();
260 }
261 
263  const coff_section *Sec = toSec(Ref);
264  Sec += 1;
265  Ref.p = reinterpret_cast<uintptr_t>(Sec);
266 }
267 
269  const coff_section *Sec = toSec(Ref);
270  return getSectionName(Sec);
271 }
272 
274  const coff_section *Sec = toSec(Ref);
275  uint64_t Result = Sec->VirtualAddress;
276 
277  // The section VirtualAddress does not include ImageBase, and we want to
278  // return virtual addresses.
279  Result += getImageBase();
280  return Result;
281 }
282 
284  return toSec(Sec) - SectionTable;
285 }
286 
287 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
288  return getSectionSize(toSec(Ref));
289 }
290 
293  const coff_section *Sec = toSec(Ref);
294  ArrayRef<uint8_t> Res;
295  if (Error E = getSectionContents(Sec, Res))
296  return std::move(E);
297  return Res;
298 }
299 
301  const coff_section *Sec = toSec(Ref);
302  return Sec->getAlignment();
303 }
304 
306  return false;
307 }
308 
310  const coff_section *Sec = toSec(Ref);
312 }
313 
315  const coff_section *Sec = toSec(Ref);
317 }
318 
320  const coff_section *Sec = toSec(Ref);
324  return (Sec->Characteristics & BssFlags) == BssFlags;
325 }
326 
327 // The .debug sections are the only debug sections for COFF
328 // (\see MCObjectFileInfo.cpp).
330  return SectionName.startswith(".debug");
331 }
332 
334  uintptr_t Offset =
335  uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
336  assert((Offset % sizeof(coff_section)) == 0);
337  return (Offset / sizeof(coff_section)) + 1;
338 }
339 
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;
345 }
346 
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));
359  return 0;
360  }
361  // -1 to exclude this first relocation entry.
362  return FirstReloc->VirtualAddress - 1;
363  }
364  return Sec->NumberOfRelocations;
365 }
366 
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);
370  if (!NumRelocs)
371  return nullptr;
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
376  // relocations.
377  begin++;
378  }
379  if (auto E = Binary::checkOffset(M, uintptr_t(begin),
380  sizeof(coff_relocation) * NumRelocs)) {
381  consumeError(std::move(E));
382  return nullptr;
383  }
384  return begin;
385 }
386 
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));
395 }
396 
398  const coff_section *Sec = toSec(Ref);
399  const coff_relocation *I = getFirstReloc(Sec, Data, base());
400  if (I)
401  I += getNumberOfRelocations(Sec, Data, base());
403  Ret.p = reinterpret_cast<uintptr_t>(I);
404  return relocation_iterator(RelocationRef(Ret, this));
405 }
406 
407 // Initialize the pointer to the symbol table.
408 Error COFFObjectFile::initSymbolTablePtr() {
409  if (COFFHeader)
410  if (Error E = getObject(
411  SymbolTable16, Data, base() + getPointerToSymbolTable(),
413  return E;
414 
415  if (COFFBigObjHeader)
416  if (Error E = getObject(
417  SymbolTable32, Data, base() + getPointerToSymbolTable(),
419  return E;
420 
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.
426  const uint8_t *StringTableAddr = base() + StringTableOffset;
427  const ulittle32_t *StringTableSizePtr;
428  if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr))
429  return E;
430  StringTableSize = *StringTableSizePtr;
431  if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize))
432  return E;
433 
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)
437  StringTableSize = 4;
438 
439  // Check that the string table is null terminated if has any in it.
440  if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
442  return Error::success();
443 }
444 
446  if (PE32Header)
447  return PE32Header->ImageBase;
448  else if (PE32PlusHeader)
449  return PE32PlusHeader->ImageBase;
450  // This actually comes up in practice.
451  return 0;
452 }
453 
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);
460 }
461 
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();
472  }
473  }
475 }
476 
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
483  // overflow.
484  uint32_t OffsetIntoSection = RVA - SectionStart;
485  if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
486  Size <= Section->VirtualSize - OffsetIntoSection) {
487  uintptr_t Begin =
488  uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
489  Contents =
490  ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
491  return Error::success();
492  }
493  }
495 }
496 
497 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
498 // table entry.
500  StringRef &Name) const {
501  uintptr_t IntPtr = 0;
502  if (Error E = getRvaPtr(Rva, IntPtr))
503  return E;
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();
508 }
509 
511  const codeview::DebugInfo *&PDBInfo,
512  StringRef &PDBFileName) const {
513  ArrayRef<uint8_t> InfoBytes;
515  DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
516  return E;
517  if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
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()),
522  InfoBytes.size());
523  // Truncate the name at the first null byte. Ignore any padding.
524  PDBFileName = PDBFileName.split('\0').first;
525  return Error::success();
526 }
527 
529  StringRef &PDBFileName) const {
530  for (const debug_directory &D : debug_directories())
532  return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
533  // If we get here, there is no PDB info to return.
534  PDBInfo = nullptr;
535  PDBFileName = StringRef();
536  return Error::success();
537 }
538 
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.
544  if (!DataEntry)
545  return Error::success();
546 
547  // Do nothing if the pointer to import table is NULL.
548  if (DataEntry->RelativeVirtualAddress == 0)
549  return Error::success();
550 
551  uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
552 
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))
557  return E;
558  if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
559  return E;
560  ImportDirectory = reinterpret_cast<
561  const coff_import_directory_table_entry *>(IntPtr);
562  return Error::success();
563 }
564 
565 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
566 Error COFFObjectFile::initDelayImportTablePtr() {
567  const data_directory *DataEntry =
569  if (!DataEntry)
570  return Error::success();
571  if (DataEntry->RelativeVirtualAddress == 0)
572  return Error::success();
573 
574  uint32_t RVA = DataEntry->RelativeVirtualAddress;
575  NumberOfDelayImportDirectory = DataEntry->Size /
577 
578  uintptr_t IntPtr = 0;
579  if (Error E = getRvaPtr(RVA, IntPtr))
580  return E;
581  DelayImportDirectory = reinterpret_cast<
582  const delay_import_directory_table_entry *>(IntPtr);
583  return Error::success();
584 }
585 
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.
591  if (!DataEntry)
592  return Error::success();
593 
594  // Do nothing if the pointer to export table is NULL.
595  if (DataEntry->RelativeVirtualAddress == 0)
596  return Error::success();
597 
598  uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
599  uintptr_t IntPtr = 0;
600  if (Error E = getRvaPtr(ExportTableRva, IntPtr))
601  return E;
602  ExportDirectory =
603  reinterpret_cast<const export_directory_table_entry *>(IntPtr);
604  return Error::success();
605 }
606 
607 Error COFFObjectFile::initBaseRelocPtr() {
608  const data_directory *DataEntry =
610  if (!DataEntry)
611  return Error::success();
612  if (DataEntry->RelativeVirtualAddress == 0)
613  return Error::success();
614 
615  uintptr_t IntPtr = 0;
616  if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
617  return E;
618  BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
619  IntPtr);
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();
625 }
626 
627 Error COFFObjectFile::initDebugDirectoryPtr() {
628  // Get the RVA of the debug directory. Do nothing if it does not exist.
630  if (!DataEntry)
631  return Error::success();
632 
633  // Do nothing if the RVA is NULL.
634  if (DataEntry->RelativeVirtualAddress == 0)
635  return Error::success();
636 
637  // Check that the size is a multiple of the entry size.
638  if (DataEntry->Size % sizeof(debug_directory) != 0)
640 
641  uintptr_t IntPtr = 0;
642  if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
643  return E;
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();
650 }
651 
652 Error COFFObjectFile::initLoadConfigPtr() {
653  // Get the RVA of the debug directory. Do nothing if it does not exist.
655  if (!DataEntry)
656  return Error::success();
657 
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))
663  return E;
664 
665  LoadConfig = (const void *)IntPtr;
666  return Error::success();
667 }
668 
671  std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
672  if (Error E = Obj->initialize())
673  return std::move(E);
674  return std::move(Obj);
675 }
676 
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) {}
686 
687 Error COFFObjectFile::initialize() {
688  // Check that we at least have enough room for a header.
689  std::error_code EC;
690  if (!checkSize(Data, EC, sizeof(coff_file_header)))
691  return errorCodeToError(EC);
692 
693  // The current location in the file where we are looking at.
694  uint64_t CurPtr = 0;
695 
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;
699 
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) {
710  }
711  CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
712  HasPEHeader = true;
713  }
714  }
715 
716  if (Error E = getObject(COFFHeader, Data, base() + CurPtr))
717  return E;
718 
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))
725  return E;
726 
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);
733  } else {
734  // It's not a bigobj.
735  COFFBigObjHeader = nullptr;
736  }
737  }
738  if (COFFHeader) {
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);
743 
744  if (COFFHeader->isImportLibrary())
745  return errorCodeToError(EC);
746  }
747 
748  if (HasPEHeader) {
749  const pe32_header *Header;
750  if (Error E = getObject(Header, Data, base() + CurPtr))
751  return E;
752 
753  const uint8_t *DataDirAddr;
754  uint64_t DataDirSize;
755  if (Header->Magic == COFF::PE32Header::PE32) {
756  PE32Header = Header;
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;
763  } else {
764  // It's neither PE32 nor PE32+.
766  }
767  if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))
768  return E;
769  }
770 
771  if (COFFHeader)
772  CurPtr += COFFHeader->SizeOfOptionalHeader;
773 
774  assert(COFFHeader || COFFBigObjHeader);
775 
776  if (Error E =
777  getObject(SectionTable, Data, base() + CurPtr,
778  (uint64_t)getNumberOfSections() * sizeof(coff_section)))
779  return E;
780 
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;
789  StringTableSize = 0;
790  }
791  } else {
792  // We had better not have any symbols if we don't have a symbol table.
793  if (getNumberOfSymbols() != 0) {
795  }
796  }
797 
798  // Initialize the pointer to the beginning of the import table.
799  if (Error E = initImportTablePtr())
800  return E;
801  if (Error E = initDelayImportTablePtr())
802  return E;
803 
804  // Initialize the pointer to the export table.
805  if (Error E = initExportTablePtr())
806  return E;
807 
808  // Initialize the pointer to the base relocation table.
809  if (Error E = initBaseRelocPtr())
810  return E;
811 
812  // Initialize the pointer to the export table.
813  if (Error E = initDebugDirectoryPtr())
814  return E;
815 
816  if (Error E = initLoadConfigPtr())
817  return E;
818 
819  return Error::success();
820 }
821 
824  Ret.p = getSymbolTable();
825  return basic_symbol_iterator(SymbolRef(Ret, this));
826 }
827 
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));
833 }
834 
836  if (!ImportDirectory)
837  return import_directory_end();
838  if (ImportDirectory->isNull())
839  return import_directory_end();
841  ImportDirectoryEntryRef(ImportDirectory, 0, this));
842 }
843 
846  ImportDirectoryEntryRef(nullptr, -1, this));
847 }
848 
852  DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
853 }
854 
859  DelayImportDirectory, NumberOfDelayImportDirectory, this));
860 }
861 
864  ExportDirectoryEntryRef(ExportDirectory, 0, this));
865 }
866 
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);
873 }
874 
877  Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
878  return section_iterator(SectionRef(Ret, this));
879 }
880 
883  int NumSections =
884  COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
885  Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
886  return section_iterator(SectionRef(Ret, this));
887 }
888 
890  return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
891 }
892 
894  return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
895 }
896 
898  return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
899 }
900 
902  switch(getMachine()) {
904  return "COFF-i386";
906  return "COFF-x86-64";
908  return "COFF-ARM";
910  return "COFF-ARM64";
911  default:
912  return "COFF-<unknown arch>";
913  }
914 }
915 
917  switch (getMachine()) {
919  return Triple::x86;
921  return Triple::x86_64;
923  return Triple::thumb;
925  return Triple::aarch64;
926  default:
927  return Triple::UnknownArch;
928  }
929 }
930 
932  if (PE32Header)
933  return PE32Header->AddressOfEntryPoint;
934  return 0;
935 }
936 
940 }
941 
946 }
947 
951 }
952 
955 }
956 
958  if (!DataDirectory)
959  return nullptr;
960  assert(PE32Header || PE32PlusHeader);
961  uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
962  : PE32PlusHeader->NumberOfRvaAndSize;
963  if (Index >= NumEnt)
964  return nullptr;
965  return &DataDirectory[Index];
966 }
967 
969  // Perhaps getting the section of a reserved section index should be an error,
970  // but callers rely on this to return null.
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);
976  }
978 }
979 
980 Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
981  if (StringTableSize <= 4)
982  // Tried to get a string from an empty string table.
984  if (Offset >= StringTableSize)
986  return StringRef(StringTable + Offset);
987 }
988 
990  return getSymbolName(Symbol.getGeneric());
991 }
992 
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);
998 
999  // Null terminated, let ::strlen figure out the length.
1000  if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1001  return StringRef(Symbol->Name.ShortName);
1002 
1003  // Not null terminated, use all 8 bytes.
1004  return StringRef(Symbol->Name.ShortName, COFF::NameSize);
1005 }
1006 
1009  const uint8_t *Aux = nullptr;
1010 
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;
1015 #ifndef NDEBUG
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() ||
1019  Offset >=
1020  getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1021  report_fatal_error("Aux Symbol data was outside of symbol table.");
1022 
1023  assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1024  "Aux Symbol data did not point to the beginning of a symbol");
1025 #endif
1026  }
1027  return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1028 }
1029 
1031  uintptr_t Offset =
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());
1037  return Index;
1038 }
1039 
1042  StringRef Name;
1043  if (Sec->Name[COFF::NameSize - 1] == 0)
1044  // Null terminated, let ::strlen figure out the length.
1045  Name = Sec->Name;
1046  else
1047  // Not null terminated, use all 8 bytes.
1048  Name = StringRef(Sec->Name, COFF::NameSize);
1049 
1050  // Check for string table entry. First byte is '/'.
1051  if (Name.startswith("/")) {
1052  uint32_t Offset;
1053  if (Name.startswith("//")) {
1054  if (decodeBase64StringEntry(Name.substr(2), Offset))
1056  "invalid section name");
1057  } else {
1058  if (Name.substr(1).getAsInteger(10, Offset))
1060  "invalid section name");
1061  }
1062  return getString(Offset);
1063  }
1064 
1065  return Name;
1066 }
1067 
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.
1071  //
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.
1074  //
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.
1079  if (getDOSHeader())
1080  return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1081  return Sec->SizeOfRawData;
1082 }
1083 
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;
1095  if (Error E = checkOffset(Data, ConStart, SectionSize))
1096  return E;
1097  Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1098  return Error::success();
1099 }
1100 
1101 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1102  return reinterpret_cast<const coff_relocation*>(Rel.p);
1103 }
1104 
1106  Rel.p = reinterpret_cast<uintptr_t>(
1107  reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1108 }
1109 
1111  const coff_relocation *R = toRel(Rel);
1112  return R->VirtualAddress;
1113 }
1114 
1116  const coff_relocation *R = toRel(Rel);
1117  DataRefImpl Ref;
1119  return symbol_end();
1120  if (SymbolTable16)
1121  Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1122  else if (SymbolTable32)
1123  Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1124  else
1125  llvm_unreachable("no symbol table pointer!");
1126  return symbol_iterator(SymbolRef(Ref, this));
1127 }
1128 
1130  const coff_relocation* R = toRel(Rel);
1131  return R->Type;
1132 }
1133 
1134 const coff_section *
1136  return toSec(Section.getRawDataRefImpl());
1137 }
1138 
1140  if (SymbolTable16)
1141  return toSymb<coff_symbol16>(Ref);
1142  if (SymbolTable32)
1143  return toSymb<coff_symbol32>(Ref);
1144  llvm_unreachable("no symbol table pointer!");
1145 }
1146 
1148  return getCOFFSymbol(Symbol.getRawDataRefImpl());
1149 }
1150 
1151 const coff_relocation *
1153  return toRel(Reloc.getRawDataRefImpl());
1154 }
1155 
1158  return {getFirstReloc(Sec, Data, base()),
1159  getNumberOfRelocations(Sec, Data, base())};
1160 }
1161 
1162 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1163  case COFF::reloc_type: \
1164  return #reloc_type;
1165 
1167  switch (getMachine()) {
1169  switch (Type) {
1187  default:
1188  return "Unknown";
1189  }
1190  break;
1192  switch (Type) {
1210  default:
1211  return "Unknown";
1212  }
1213  break;
1215  switch (Type) {
1234  default:
1235  return "Unknown";
1236  }
1237  break;
1239  switch (Type) {
1251  default:
1252  return "Unknown";
1253  }
1254  break;
1255  default:
1256  return "Unknown";
1257  }
1258 }
1259 
1260 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1261 
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());
1267 }
1268 
1270  return !DataDirectory;
1271 }
1272 
1275  .Case("eh_fram", "eh_frame")
1276  .Default(Name);
1277 }
1278 
1281  return ImportTable == Other.ImportTable && Index == Other.Index;
1282 }
1283 
1285  ++Index;
1286  if (ImportTable[Index].isNull()) {
1287  Index = -1;
1288  ImportTable = nullptr;
1289  }
1290 }
1291 
1293  const coff_import_directory_table_entry *&Result) const {
1294  return getObject(Result, OwningObject->Data, ImportTable + Index);
1295 }
1296 
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));
1303  }
1304  auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1305  return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1306 }
1307 
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);
1314 }
1315 
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.
1322  int Index = 0;
1323  if (Object->getBytesInAddress() == 4) {
1324  auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1325  while (*Entry++)
1326  ++Index;
1327  } else {
1328  auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1329  while (*Entry++)
1330  ++Index;
1331  }
1332  return makeImportedSymbolIterator(Object, IntPtr, Index);
1333 }
1334 
1337  return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1338  OwningObject);
1339 }
1340 
1343  return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1344  OwningObject);
1345 }
1346 
1349  return make_range(imported_symbol_begin(), imported_symbol_end());
1350 }
1351 
1353  return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1354  OwningObject);
1355 }
1356 
1358  return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1359  OwningObject);
1360 }
1361 
1364  return make_range(lookup_table_begin(), lookup_table_end());
1365 }
1366 
1368  uintptr_t IntPtr = 0;
1369  if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1370  return E;
1371  Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1372  return Error::success();
1373 }
1374 
1375 Error
1377  Result = ImportTable[Index].ImportLookupTableRVA;
1378  return Error::success();
1379 }
1380 
1382  uint32_t &Result) const {
1383  Result = ImportTable[Index].ImportAddressTableRVA;
1384  return Error::success();
1385 }
1386 
1389  return Table == Other.Table && Index == Other.Index;
1390 }
1391 
1393  ++Index;
1394 }
1395 
1398  return importedSymbolBegin(Table[Index].DelayImportNameTable,
1399  OwningObject);
1400 }
1401 
1404  return importedSymbolEnd(Table[Index].DelayImportNameTable,
1405  OwningObject);
1406 }
1407 
1410  return make_range(imported_symbol_begin(), imported_symbol_end());
1411 }
1412 
1414  uintptr_t IntPtr = 0;
1415  if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1416  return E;
1417  Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1418  return Error::success();
1419 }
1420 
1422  const delay_import_directory_table_entry *&Result) const {
1423  Result = &Table[Index];
1424  return Error::success();
1425 }
1426 
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))
1433  return E;
1434  if (OwningObject->is64())
1435  Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1436  else
1437  Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1438  return Error::success();
1439 }
1440 
1443  return ExportTable == Other.ExportTable && Index == Other.Index;
1444 }
1445 
1447  ++Index;
1448 }
1449 
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.
1453  uintptr_t IntPtr = 0;
1454  if (Error E = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1455  return E;
1456  Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1457  return Error::success();
1458 }
1459 
1460 // Returns the starting ordinal number.
1462  Result = ExportTable->OrdinalBase;
1463  return Error::success();
1464 }
1465 
1466 // Returns the export ordinal of the current export symbol.
1468  Result = ExportTable->OrdinalBase + Index;
1469  return Error::success();
1470 }
1471 
1472 // Returns the address of the current export symbol.
1474  uintptr_t IntPtr = 0;
1475  if (Error EC =
1476  OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1477  return EC;
1479  reinterpret_cast<const export_address_table_entry *>(IntPtr);
1480  Result = entry[Index].ExportRVA;
1481  return Error::success();
1482 }
1483 
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.
1486 Error
1488  uintptr_t IntPtr = 0;
1489  if (Error EC =
1490  OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1491  return EC;
1492  const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1493 
1494  uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1495  int Offset = 0;
1496  for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1497  I < E; ++I, ++Offset) {
1498  if (*I != Index)
1499  continue;
1500  if (Error EC =
1501  OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1502  return EC;
1503  const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1504  if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1505  return EC;
1506  Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1507  return Error::success();
1508  }
1509  Result = "";
1510  return Error::success();
1511 }
1512 
1514  const data_directory *DataEntry =
1515  OwningObject->getDataDirectory(COFF::EXPORT_TABLE);
1516  if (!DataEntry)
1518  uint32_t RVA;
1519  if (auto EC = getExportRVA(RVA))
1520  return EC;
1521  uint32_t Begin = DataEntry->RelativeVirtualAddress;
1522  uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1523  Result = (Begin <= RVA && RVA < End);
1524  return Error::success();
1525 }
1526 
1528  uint32_t RVA;
1529  if (auto EC = getExportRVA(RVA))
1530  return EC;
1531  uintptr_t IntPtr = 0;
1532  if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1533  return EC;
1534  Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1535  return Error::success();
1536 }
1537 
1539 operator==(const ImportedSymbolRef &Other) const {
1540  return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1541  && Index == Other.Index;
1542 }
1543 
1545  ++Index;
1546 }
1547 
1549  uint32_t RVA;
1550  if (Entry32) {
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();
1555  } else {
1556  if (Entry64[Index].isOrdinal())
1557  return Error::success();
1558  RVA = Entry64[Index].getHintNameRVA();
1559  }
1560  uintptr_t IntPtr = 0;
1561  if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
1562  return EC;
1563  // +2 because the first two bytes is hint.
1564  Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1565  return Error::success();
1566 }
1567 
1569  if (Entry32)
1570  Result = Entry32[Index].isOrdinal();
1571  else
1572  Result = Entry64[Index].isOrdinal();
1573  return Error::success();
1574 }
1575 
1577  if (Entry32)
1578  Result = Entry32[Index].getHintNameRVA();
1579  else
1580  Result = Entry64[Index].getHintNameRVA();
1581  return Error::success();
1582 }
1583 
1585  uint32_t RVA;
1586  if (Entry32) {
1587  if (Entry32[Index].isOrdinal()) {
1588  Result = Entry32[Index].getOrdinal();
1589  return Error::success();
1590  }
1591  RVA = Entry32[Index].getHintNameRVA();
1592  } else {
1593  if (Entry64[Index].isOrdinal()) {
1594  Result = Entry64[Index].getOrdinal();
1595  return Error::success();
1596  }
1597  RVA = Entry64[Index].getHintNameRVA();
1598  }
1599  uintptr_t IntPtr = 0;
1600  if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
1601  return EC;
1602  Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1603  return Error::success();
1604 }
1605 
1608  return COFFObjectFile::create(Object);
1609 }
1610 
1611 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1612  return Header == Other.Header && Index == Other.Index;
1613 }
1614 
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);
1627  Index = 0;
1628  } else {
1629  ++Index;
1630  }
1631 }
1632 
1634  auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1635  Type = Entry[Index].getType();
1636  return Error::success();
1637 }
1638 
1640  auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1641  Result = Header->PageRVA + Entry[Index].getOffset();
1642  return Error::success();
1643 }
1644 
1645 #define RETURN_IF_ERROR(Expr) \
1646  do { \
1647  Error E = (Expr); \
1648  if (E) \
1649  return std::move(E); \
1650  } while (0)
1651 
1653 ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1654  BinaryStreamReader Reader = BinaryStreamReader(BBS);
1655  Reader.setOffset(Offset);
1656  uint16_t Length;
1657  RETURN_IF_ERROR(Reader.readInteger(Length));
1658  ArrayRef<UTF16> RawDirString;
1659  RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1660  return RawDirString;
1661 }
1662 
1665  return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1666 }
1667 
1669 ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1670  const coff_resource_dir_table *Table = nullptr;
1671 
1672  BinaryStreamReader Reader(BBS);
1673  Reader.setOffset(Offset);
1674  RETURN_IF_ERROR(Reader.readObject(Table));
1675  assert(Table != nullptr);
1676  return *Table;
1677 }
1678 
1680 ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
1681  const coff_resource_dir_entry *Entry = nullptr;
1682 
1683  BinaryStreamReader Reader(BBS);
1684  Reader.setOffset(Offset);
1685  RETURN_IF_ERROR(Reader.readObject(Entry));
1686  assert(Entry != nullptr);
1687  return *Entry;
1688 }
1689 
1691 ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
1692  const coff_resource_data_entry *Entry = nullptr;
1693 
1694  BinaryStreamReader Reader(BBS);
1695  Reader.setOffset(Offset);
1696  RETURN_IF_ERROR(Reader.readObject(Entry));
1697  assert(Entry != nullptr);
1698  return *Entry;
1699 }
1700 
1703  assert(Entry.Offset.isSubDir());
1704  return getTableAtOffset(Entry.Offset.value());
1705 }
1706 
1709  assert(!Entry.Offset.isSubDir());
1710  return getDataEntryAtOffset(Entry.Offset.value());
1711 }
1712 
1714  return getTableAtOffset(0);
1715 }
1716 
1719  uint32_t Index) {
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));
1726 }
1727 
1729  for (const SectionRef &S : O->sections()) {
1730  Expected<StringRef> Name = S.getName();
1731  if (!Name)
1732  return Name.takeError();
1733 
1734  if (*Name == ".rsrc" || *Name == ".rsrc$01")
1735  return load(O, S);
1736  }
1738  "no resource section found");
1739 }
1740 
1742  Obj = O;
1743  Section = S;
1744  Expected<StringRef> Contents = Section.getContents();
1745  if (!Contents)
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;
1756  });
1757  return Error::success();
1758 }
1759 
1762  if (!Obj)
1763  return createStringError(object_error::parse_failed, "no object provided");
1764 
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),
1770  ulittle16_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;
1775  });
1776 
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;
1781  uint16_t RVAReloc;
1782  switch (Obj->getMachine()) {
1784  RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
1785  break;
1787  RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
1788  break;
1790  RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
1791  break;
1793  RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
1794  break;
1795  default:
1797  "unsupported architecture");
1798  }
1799  if (R.Type != RVAReloc)
1801  "unexpected relocation type");
1802  // Get the relocation's symbol
1803  Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
1804  if (!Sym)
1805  return Sym.takeError();
1806  // And the symbol's section
1808  Obj->getSection(Sym->getSectionNumber());
1809  if (!Section)
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())
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,
1822  Entry.DataSize);
1823  } else {
1824  // Relocatable objects need a relocation for the DataRVA field.
1825  if (Obj->isRelocatableObject())
1827  "no relocation found for DataRVA");
1828 
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();
1836  if (!Contents)
1837  return Contents.takeError();
1838  return Contents->slice(Offset, Offset + Entry.DataSize);
1839  }
1840  }
1842  "address not found in image");
1843  }
1844 }
bool isNull() const
Definition: COFF.h:562
Error getRvaPtr(uint32_t Rva, uintptr_t &Res) const
uint32_t getAlignment() const
Definition: COFF.h:459
void cantFail(Error Err, const char *Msg=nullptr)
Report a fatal error if Err is a failure value.
Definition: Error.h:708
bool isCommon() const
Definition: COFF.h:381
static uint32_t getNumberOfRelocations(const coff_section *Sec, MemoryBufferRef M, const uint8_t *base)
Error getExportRVA(uint32_t &Result) const
static Expected< std::unique_ptr< COFFObjectFile > > create(MemoryBufferRef Object)
The 64-bit PE header that follows the COFF header.
Definition: COFF.h:140
uint32_t getSymbolAlignment(DataRefImpl Symb) const override
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:224
section_iterator section_begin() const override
support::ulittle16_t Machine
Definition: COFF.h:76
An implementation of BinaryStream which holds its entire data set in a single contiguous buffer...
friend class SymbolRef
Definition: ObjectFile.h:243
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
This class represents lattice values for constants.
Definition: AllocatorList.h:23
const coff_section * getCOFFSection(const SectionRef &Section) const
Error getDelayImportTable(const delay_import_directory_table_entry *&Result) const
Error readInteger(T &Dest)
Read an integer of the specified endianness into Dest and update the stream&#39;s offset.
Error getType(uint8_t &Type) const
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
friend class SectionRef
Definition: ObjectFile.h:257
uint64_t getRelocationOffset(DataRefImpl Rel) const override
LLVM_NODISCARD bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:289
support::ulittle32_t VirtualAddress
Definition: COFF.h:443
bool operator==(const DelayImportDirectoryEntryRef &Other) const
Definition: COFF.h:222
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
void moveSectionNext(DataRefImpl &Sec) const override
union llvm::object::coff_resource_dir_entry::@294 Identifier
COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const
export_directory_iterator export_directory_end() const
Error getOrdinalBase(uint32_t &Result) const
Error readObject(const T *&Dest)
Get a pointer to an object of type T from the underlying stream, as if by memcpy, and store the resul...
Error getImportAddressTableRVA(uint32_t &Result) const
base_reloc_iterator base_reloc_end() const
void moveRelocationNext(DataRefImpl &Rel) const override
support::ulittle16_t Version
Definition: COFF.h:90
support::ulittle16_t NumberOfSections
Definition: COFF.h:77
content_iterator< DelayImportDirectoryEntryRef > delay_import_directory_iterator
Definition: COFF.h:47
uint32_t getPointerToSymbolTable() const
Definition: COFF.h:866
static const coff_relocation * getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base)
iterator_range< imported_symbol_iterator > imported_symbols() const
bool isSectionDefinition() const
Definition: COFF.h:417
Error getDllName(StringRef &Result) const
bool isSectionCompressed(DataRefImpl Sec) const override
const uint8_t * base() const
Definition: ObjectFile.h:231
uint8_t getNumberOfAuxSymbols() const
Definition: COFF.h:343
export_directory_iterator export_directory_begin() const
Definition: COFF.h:236
Error takeError()
Take ownership of the stored error.
Definition: Error.h:557
detail::packed_endian_specific_integral< uint16_t, little, unaligned > ulittle16_t
Definition: Endian.h:270
uint64_t getSymbolValueImpl(DataRefImpl Symb) const override
Error getOrdinal(uint16_t &Result) const
static const char BigObjMagic[]
Definition: COFF.h:38
const coff_relocation * getCOFFRelocation(const RelocationRef &Reloc) const
import_directory_iterator import_directory_begin() const
iterator_range< const debug_directory * > debug_directories() const
Definition: COFF.h:975
uint8_t getBytesInAddress() const override
The number of bytes used to represent an address in this object file format.
basic_symbol_iterator symbol_end() const override
detail::packed_endian_specific_integral< uint64_t, little, unaligned > ulittle64_t
Definition: Endian.h:274
char ShortName[COFF::NameSize]
Definition: COFF.h:271
Expected< uint32_t > getSymbolFlags(DataRefImpl Symb) const override
support::ulittle64_t ImageBase
Definition: COFF.h:149
friend class ExportDirectoryEntryRef
Definition: COFF.h:770
static Error checkOffset(MemoryBufferRef M, uintptr_t Addr, const uint64_t Size)
Definition: Binary.h:163
uint64_t getSectionAlignment(DataRefImpl Sec) const override
char Name[COFF::NameSize]
Definition: COFF.h:441
Error isOrdinal(bool &Result) const
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
Definition: ArrayRef.h:458
support::ulittle32_t AddressOfEntryPoint
Definition: COFF.h:111
DataRefImpl getRawDataRefImpl() const
Definition: SymbolicFile.h:202
Error isForwarder(bool &Result) const
support::ulittle16_t NumberOfNameEntries
Definition: COFF.h:755
Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, ArrayRef< uint8_t > &Contents) const
Given an RVA base and size, returns a valid array of bytes or an error code if the RVA and size is no...
This is a value type class that represents a single relocation in the list of relocations in the obje...
Definition: ObjectFile.h:51
support::ulittle16_t SizeOfOptionalHeader
Definition: COFF.h:81
Expected< uint64_t > getSymbolAddress(DataRefImpl Symb) const override
static Expected< const T * > getObject(MemoryBufferRef M, const void *Ptr, const uint64_t Size=sizeof(T))
The access may reference the value stored in memory.
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
iterator_range< base_reloc_iterator > base_relocs() const
Tagged union holding either a T or a Error.
Definition: APFloat.h:42
static imported_symbol_iterator importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object)
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:612
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:156
bool isReservedSectionNumber(int32_t SectionNumber)
Definition: COFF.h:728
imported_symbol_iterator lookup_table_begin() const
bool isDebugSection(StringRef SectionName) const override
support::ulittle32_t VirtualSize
Definition: COFF.h:442
#define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:47
iterator_range< imported_symbol_iterator > imported_symbols() const
Error load(const COFFObjectFile *O)
imported_symbol_iterator imported_symbol_end() const
Expected< SymbolRef::Type > getSymbolType(DataRefImpl Symb) const override
int32_t getSectionNumber() const
Definition: COFF.h:322
#define RETURN_IF_ERROR(Expr)
Error getForwardTo(StringRef &Result) const
uint64_t getSectionAddress(DataRefImpl Sec) const override
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:160
union llvm::object::coff_resource_dir_entry::@295 Offset
Error getDebugPDBInfo(const debug_directory *DebugDir, const codeview::DebugInfo *&Info, StringRef &PDBFileName) const
Get PDB information out of a codeview debug directory entry.
section_iterator_range sections() const
Definition: ObjectFile.h:319
Error getOrdinal(uint32_t &Result) const
void moveSymbolNext(DataRefImpl &Symb) const override
union llvm::object::coff_symbol_generic::@293 Name
uint8_t getComplexType() const
Definition: COFF.h:350
support::ulittle32_t ExportRVA
Definition: COFF.h:237
Error getSymbolName(StringRef &Result) const
bool isRelocatableObject() const override
True if this is a relocatable object (.o/.obj).
Error getImportAddress(int AddrIndex, uint64_t &Result) const
std::enable_if_t< std::numeric_limits< T >::is_signed, bool > getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:511
Expected< StringRef > getContents(const coff_resource_data_entry &Entry)
static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size)
relocation_iterator section_rel_end(DataRefImpl Sec) const override
support::ulittle16_t Magic
Definition: COFF.h:105
Expected< ArrayRef< uint8_t > > getSectionContents(DataRefImpl Sec) const override
#define P(N)
support::ulittle32_t Characteristics
Definition: COFF.h:450
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:42
base_reloc_iterator base_reloc_begin() const
support::ulittle32_t NumberOfRvaAndSize
Definition: COFF.h:169
Expected< section_iterator > getSymbolSection(DataRefImpl Symb) const override
content_iterator< ExportDirectoryEntryRef > export_directory_iterator
Definition: COFF.h:48
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
support::ulittle16_t NumberOfIDEntries
Definition: COFF.h:756
Error getImportTableEntry(const coff_import_directory_table_entry *&Result) const
size_t getBufferSize() const
Definition: MemoryBuffer.h:280
delay_import_directory_iterator delay_import_directory_end() const
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
detail::packed_endian_specific_integral< uint32_t, little, unaligned > ulittle32_t
Definition: Endian.h:272
bool operator==(const BaseRelocRef &Other) const
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:156
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:87
Expected< const coff_resource_data_entry & > getEntryData(const coff_resource_dir_entry &Entry)
Error getImportLookupTableRVA(uint32_t &Result) const
const dos_header * getDOSHeader() const
Definition: COFF.h:979
Error getRVA(uint32_t &Result) const
content_iterator< ImportedSymbolRef > imported_symbol_iterator
Definition: COFF.h:49
The 32-bit PE header that follows the COFF header.
Definition: COFF.h:104
Definition: COFF.h:743
import_lookup_table_entry< support::little64_t > import_lookup_table_entry64
Definition: COFF.h:208
bool operator==(const ImportedSymbolRef &Other) const
delay_import_directory_iterator delay_import_directory_begin() const
support::ulittle32_t RelativeVirtualAddress
Definition: COFF.h:173
content_iterator< ImportDirectoryEntryRef > import_directory_iterator
Definition: COFF.h:45
Expected< StringRef > getSymbolName(DataRefImpl Symb) const override
Expected< ExpressionValue > min(const ExpressionValue &Lhs, const ExpressionValue &Rhs)
Definition: FileCheck.cpp:305
support::ulittle32_t DataSize
Definition: COFF.h:745
imported_symbol_iterator imported_symbol_begin() const
Error getName(StringRef &Result) const
relocation_iterator section_rel_begin(DataRefImpl Sec) const override
const void * getRawPtr() const
Definition: COFF.h:286
Error getVaPtr(uint64_t VA, uintptr_t &Res) const
support::ulittle16_t Type
Definition: COFF.h:477
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1433
const coff_symbol_generic * getGeneric() const
Definition: COFF.h:290
static imported_symbol_iterator makeImportedSymbolIterator(const COFFObjectFile *Object, uintptr_t Ptr, int Index)
StringTableOffset Offset
Definition: COFF.h:272
support::ulittle32_t SizeOfRawData
Definition: COFF.h:444
bool isImportLibrary() const
Definition: COFF.h:84
uint64_t getRelocationType(DataRefImpl Rel) const override
StringRef getFileFormatName() const override
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:521
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1006
unsigned getSectionID(SectionRef Sec) const
support::ulittle32_t VirtualAddress
Definition: COFF.h:475
support::ulittle32_t SymbolTableIndex
Definition: COFF.h:476
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isUndefined() const
Definition: COFF.h:386
const T * data() const
Definition: ArrayRef.h:153
StringRef getRelocationTypeName(uint16_t Type) const
import_directory_iterator import_directory_end() const
uint16_t getMachine() const
Definition: COFF.h:822
Expected< const coff_section * > getSection(int32_t index) const
Definition: COFF.h:555
friend class ImportDirectoryEntryRef
Definition: COFF.h:769
Expected< uint64_t > getSymbolValue(DataRefImpl Symb) const
Definition: ObjectFile.cpp:57
const coff_aux_weak_external * getWeakExternal() const
Definition: COFF.h:366
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
imported_symbol_iterator imported_symbol_begin() const
void setOffset(uint32_t Off)
static ErrorSuccess success()
Create a success value.
Definition: Error.h:332
support::ulittle32_t PointerToRawData
Definition: COFF.h:445
friend class RelocationRef
Definition: ObjectFile.h:283
iterator_range< import_directory_iterator > import_directories() const
Error getName(StringRef &Result) const
static Expected< std::unique_ptr< COFFObjectFile > > createCOFFObjectFile(MemoryBufferRef Object)
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:350
Expected< const coff_resource_dir_table & > getEntrySubDir(const coff_resource_dir_entry &Entry)
uint32_t getNumberOfSections() const
Definition: COFF.h:858
uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override
Expected< ArrayRef< UTF16 > > getEntryNameString(const coff_resource_dir_entry &Entry)
basic_symbol_iterator symbol_begin() const override
static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result)
LLVM_NODISCARD std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:730
Definition: COFF.h:713
bool isSectionData(DataRefImpl Sec) const override
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Expected< StringRef > getSectionName(DataRefImpl Sec) const override
content_iterator< BasicSymbolRef > basic_symbol_iterator
Definition: SymbolicFile.h:137
The DOS compatible header at the front of all PE/COFF executables.
Definition: COFF.h:53
A range adaptor for a pair of iterators.
section_iterator section_end() const override
support::ulittle32_t AddressOfRawData
Definition: COFF.h:184
MemoryBufferRef Data
Definition: Binary.h:37
size_t getSymbolTableEntrySize() const
Definition: COFF.h:1021
Expected< uint64_t > getStartAddress() const override
support::ulittle32_t Size
Definition: COFF.h:174
Expected< const coff_resource_dir_entry & > getTableEntry(const coff_resource_dir_table &Table, uint32_t Index)
Triple::ArchType getArch() const override
This is a value type class that represents a single symbol in the list of symbols in the object file...
Definition: ObjectFile.h:164
iterator begin() const
Definition: StringRef.h:131
support::ulittle32_t ImageBase
Definition: COFF.h:114
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:433
support::ulittle32_t Zeroes
Definition: COFF.h:245
StringRef mapDebugSectionName(StringRef Name) const override
Maps a debug section name to a standard DWARF section name.
ArrayRef< coff_relocation > getRelocations(const coff_section *Sec) const
bool operator==(const ExportDirectoryEntryRef &Other) const
symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override
bool isWeakExternal() const
Definition: COFF.h:391
Definition: COFF.h:720
bool isSectionText(DataRefImpl Sec) const override
const data_directory * getDataDirectory(uint32_t index) const
Merge contiguous icmps into a memcmp
Definition: MergeICmps.cpp:928
Error getSymbolName(StringRef &Result) const
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition: ArrayRef.h:195
Expected< const coff_resource_dir_table & > getBaseTable()
detail::packed_endian_specific_integral< int16_t, little, unaligned > little16_t
Definition: Endian.h:277
support::ulittle32_t AddressTableEntries
Definition: COFF.h:229
#define I(x, y, z)
Definition: MD5.cpp:59
iterator_range< export_directory_iterator > export_directories() const
static const char PEMagic[]
Definition: COFF.h:36
uint32_t Size
Definition: Profile.cpp:46
support::ulittle32_t DataRVA
Definition: COFF.h:744
Definition: COFF.h:210
bool isAnyUndefined() const
Definition: COFF.h:405
bool isSectionVirtual(DataRefImpl Sec) const override
static imported_symbol_iterator importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object)
ArrayRef< uint8_t > getSymbolAuxData(COFFSymbolRef Symbol) const
uint64_t getSectionSize(DataRefImpl Sec) const override
iterator_range< imported_symbol_iterator > lookup_table_symbols() const
uint8_t NumberOfAuxSymbols
Definition: COFF.h:262
support::ulittle32_t SizeOfData
Definition: COFF.h:183
bool isSectionBSS(DataRefImpl Sec) const override
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
support::ulittle32_t AddressOfNewExeHeader
Definition: COFF.h:72
uintptr_t getSymbolTable() const
Definition: COFF.h:814
Error getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const
bool isFileRecord() const
Definition: COFF.h:409
LLVM Value Representation.
Definition: Value.h:74
content_iterator< BaseRelocRef > base_reloc_iterator
Definition: COFF.h:50
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
imported_symbol_iterator imported_symbol_end() const
content_iterator< RelocationRef > relocation_iterator
Definition: ObjectFile.h:76
import_lookup_table_entry< support::little32_t > import_lookup_table_entry32
Definition: COFF.h:206
support::ulittle32_t NumberOfRvaAndSize
Definition: COFF.h:136
uint32_t getValue() const
Definition: COFF.h:317
print Instructions which execute on loop entry
Provides read only access to a subclass of BinaryStream.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:57
bool operator==(const ImportDirectoryEntryRef &Other) const
Error getHintNameRVA(uint32_t &Result) const
uint32_t getSymbolIndex(COFFSymbolRef Symbol) const
bool isExternal() const
Definition: COFF.h:377
iterator end() const
Definition: StringRef.h:133
imported_symbol_iterator lookup_table_end() const
uint64_t getSectionIndex(DataRefImpl Sec) const override
unsigned getSymbolSectionID(SymbolRef Sym) const
DataRefImpl getRawDataRefImpl() const
Definition: ObjectFile.h:559
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 ...
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1202
iterator_range< delay_import_directory_iterator > delay_import_directories() const
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:80
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:703
uint32_t getNumberOfSymbols() const
Definition: COFF.h:883
support::ulittle32_t Offset
Definition: COFF.h:246
A function that returns a base type.
Definition: COFF.h:261