Coverage Report

Created: 2018-07-18 22:01

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/include/llvm/Object/COFF.h
Line
Count
Source (jump to first uncovered line)
1
//===- COFF.h - COFF object file implementation -----------------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This file declares the COFFObjectFile class.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_OBJECT_COFF_H
15
#define LLVM_OBJECT_COFF_H
16
17
#include "llvm/ADT/iterator_range.h"
18
#include "llvm/BinaryFormat/COFF.h"
19
#include "llvm/MC/SubtargetFeature.h"
20
#include "llvm/Object/Binary.h"
21
#include "llvm/Object/CVDebugRecord.h"
22
#include "llvm/Object/Error.h"
23
#include "llvm/Object/ObjectFile.h"
24
#include "llvm/Support/BinaryByteStream.h"
25
#include "llvm/Support/ConvertUTF.h"
26
#include "llvm/Support/Endian.h"
27
#include "llvm/Support/ErrorHandling.h"
28
#include <cassert>
29
#include <cstddef>
30
#include <cstdint>
31
#include <system_error>
32
33
namespace llvm {
34
35
template <typename T> class ArrayRef;
36
37
namespace object {
38
39
class BaseRelocRef;
40
class DelayImportDirectoryEntryRef;
41
class ExportDirectoryEntryRef;
42
class ImportDirectoryEntryRef;
43
class ImportedSymbolRef;
44
class ResourceSectionRef;
45
46
using import_directory_iterator = content_iterator<ImportDirectoryEntryRef>;
47
using delay_import_directory_iterator =
48
    content_iterator<DelayImportDirectoryEntryRef>;
49
using export_directory_iterator = content_iterator<ExportDirectoryEntryRef>;
50
using imported_symbol_iterator = content_iterator<ImportedSymbolRef>;
51
using base_reloc_iterator = content_iterator<BaseRelocRef>;
52
53
/// The DOS compatible header at the front of all PE/COFF executables.
54
struct dos_header {
55
  char                 Magic[2];
56
  support::ulittle16_t UsedBytesInTheLastPage;
57
  support::ulittle16_t FileSizeInPages;
58
  support::ulittle16_t NumberOfRelocationItems;
59
  support::ulittle16_t HeaderSizeInParagraphs;
60
  support::ulittle16_t MinimumExtraParagraphs;
61
  support::ulittle16_t MaximumExtraParagraphs;
62
  support::ulittle16_t InitialRelativeSS;
63
  support::ulittle16_t InitialSP;
64
  support::ulittle16_t Checksum;
65
  support::ulittle16_t InitialIP;
66
  support::ulittle16_t InitialRelativeCS;
67
  support::ulittle16_t AddressOfRelocationTable;
68
  support::ulittle16_t OverlayNumber;
69
  support::ulittle16_t Reserved[4];
70
  support::ulittle16_t OEMid;
71
  support::ulittle16_t OEMinfo;
72
  support::ulittle16_t Reserved2[10];
73
  support::ulittle32_t AddressOfNewExeHeader;
74
};
75
76
struct coff_file_header {
77
  support::ulittle16_t Machine;
78
  support::ulittle16_t NumberOfSections;
79
  support::ulittle32_t TimeDateStamp;
80
  support::ulittle32_t PointerToSymbolTable;
81
  support::ulittle32_t NumberOfSymbols;
82
  support::ulittle16_t SizeOfOptionalHeader;
83
  support::ulittle16_t Characteristics;
84
85
34.5k
  bool isImportLibrary() const { return NumberOfSections == 0xffff; }
86
};
87
88
struct coff_bigobj_file_header {
89
  support::ulittle16_t Sig1;
90
  support::ulittle16_t Sig2;
91
  support::ulittle16_t Version;
92
  support::ulittle16_t Machine;
93
  support::ulittle32_t TimeDateStamp;
94
  uint8_t              UUID[16];
95
  support::ulittle32_t unused1;
96
  support::ulittle32_t unused2;
97
  support::ulittle32_t unused3;
98
  support::ulittle32_t unused4;
99
  support::ulittle32_t NumberOfSections;
100
  support::ulittle32_t PointerToSymbolTable;
101
  support::ulittle32_t NumberOfSymbols;
102
};
103
104
/// The 32-bit PE header that follows the COFF header.
105
struct pe32_header {
106
  support::ulittle16_t Magic;
107
  uint8_t MajorLinkerVersion;
108
  uint8_t MinorLinkerVersion;
109
  support::ulittle32_t SizeOfCode;
110
  support::ulittle32_t SizeOfInitializedData;
111
  support::ulittle32_t SizeOfUninitializedData;
112
  support::ulittle32_t AddressOfEntryPoint;
113
  support::ulittle32_t BaseOfCode;
114
  support::ulittle32_t BaseOfData;
115
  support::ulittle32_t ImageBase;
116
  support::ulittle32_t SectionAlignment;
117
  support::ulittle32_t FileAlignment;
118
  support::ulittle16_t MajorOperatingSystemVersion;
119
  support::ulittle16_t MinorOperatingSystemVersion;
120
  support::ulittle16_t MajorImageVersion;
121
  support::ulittle16_t MinorImageVersion;
122
  support::ulittle16_t MajorSubsystemVersion;
123
  support::ulittle16_t MinorSubsystemVersion;
124
  support::ulittle32_t Win32VersionValue;
125
  support::ulittle32_t SizeOfImage;
126
  support::ulittle32_t SizeOfHeaders;
127
  support::ulittle32_t CheckSum;
128
  support::ulittle16_t Subsystem;
129
  // FIXME: This should be DllCharacteristics.
130
  support::ulittle16_t DLLCharacteristics;
131
  support::ulittle32_t SizeOfStackReserve;
132
  support::ulittle32_t SizeOfStackCommit;
133
  support::ulittle32_t SizeOfHeapReserve;
134
  support::ulittle32_t SizeOfHeapCommit;
135
  support::ulittle32_t LoaderFlags;
136
  // FIXME: This should be NumberOfRvaAndSizes.
137
  support::ulittle32_t NumberOfRvaAndSize;
138
};
139
140
/// The 64-bit PE header that follows the COFF header.
141
struct pe32plus_header {
142
  support::ulittle16_t Magic;
143
  uint8_t MajorLinkerVersion;
144
  uint8_t MinorLinkerVersion;
145
  support::ulittle32_t SizeOfCode;
146
  support::ulittle32_t SizeOfInitializedData;
147
  support::ulittle32_t SizeOfUninitializedData;
148
  support::ulittle32_t AddressOfEntryPoint;
149
  support::ulittle32_t BaseOfCode;
150
  support::ulittle64_t ImageBase;
151
  support::ulittle32_t SectionAlignment;
152
  support::ulittle32_t FileAlignment;
153
  support::ulittle16_t MajorOperatingSystemVersion;
154
  support::ulittle16_t MinorOperatingSystemVersion;
155
  support::ulittle16_t MajorImageVersion;
156
  support::ulittle16_t MinorImageVersion;
157
  support::ulittle16_t MajorSubsystemVersion;
158
  support::ulittle16_t MinorSubsystemVersion;
159
  support::ulittle32_t Win32VersionValue;
160
  support::ulittle32_t SizeOfImage;
161
  support::ulittle32_t SizeOfHeaders;
162
  support::ulittle32_t CheckSum;
163
  support::ulittle16_t Subsystem;
164
  support::ulittle16_t DLLCharacteristics;
165
  support::ulittle64_t SizeOfStackReserve;
166
  support::ulittle64_t SizeOfStackCommit;
167
  support::ulittle64_t SizeOfHeapReserve;
168
  support::ulittle64_t SizeOfHeapCommit;
169
  support::ulittle32_t LoaderFlags;
170
  support::ulittle32_t NumberOfRvaAndSize;
171
};
172
173
struct data_directory {
174
  support::ulittle32_t RelativeVirtualAddress;
175
  support::ulittle32_t Size;
176
};
177
178
struct debug_directory {
179
  support::ulittle32_t Characteristics;
180
  support::ulittle32_t TimeDateStamp;
181
  support::ulittle16_t MajorVersion;
182
  support::ulittle16_t MinorVersion;
183
  support::ulittle32_t Type;
184
  support::ulittle32_t SizeOfData;
185
  support::ulittle32_t AddressOfRawData;
186
  support::ulittle32_t PointerToRawData;
187
};
188
189
template <typename IntTy>
190
struct import_lookup_table_entry {
191
  IntTy Data;
192
193
170
  bool isOrdinal() const { return Data < 0; }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<int, (llvm::support::endianness)1, 1ul> >::isOrdinal() const
Line
Count
Source
193
106
  bool isOrdinal() const { return Data < 0; }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<long long, (llvm::support::endianness)1, 1ul> >::isOrdinal() const
Line
Count
Source
193
64
  bool isOrdinal() const { return Data < 0; }
194
195
6
  uint16_t getOrdinal() const {
196
6
    assert(isOrdinal() && "ILT entry is not an ordinal!");
197
6
    return Data & 0xFFFF;
198
6
  }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<int, (llvm::support::endianness)1, 1ul> >::getOrdinal() const
Line
Count
Source
195
1
  uint16_t getOrdinal() const {
196
1
    assert(isOrdinal() && "ILT entry is not an ordinal!");
197
1
    return Data & 0xFFFF;
198
1
  }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<long long, (llvm::support::endianness)1, 1ul> >::getOrdinal() const
Line
Count
Source
195
5
  uint16_t getOrdinal() const {
196
5
    assert(isOrdinal() && "ILT entry is not an ordinal!");
197
5
    return Data & 0xFFFF;
198
5
  }
199
200
158
  uint32_t getHintNameRVA() const {
201
158
    assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
202
158
    return Data & 0xFFFFFFFF;
203
158
  }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<int, (llvm::support::endianness)1, 1ul> >::getHintNameRVA() const
Line
Count
Source
200
104
  uint32_t getHintNameRVA() const {
201
104
    assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
202
104
    return Data & 0xFFFFFFFF;
203
104
  }
llvm::object::import_lookup_table_entry<llvm::support::detail::packed_endian_specific_integral<long long, (llvm::support::endianness)1, 1ul> >::getHintNameRVA() const
Line
Count
Source
200
54
  uint32_t getHintNameRVA() const {
201
54
    assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!");
202
54
    return Data & 0xFFFFFFFF;
203
54
  }
204
};
205
206
using import_lookup_table_entry32 =
207
    import_lookup_table_entry<support::little32_t>;
208
using import_lookup_table_entry64 =
209
    import_lookup_table_entry<support::little64_t>;
210
211
struct delay_import_directory_table_entry {
212
  // dumpbin reports this field as "Characteristics" instead of "Attributes".
213
  support::ulittle32_t Attributes;
214
  support::ulittle32_t Name;
215
  support::ulittle32_t ModuleHandle;
216
  support::ulittle32_t DelayImportAddressTable;
217
  support::ulittle32_t DelayImportNameTable;
218
  support::ulittle32_t BoundDelayImportTable;
219
  support::ulittle32_t UnloadDelayImportTable;
220
  support::ulittle32_t TimeStamp;
221
};
222
223
struct export_directory_table_entry {
224
  support::ulittle32_t ExportFlags;
225
  support::ulittle32_t TimeDateStamp;
226
  support::ulittle16_t MajorVersion;
227
  support::ulittle16_t MinorVersion;
228
  support::ulittle32_t NameRVA;
229
  support::ulittle32_t OrdinalBase;
230
  support::ulittle32_t AddressTableEntries;
231
  support::ulittle32_t NumberOfNamePointers;
232
  support::ulittle32_t ExportAddressTableRVA;
233
  support::ulittle32_t NamePointerRVA;
234
  support::ulittle32_t OrdinalTableRVA;
235
};
236
237
union export_address_table_entry {
238
  support::ulittle32_t ExportRVA;
239
  support::ulittle32_t ForwarderRVA;
240
};
241
242
using export_name_pointer_table_entry = support::ulittle32_t;
243
using export_ordinal_table_entry = support::ulittle16_t;
244
245
struct StringTableOffset {
246
  support::ulittle32_t Zeroes;
247
  support::ulittle32_t Offset;
248
};
249
250
template <typename SectionNumberType>
251
struct coff_symbol {
252
  union {
253
    char ShortName[COFF::NameSize];
254
    StringTableOffset Offset;
255
  } Name;
256
257
  support::ulittle32_t Value;
258
  SectionNumberType SectionNumber;
259
260
  support::ulittle16_t Type;
261
262
  uint8_t StorageClass;
263
  uint8_t NumberOfAuxSymbols;
264
};
265
266
using coff_symbol16 = coff_symbol<support::ulittle16_t>;
267
using coff_symbol32 = coff_symbol<support::ulittle32_t>;
268
269
// Contains only common parts of coff_symbol16 and coff_symbol32.
270
struct coff_symbol_generic {
271
  union {
272
    char ShortName[COFF::NameSize];
273
    StringTableOffset Offset;
274
  } Name;
275
  support::ulittle32_t Value;
276
};
277
278
struct coff_aux_section_definition;
279
280
class COFFSymbolRef {
281
public:
282
  COFFSymbolRef() = default;
283
17.3k
  COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {}
284
4
  COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {}
285
286
368
  const void *getRawPtr() const {
287
368
    return CS16 ? 
static_cast<const void *>(CS16)364
:
CS324
;
288
368
  }
289
290
7.47k
  const coff_symbol_generic *getGeneric() const {
291
7.47k
    if (CS16)
292
7.47k
      return reinterpret_cast<const coff_symbol_generic *>(CS16);
293
4
    return reinterpret_cast<const coff_symbol_generic *>(CS32);
294
4
  }
295
296
0
  friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) {
297
0
    return A.getRawPtr() < B.getRawPtr();
298
0
  }
299
300
  bool isBigObj() const {
301
    if (CS16)
302
      return false;
303
    if (CS32)
304
      return true;
305
    llvm_unreachable("COFFSymbolRef points to nothing!");
306
  }
307
308
0
  const char *getShortName() const {
309
0
    return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName;
310
0
  }
311
312
0
  const StringTableOffset &getStringTableOffset() const {
313
0
    assert(isSet() && "COFFSymbolRef points to nothing!");
314
0
    return CS16 ? CS16->Name.Offset : CS32->Name.Offset;
315
0
  }
316
317
3.35k
  uint32_t getValue() const { return CS16 ? 
CS16->Value3.35k
:
CS32->Value4
; }
318
319
32.5k
  int32_t getSectionNumber() const {
320
32.5k
    assert(isSet() && "COFFSymbolRef points to nothing!");
321
32.5k
    if (CS16) {
322
32.5k
      // Reserved sections are returned as negative numbers.
323
32.5k
      if (CS16->SectionNumber <= COFF::MaxNumberOfSections16)
324
31.8k
        return CS16->SectionNumber;
325
706
      return static_cast<int16_t>(CS16->SectionNumber);
326
706
    }
327
12
    return static_cast<int32_t>(CS32->SectionNumber);
328
12
  }
329
330
1.93k
  uint16_t getType() const {
331
1.93k
    assert(isSet() && "COFFSymbolRef points to nothing!");
332
1.93k
    return CS16 ? 
CS16->Type1.92k
:
CS32->Type8
;
333
1.93k
  }
334
335
69.0k
  uint8_t getStorageClass() const {
336
69.0k
    assert(isSet() && "COFFSymbolRef points to nothing!");
337
69.0k
    return CS16 ? 
CS16->StorageClass68.9k
:
CS32->StorageClass26
;
338
69.0k
  }
339
340
12.6k
  uint8_t getNumberOfAuxSymbols() const {
341
12.6k
    assert(isSet() && "COFFSymbolRef points to nothing!");
342
12.6k
    return CS16 ? 
CS16->NumberOfAuxSymbols12.6k
:
CS32->NumberOfAuxSymbols23
;
343
12.6k
  }
344
345
  uint8_t getBaseType() const { return getType() & 0x0F; }
346
347
846
  uint8_t getComplexType() const {
348
846
    return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT;
349
846
  }
350
351
  template <typename T> const T *getAux() const {
352
    return CS16 ? reinterpret_cast<const T *>(CS16 + 1)
353
                : reinterpret_cast<const T *>(CS32 + 1);
354
  }
355
356
  const coff_aux_section_definition *getSectionDefinition() const {
357
    if (!getNumberOfAuxSymbols() ||
358
        getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC)
359
      return nullptr;
360
    return getAux<coff_aux_section_definition>();
361
  }
362
363
  bool isAbsolute() const {
364
    return getSectionNumber() == -1;
365
  }
366
367
29.5k
  bool isExternal() const {
368
29.5k
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL;
369
29.5k
  }
370
371
9.75k
  bool isCommon() const {
372
9.75k
    return isExternal() && 
getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED4.01k
&&
373
9.75k
           
getValue() != 0715
;
374
9.75k
  }
375
376
10.3k
  bool isUndefined() const {
377
10.3k
    return isExternal() && 
getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED4.28k
&&
378
10.3k
           
getValue() == 0991
;
379
10.3k
  }
380
381
18.6k
  bool isWeakExternal() const {
382
18.6k
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
383
18.6k
  }
384
385
  bool isFunctionDefinition() const {
386
    return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
387
           getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION &&
388
           !COFF::isReservedSectionNumber(getSectionNumber());
389
  }
390
391
  bool isFunctionLineInfo() const {
392
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION;
393
  }
394
395
7.05k
  bool isAnyUndefined() const {
396
7.05k
    return isUndefined() || 
isWeakExternal()6.30k
;
397
7.05k
  }
398
399
6.32k
  bool isFileRecord() const {
400
6.32k
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE;
401
6.32k
  }
402
403
0
  bool isSection() const {
404
0
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION;
405
0
  }
406
407
6.42k
  bool isSectionDefinition() const {
408
6.42k
    // C++/CLI creates external ABS symbols for non-const appdomain globals.
409
6.42k
    // These are also followed by an auxiliary section definition.
410
6.42k
    bool isAppdomainGlobal =
411
6.42k
        getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
412
6.42k
        
getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE2.82k
;
413
6.42k
    bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC;
414
6.42k
    if (!getNumberOfAuxSymbols())
415
3.99k
      return false;
416
2.43k
    return isAppdomainGlobal || 
isOrdinarySection2.43k
;
417
2.43k
  }
418
419
  bool isCLRToken() const {
420
    return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN;
421
  }
422
423
private:
424
0
  bool isSet() const { return CS16 || CS32; }
425
426
  const coff_symbol16 *CS16 = nullptr;
427
  const coff_symbol32 *CS32 = nullptr;
428
};
429
430
struct coff_section {
431
  char Name[COFF::NameSize];
432
  support::ulittle32_t VirtualSize;
433
  support::ulittle32_t VirtualAddress;
434
  support::ulittle32_t SizeOfRawData;
435
  support::ulittle32_t PointerToRawData;
436
  support::ulittle32_t PointerToRelocations;
437
  support::ulittle32_t PointerToLinenumbers;
438
  support::ulittle16_t NumberOfRelocations;
439
  support::ulittle16_t NumberOfLinenumbers;
440
  support::ulittle32_t Characteristics;
441
442
  // Returns true if the actual number of relocations is stored in
443
  // VirtualAddress field of the first relocation table entry.
444
7.85k
  bool hasExtendedRelocations() const {
445
7.85k
    return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) &&
446
7.85k
           
NumberOfRelocations == UINT16_MAX10
;
447
7.85k
  }
448
449
1.54k
  uint32_t getAlignment() const {
450
1.54k
    // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to
451
1.54k
    // IMAGE_SCN_ALIGN_1BYTES.
452
1.54k
    if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD)
453
0
      return 1;
454
1.54k
455
1.54k
    // Bit [20:24] contains section alignment. 0 means use a default alignment
456
1.54k
    // of 16.
457
1.54k
    uint32_t Shift = (Characteristics >> 20) & 0xF;
458
1.54k
    if (Shift > 0)
459
1.53k
      return 1U << (Shift - 1);
460
10
    return 16;
461
10
  }
462
};
463
464
struct coff_relocation {
465
  support::ulittle32_t VirtualAddress;
466
  support::ulittle32_t SymbolTableIndex;
467
  support::ulittle16_t Type;
468
};
469
470
struct coff_aux_function_definition {
471
  support::ulittle32_t TagIndex;
472
  support::ulittle32_t TotalSize;
473
  support::ulittle32_t PointerToLinenumber;
474
  support::ulittle32_t PointerToNextFunction;
475
  char Unused1[2];
476
};
477
478
static_assert(sizeof(coff_aux_function_definition) == 18,
479
              "auxiliary entry must be 18 bytes");
480
481
struct coff_aux_bf_and_ef_symbol {
482
  char Unused1[4];
483
  support::ulittle16_t Linenumber;
484
  char Unused2[6];
485
  support::ulittle32_t PointerToNextFunction;
486
  char Unused3[2];
487
};
488
489
static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18,
490
              "auxiliary entry must be 18 bytes");
491
492
struct coff_aux_weak_external {
493
  support::ulittle32_t TagIndex;
494
  support::ulittle32_t Characteristics;
495
  char Unused1[10];
496
};
497
498
static_assert(sizeof(coff_aux_weak_external) == 18,
499
              "auxiliary entry must be 18 bytes");
500
501
struct coff_aux_section_definition {
502
  support::ulittle32_t Length;
503
  support::ulittle16_t NumberOfRelocations;
504
  support::ulittle16_t NumberOfLinenumbers;
505
  support::ulittle32_t CheckSum;
506
  support::ulittle16_t NumberLowPart;
507
  uint8_t              Selection;
508
  uint8_t              Unused;
509
  support::ulittle16_t NumberHighPart;
510
  int32_t getNumber(bool IsBigObj) const {
511
    uint32_t Number = static_cast<uint32_t>(NumberLowPart);
512
    if (IsBigObj)
513
      Number |= static_cast<uint32_t>(NumberHighPart) << 16;
514
    return static_cast<int32_t>(Number);
515
  }
516
};
517
518
static_assert(sizeof(coff_aux_section_definition) == 18,
519
              "auxiliary entry must be 18 bytes");
520
521
struct coff_aux_clr_token {
522
  uint8_t              AuxType;
523
  uint8_t              Reserved;
524
  support::ulittle32_t SymbolTableIndex;
525
  char                 MBZ[12];
526
};
527
528
static_assert(sizeof(coff_aux_clr_token) == 18,
529
              "auxiliary entry must be 18 bytes");
530
531
struct coff_import_header {
532
  support::ulittle16_t Sig1;
533
  support::ulittle16_t Sig2;
534
  support::ulittle16_t Version;
535
  support::ulittle16_t Machine;
536
  support::ulittle32_t TimeDateStamp;
537
  support::ulittle32_t SizeOfData;
538
  support::ulittle16_t OrdinalHint;
539
  support::ulittle16_t TypeInfo;
540
541
513
  int getType() const { return TypeInfo & 0x3; }
542
  int getNameType() const { return (TypeInfo >> 2) & 0x7; }
543
};
544
545
struct coff_import_directory_table_entry {
546
  support::ulittle32_t ImportLookupTableRVA;
547
  support::ulittle32_t TimeDateStamp;
548
  support::ulittle32_t ForwarderChain;
549
  support::ulittle32_t NameRVA;
550
  support::ulittle32_t ImportAddressTableRVA;
551
552
37
  bool isNull() const {
553
37
    return ImportLookupTableRVA == 0 && 
TimeDateStamp == 014
&&
554
37
           
ForwarderChain == 014
&&
NameRVA == 014
&&
ImportAddressTableRVA == 014
;
555
37
  }
556
};
557
558
template <typename IntTy>
559
struct coff_tls_directory {
560
  IntTy StartAddressOfRawData;
561
  IntTy EndAddressOfRawData;
562
  IntTy AddressOfIndex;
563
  IntTy AddressOfCallBacks;
564
  support::ulittle32_t SizeOfZeroFill;
565
  support::ulittle32_t Characteristics;
566
567
  uint32_t getAlignment() const {
568
    // Bit [20:24] contains section alignment.
569
    uint32_t Shift = (Characteristics & 0x00F00000) >> 20;
570
    if (Shift > 0)
571
      return 1U << (Shift - 1);
572
    return 0;
573
  }
574
};
575
576
using coff_tls_directory32 = coff_tls_directory<support::little32_t>;
577
using coff_tls_directory64 = coff_tls_directory<support::little64_t>;
578
579
/// Bits in control flow guard flags as we understand them.
580
enum class coff_guard_flags : uint32_t {
581
  CFInstrumented = 0x00000100,
582
  HasFidTable = 0x00000400,
583
  ProtectDelayLoadIAT = 0x00001000,
584
  DelayLoadIATSection = 0x00002000, // Delay load in separate section
585
  HasLongJmpTable = 0x00010000,
586
  FidTableHasFlags = 0x10000000, // Indicates that fid tables are 5 bytes
587
};
588
589
struct coff_load_config_code_integrity {
590
  support::ulittle16_t Flags;
591
  support::ulittle16_t Catalog;
592
  support::ulittle32_t CatalogOffset;
593
  support::ulittle32_t Reserved;
594
};
595
596
/// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32)
597
struct coff_load_configuration32 {
598
  support::ulittle32_t Size;
599
  support::ulittle32_t TimeDateStamp;
600
  support::ulittle16_t MajorVersion;
601
  support::ulittle16_t MinorVersion;
602
  support::ulittle32_t GlobalFlagsClear;
603
  support::ulittle32_t GlobalFlagsSet;
604
  support::ulittle32_t CriticalSectionDefaultTimeout;
605
  support::ulittle32_t DeCommitFreeBlockThreshold;
606
  support::ulittle32_t DeCommitTotalFreeThreshold;
607
  support::ulittle32_t LockPrefixTable;
608
  support::ulittle32_t MaximumAllocationSize;
609
  support::ulittle32_t VirtualMemoryThreshold;
610
  support::ulittle32_t ProcessAffinityMask;
611
  support::ulittle32_t ProcessHeapFlags;
612
  support::ulittle16_t CSDVersion;
613
  support::ulittle16_t DependentLoadFlags;
614
  support::ulittle32_t EditList;
615
  support::ulittle32_t SecurityCookie;
616
  support::ulittle32_t SEHandlerTable;
617
  support::ulittle32_t SEHandlerCount;
618
619
  // Added in MSVC 2015 for /guard:cf.
620
  support::ulittle32_t GuardCFCheckFunction;
621
  support::ulittle32_t GuardCFCheckDispatch;
622
  support::ulittle32_t GuardCFFunctionTable;
623
  support::ulittle32_t GuardCFFunctionCount;
624
  support::ulittle32_t GuardFlags; // coff_guard_flags
625
626
  // Added in MSVC 2017
627
  coff_load_config_code_integrity CodeIntegrity;
628
  support::ulittle32_t GuardAddressTakenIatEntryTable;
629
  support::ulittle32_t GuardAddressTakenIatEntryCount;
630
  support::ulittle32_t GuardLongJumpTargetTable;
631
  support::ulittle32_t GuardLongJumpTargetCount;
632
  support::ulittle32_t DynamicValueRelocTable;
633
  support::ulittle32_t CHPEMetadataPointer;
634
  support::ulittle32_t GuardRFFailureRoutine;
635
  support::ulittle32_t GuardRFFailureRoutineFunctionPointer;
636
  support::ulittle32_t DynamicValueRelocTableOffset;
637
  support::ulittle16_t DynamicValueRelocTableSection;
638
  support::ulittle16_t Reserved2;
639
  support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer;
640
  support::ulittle32_t HotPatchTableOffset;
641
};
642
643
/// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64)
644
struct coff_load_configuration64 {
645
  support::ulittle32_t Size;
646
  support::ulittle32_t TimeDateStamp;
647
  support::ulittle16_t MajorVersion;
648
  support::ulittle16_t MinorVersion;
649
  support::ulittle32_t GlobalFlagsClear;
650
  support::ulittle32_t GlobalFlagsSet;
651
  support::ulittle32_t CriticalSectionDefaultTimeout;
652
  support::ulittle64_t DeCommitFreeBlockThreshold;
653
  support::ulittle64_t DeCommitTotalFreeThreshold;
654
  support::ulittle64_t LockPrefixTable;
655
  support::ulittle64_t MaximumAllocationSize;
656
  support::ulittle64_t VirtualMemoryThreshold;
657
  support::ulittle64_t ProcessAffinityMask;
658
  support::ulittle32_t ProcessHeapFlags;
659
  support::ulittle16_t CSDVersion;
660
  support::ulittle16_t DependentLoadFlags;
661
  support::ulittle64_t EditList;
662
  support::ulittle64_t SecurityCookie;
663
  support::ulittle64_t SEHandlerTable;
664
  support::ulittle64_t SEHandlerCount;
665
666
  // Added in MSVC 2015 for /guard:cf.
667
  support::ulittle64_t GuardCFCheckFunction;
668
  support::ulittle64_t GuardCFCheckDispatch;
669
  support::ulittle64_t GuardCFFunctionTable;
670
  support::ulittle64_t GuardCFFunctionCount;
671
  support::ulittle32_t GuardFlags;
672
673
  // Added in MSVC 2017
674
  coff_load_config_code_integrity CodeIntegrity;
675
  support::ulittle64_t GuardAddressTakenIatEntryTable;
676
  support::ulittle64_t GuardAddressTakenIatEntryCount;
677
  support::ulittle64_t GuardLongJumpTargetTable;
678
  support::ulittle64_t GuardLongJumpTargetCount;
679
  support::ulittle64_t DynamicValueRelocTable;
680
  support::ulittle64_t CHPEMetadataPointer;
681
  support::ulittle64_t GuardRFFailureRoutine;
682
  support::ulittle64_t GuardRFFailureRoutineFunctionPointer;
683
  support::ulittle32_t DynamicValueRelocTableOffset;
684
  support::ulittle16_t DynamicValueRelocTableSection;
685
  support::ulittle16_t Reserved2;
686
  support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer;
687
  support::ulittle32_t HotPatchTableOffset;
688
};
689
690
struct coff_runtime_function_x64 {
691
  support::ulittle32_t BeginAddress;
692
  support::ulittle32_t EndAddress;
693
  support::ulittle32_t UnwindInformation;
694
};
695
696
struct coff_base_reloc_block_header {
697
  support::ulittle32_t PageRVA;
698
  support::ulittle32_t BlockSize;
699
};
700
701
struct coff_base_reloc_block_entry {
702
  support::ulittle16_t Data;
703
704
100
  int getType() const { return Data >> 12; }
705
100
  int getOffset() const { return Data & ((1 << 12) - 1); }
706
};
707
708
struct coff_resource_dir_entry {
709
  union {
710
    support::ulittle32_t NameOffset;
711
    support::ulittle32_t ID;
712
28
    uint32_t getNameOffset() const {
713
28
      return maskTrailingOnes<uint32_t>(31) & NameOffset;
714
28
    }
715
    // Even though the PE/COFF spec doesn't mention this, the high bit of a name
716
    // offset is set.
717
72
    void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); }
718
  } Identifier;
719
  union {
720
    support::ulittle32_t DataEntryOffset;
721
    support::ulittle32_t SubdirOffset;
722
723
    bool isSubDir() const { return SubdirOffset >> 31; }
724
229
    uint32_t value() const {
725
229
      return maskTrailingOnes<uint32_t>(31) & SubdirOffset;
726
229
    }
727
728
  } Offset;
729
};
730
731
struct coff_resource_data_entry {
732
  support::ulittle32_t DataRVA;
733
  support::ulittle32_t DataSize;
734
  support::ulittle32_t Codepage;
735
  support::ulittle32_t Reserved;
736
};
737
738
struct coff_resource_dir_table {
739
  support::ulittle32_t Characteristics;
740
  support::ulittle32_t TimeDateStamp;
741
  support::ulittle16_t MajorVersion;
742
  support::ulittle16_t MinorVersion;
743
  support::ulittle16_t NumberOfNameEntries;
744
  support::ulittle16_t NumberOfIDEntries;
745
};
746
747
struct debug_h_header {
748
  support::ulittle32_t Magic;
749
  support::ulittle16_t Version;
750
  support::ulittle16_t HashAlgorithm;
751
};
752
753
class COFFObjectFile : public ObjectFile {
754
private:
755
  friend class ImportDirectoryEntryRef;
756
  friend class ExportDirectoryEntryRef;
757
  const coff_file_header *COFFHeader;
758
  const coff_bigobj_file_header *COFFBigObjHeader;
759
  const pe32_header *PE32Header;
760
  const pe32plus_header *PE32PlusHeader;
761
  const data_directory *DataDirectory;
762
  const coff_section *SectionTable;
763
  const coff_symbol16 *SymbolTable16;
764
  const coff_symbol32 *SymbolTable32;
765
  const char *StringTable;
766
  uint32_t StringTableSize;
767
  const coff_import_directory_table_entry *ImportDirectory;
768
  const delay_import_directory_table_entry *DelayImportDirectory;
769
  uint32_t NumberOfDelayImportDirectory;
770
  const export_directory_table_entry *ExportDirectory;
771
  const coff_base_reloc_block_header *BaseRelocHeader;
772
  const coff_base_reloc_block_header *BaseRelocEnd;
773
  const debug_directory *DebugDirectoryBegin;
774
  const debug_directory *DebugDirectoryEnd;
775
  // Either coff_load_configuration32 or coff_load_configuration64.
776
  const void *LoadConfig = nullptr;
777
778
  std::error_code getString(uint32_t offset, StringRef &Res) const;
779
780
  template <typename coff_symbol_type>
781
  const coff_symbol_type *toSymb(DataRefImpl Symb) const;
782
  const coff_section *toSec(DataRefImpl Sec) const;
783
  const coff_relocation *toRel(DataRefImpl Rel) const;
784
785
  std::error_code initSymbolTablePtr();
786
  std::error_code initImportTablePtr();
787
  std::error_code initDelayImportTablePtr();
788
  std::error_code initExportTablePtr();
789
  std::error_code initBaseRelocPtr();
790
  std::error_code initDebugDirectoryPtr();
791
  std::error_code initLoadConfigPtr();
792
793
public:
794
4.41k
  uintptr_t getSymbolTable() const {
795
4.41k
    if (SymbolTable16)
796
4.37k
      return reinterpret_cast<uintptr_t>(SymbolTable16);
797
34
    if (SymbolTable32)
798
1
      return reinterpret_cast<uintptr_t>(SymbolTable32);
799
33
    return uintptr_t(0);
800
33
  }
801
802
154k
  uint16_t getMachine() const {
803
154k
    if (COFFHeader)
804
154k
      return COFFHeader->Machine;
805
4
    if (COFFBigObjHeader)
806
4
      return COFFBigObjHeader->Machine;
807
0
    llvm_unreachable("no COFF header!");
808
0
  }
809
810
  uint16_t getSizeOfOptionalHeader() const {
811
    if (COFFHeader)
812
      return COFFHeader->isImportLibrary() ? 0
813
                                           : COFFHeader->SizeOfOptionalHeader;
814
    // bigobj doesn't have this field.
815
    if (COFFBigObjHeader)
816
      return 0;
817
    llvm_unreachable("no COFF header!");
818
  }
819
820
  uint16_t getCharacteristics() const {
821
    if (COFFHeader)
822
      return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics;
823
    // bigobj doesn't have characteristics to speak of,
824
    // editbin will silently lie to you if you attempt to set any.
825
    if (COFFBigObjHeader)
826
      return 0;
827
    llvm_unreachable("no COFF header!");
828
  }
829
830
  uint32_t getTimeDateStamp() const {
831
    if (COFFHeader)
832
      return COFFHeader->TimeDateStamp;
833
    if (COFFBigObjHeader)
834
      return COFFBigObjHeader->TimeDateStamp;
835
    llvm_unreachable("no COFF header!");
836
  }
837
838
14.9k
  uint32_t getNumberOfSections() const {
839
14.9k
    if (COFFHeader)
840
14.9k
      return COFFHeader->isImportLibrary() ? 
00
: COFFHeader->NumberOfSections;
841
7
    if (COFFBigObjHeader)
842
7
      return COFFBigObjHeader->NumberOfSections;
843
0
    llvm_unreachable("no COFF header!");
844
0
  }
845
846
4.57k
  uint32_t getPointerToSymbolTable() const {
847
4.57k
    if (COFFHeader)
848
4.56k
      return COFFHeader->isImportLibrary() ? 
00
849
4.56k
                                           : COFFHeader->PointerToSymbolTable;
850
4
    if (COFFBigObjHeader)
851
4
      return COFFBigObjHeader->PointerToSymbolTable;
852
0
    llvm_unreachable("no COFF header!");
853
0
  }
854
855
6.99k
  uint32_t getRawNumberOfSymbols() const {
856
6.99k
    if (COFFHeader)
857
6.99k
      return COFFHeader->isImportLibrary() ? 
00
: COFFHeader->NumberOfSymbols;
858
2
    if (COFFBigObjHeader)
859
2
      return COFFBigObjHeader->NumberOfSymbols;
860
0
    llvm_unreachable("no COFF header!");
861
0
  }
862
863
8.79k
  uint32_t getNumberOfSymbols() const {
864
8.79k
    if (!SymbolTable16 && 
!SymbolTable321.80k
)
865
1.79k
      return 0;
866
6.99k
    return getRawNumberOfSymbols();
867
6.99k
  }
868
869
  const coff_load_configuration32 *getLoadConfig32() const {
870
    assert(!is64());
871
    return reinterpret_cast<const coff_load_configuration32 *>(LoadConfig);
872
  }
873
874
  const coff_load_configuration64 *getLoadConfig64() const {
875
    assert(is64());
876
    return reinterpret_cast<const coff_load_configuration64 *>(LoadConfig);
877
  }
878
879
protected:
880
  void moveSymbolNext(DataRefImpl &Symb) const override;
881
  Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
882
  Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
883
  uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
884
  uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
885
  uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
886
  uint32_t getSymbolFlags(DataRefImpl Symb) const override;
887
  Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
888
  Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
889
  void moveSectionNext(DataRefImpl &Sec) const override;
890
  std::error_code getSectionName(DataRefImpl Sec,
891
                                 StringRef &Res) const override;
892
  uint64_t getSectionAddress(DataRefImpl Sec) const override;
893
  uint64_t getSectionIndex(DataRefImpl Sec) const override;
894
  uint64_t getSectionSize(DataRefImpl Sec) const override;
895
  std::error_code getSectionContents(DataRefImpl Sec,
896
                                     StringRef &Res) const override;
897
  uint64_t getSectionAlignment(DataRefImpl Sec) const override;
898
  bool isSectionCompressed(DataRefImpl Sec) const override;
899
  bool isSectionText(DataRefImpl Sec) const override;
900
  bool isSectionData(DataRefImpl Sec) const override;
901
  bool isSectionBSS(DataRefImpl Sec) const override;
902
  bool isSectionVirtual(DataRefImpl Sec) const override;
903
  relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
904
  relocation_iterator section_rel_end(DataRefImpl Sec) const override;
905
906
  void moveRelocationNext(DataRefImpl &Rel) const override;
907
  uint64_t getRelocationOffset(DataRefImpl Rel) const override;
908
  symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
909
  uint64_t getRelocationType(DataRefImpl Rel) const override;
910
  void getRelocationTypeName(DataRefImpl Rel,
911
                             SmallVectorImpl<char> &Result) const override;
912
913
public:
914
  COFFObjectFile(MemoryBufferRef Object, std::error_code &EC);
915
916
  basic_symbol_iterator symbol_begin() const override;
917
  basic_symbol_iterator symbol_end() const override;
918
  section_iterator section_begin() const override;
919
  section_iterator section_end() const override;
920
921
  const coff_section *getCOFFSection(const SectionRef &Section) const;
922
  COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const;
923
  COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const;
924
  const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const;
925
  unsigned getSectionID(SectionRef Sec) const;
926
  unsigned getSymbolSectionID(SymbolRef Sym) const;
927
928
  uint8_t getBytesInAddress() const override;
929
  StringRef getFileFormatName() const override;
930
  Triple::ArchType getArch() const override;
931
  Expected<uint64_t> getStartAddress() const override;
932
52
  SubtargetFeatures getFeatures() const override { return SubtargetFeatures(); }
933
934
  import_directory_iterator import_directory_begin() const;
935
  import_directory_iterator import_directory_end() const;
936
  delay_import_directory_iterator delay_import_directory_begin() const;
937
  delay_import_directory_iterator delay_import_directory_end() const;
938
  export_directory_iterator export_directory_begin() const;
939
  export_directory_iterator export_directory_end() const;
940
  base_reloc_iterator base_reloc_begin() const;
941
  base_reloc_iterator base_reloc_end() const;
942
61
  const debug_directory *debug_directory_begin() const {
943
61
    return DebugDirectoryBegin;
944
61
  }
945
61
  const debug_directory *debug_directory_end() const {
946
61
    return DebugDirectoryEnd;
947
61
  }
948
949
  iterator_range<import_directory_iterator> import_directories() const;
950
  iterator_range<delay_import_directory_iterator>
951
      delay_import_directories() const;
952
  iterator_range<export_directory_iterator> export_directories() const;
953
  iterator_range<base_reloc_iterator> base_relocs() const;
954
61
  iterator_range<const debug_directory *> debug_directories() const {
955
61
    return make_range(debug_directory_begin(), debug_directory_end());
956
61
  }
957
958
153k
  const dos_header *getDOSHeader() const {
959
153k
    if (!PE32Header && 
!PE32PlusHeader153k
)
960
2.78k
      return nullptr;
961
150k
    return reinterpret_cast<const dos_header *>(base());
962
150k
  }
963
  std::error_code getPE32Header(const pe32_header *&Res) const;
964
  std::error_code getPE32PlusHeader(const pe32plus_header *&Res) const;
965
  std::error_code getDataDirectory(uint32_t index,
966
                                   const data_directory *&Res) const;
967
  std::error_code getSection(int32_t index, const coff_section *&Res) const;
968
  std::error_code getSection(StringRef SectionName,
969
                             const coff_section *&Res) const;
970
971
  template <typename coff_symbol_type>
972
  std::error_code getSymbol(uint32_t Index,
973
                            const coff_symbol_type *&Res) const {
974
    if (Index >= getNumberOfSymbols())
975
      return object_error::parse_failed;
976
977
    Res = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
978
    return std::error_code();
979
  }
980
  Expected<COFFSymbolRef> getSymbol(uint32_t index) const {
981
    if (SymbolTable16) {
982
      const coff_symbol16 *Symb = nullptr;
983
      if (std::error_code EC = getSymbol(index, Symb))
984
        return errorCodeToError(EC);
985
      return COFFSymbolRef(Symb);
986
    }
987
    if (SymbolTable32) {
988
      const coff_symbol32 *Symb = nullptr;
989
      if (std::error_code EC = getSymbol(index, Symb))
990
        return errorCodeToError(EC);
991
      return COFFSymbolRef(Symb);
992
    }
993
    return errorCodeToError(object_error::parse_failed);
994
  }
995
996
  template <typename T>
997
  std::error_code getAuxSymbol(uint32_t index, const T *&Res) const {
998
    Expected<COFFSymbolRef> S = getSymbol(index);
999
    if (Error E = S.takeError())
1000
      return errorToErrorCode(std::move(E));
1001
    Res = reinterpret_cast<const T *>(S->getRawPtr());
1002
    return std::error_code();
1003
  }
1004
1005
  std::error_code getSymbolName(COFFSymbolRef Symbol, StringRef &Res) const;
1006
  std::error_code getSymbolName(const coff_symbol_generic *Symbol,
1007
                                StringRef &Res) const;
1008
1009
  ArrayRef<uint8_t> getSymbolAuxData(COFFSymbolRef Symbol) const;
1010
1011
3.95k
  size_t getSymbolTableEntrySize() const {
1012
3.95k
    if (COFFHeader)
1013
3.94k
      return sizeof(coff_symbol16);
1014
11
    if (COFFBigObjHeader)
1015
11
      return sizeof(coff_symbol32);
1016
0
    llvm_unreachable("null symbol table pointer!");
1017
0
  }
1018
1019
  ArrayRef<coff_relocation> getRelocations(const coff_section *Sec) const;
1020
1021
  std::error_code getSectionName(const coff_section *Sec, StringRef &Res) const;
1022
  uint64_t getSectionSize(const coff_section *Sec) const;
1023
  std::error_code getSectionContents(const coff_section *Sec,
1024
                                     ArrayRef<uint8_t> &Res) const;
1025
1026
  uint64_t getImageBase() const;
1027
  std::error_code getVaPtr(uint64_t VA, uintptr_t &Res) const;
1028
  std::error_code getRvaPtr(uint32_t Rva, uintptr_t &Res) const;
1029
1030
  /// Given an RVA base and size, returns a valid array of bytes or an error
1031
  /// code if the RVA and size is not contained completely within a valid
1032
  /// section.
1033
  std::error_code getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
1034
                                       ArrayRef<uint8_t> &Contents) const;
1035
1036
  std::error_code getHintName(uint32_t Rva, uint16_t &Hint,
1037
                              StringRef &Name) const;
1038
1039
  /// Get PDB information out of a codeview debug directory entry.
1040
  std::error_code getDebugPDBInfo(const debug_directory *DebugDir,
1041
                                  const codeview::DebugInfo *&Info,
1042
                                  StringRef &PDBFileName) const;
1043
1044
  /// Get PDB information from an executable. If the information is not present,
1045
  /// Info will be set to nullptr and PDBFileName will be empty. An error is
1046
  /// returned only on corrupt object files. Convenience accessor that can be
1047
  /// used if the debug directory is not already handy.
1048
  std::error_code getDebugPDBInfo(const codeview::DebugInfo *&Info,
1049
                                  StringRef &PDBFileName) const;
1050
1051
  bool isRelocatableObject() const override;
1052
68
  bool is64() const { return PE32PlusHeader; }
1053
1054
6.78k
  static bool classof(const Binary *v) { return v->isCOFF(); }
1055
};
1056
1057
// The iterator for the import directory table.
1058
class ImportDirectoryEntryRef {
1059
public:
1060
  ImportDirectoryEntryRef() = default;
1061
  ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table,
1062
                          uint32_t I, const COFFObjectFile *Owner)
1063
88
      : ImportTable(Table), Index(I), OwningObject(Owner) {}
1064
1065
  bool operator==(const ImportDirectoryEntryRef &Other) const;
1066
  void moveNext();
1067
1068
  imported_symbol_iterator imported_symbol_begin() const;
1069
  imported_symbol_iterator imported_symbol_end() const;
1070
  iterator_range<imported_symbol_iterator> imported_symbols() const;
1071
1072
  imported_symbol_iterator lookup_table_begin() const;
1073
  imported_symbol_iterator lookup_table_end() const;
1074
  iterator_range<imported_symbol_iterator> lookup_table_symbols() const;
1075
1076
  std::error_code getName(StringRef &Result) const;
1077
  std::error_code getImportLookupTableRVA(uint32_t &Result) const;
1078
  std::error_code getImportAddressTableRVA(uint32_t &Result) const;
1079
1080
  std::error_code
1081
  getImportTableEntry(const coff_import_directory_table_entry *&Result) const;
1082
1083
private:
1084
  const coff_import_directory_table_entry *ImportTable;
1085
  uint32_t Index;
1086
  const COFFObjectFile *OwningObject = nullptr;
1087
};
1088
1089
class DelayImportDirectoryEntryRef {
1090
public:
1091
  DelayImportDirectoryEntryRef() = default;
1092
  DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T,
1093
                               uint32_t I, const COFFObjectFile *Owner)
1094
32
      : Table(T), Index(I), OwningObject(Owner) {}
1095
1096
  bool operator==(const DelayImportDirectoryEntryRef &Other) const;
1097
  void moveNext();
1098
1099
  imported_symbol_iterator imported_symbol_begin() const;
1100
  imported_symbol_iterator imported_symbol_end() const;
1101
  iterator_range<imported_symbol_iterator> imported_symbols() const;
1102
1103
  std::error_code getName(StringRef &Result) const;
1104
  std::error_code getDelayImportTable(
1105
      const delay_import_directory_table_entry *&Result) const;
1106
  std::error_code getImportAddress(int AddrIndex, uint64_t &Result) const;
1107
1108
private:
1109
  const delay_import_directory_table_entry *Table;
1110
  uint32_t Index;
1111
  const COFFObjectFile *OwningObject = nullptr;
1112
};
1113
1114
// The iterator for the export directory table entry.
1115
class ExportDirectoryEntryRef {
1116
public:
1117
  ExportDirectoryEntryRef() = default;
1118
  ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I,
1119
                          const COFFObjectFile *Owner)
1120
212
      : ExportTable(Table), Index(I), OwningObject(Owner) {}
1121
1122
  bool operator==(const ExportDirectoryEntryRef &Other) const;
1123
  void moveNext();
1124
1125
  std::error_code getDllName(StringRef &Result) const;
1126
  std::error_code getOrdinalBase(uint32_t &Result) const;
1127
  std::error_code getOrdinal(uint32_t &Result) const;
1128
  std::error_code getExportRVA(uint32_t &Result) const;
1129
  std::error_code getSymbolName(StringRef &Result) const;
1130
1131
  std::error_code isForwarder(bool &Result) const;
1132
  std::error_code getForwardTo(StringRef &Result) const;
1133
1134
private:
1135
  const export_directory_table_entry *ExportTable;
1136
  uint32_t Index;
1137
  const COFFObjectFile *OwningObject = nullptr;
1138
};
1139
1140
class ImportedSymbolRef {
1141
public:
1142
  ImportedSymbolRef() = default;
1143
  ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I,
1144
                    const COFFObjectFile *Owner)
1145
24
      : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {}
1146
  ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I,
1147
                    const COFFObjectFile *Owner)
1148
26
      : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {}
1149
1150
  bool operator==(const ImportedSymbolRef &Other) const;
1151
  void moveNext();
1152
1153
  std::error_code getSymbolName(StringRef &Result) const;
1154
  std::error_code isOrdinal(bool &Result) const;
1155
  std::error_code getOrdinal(uint16_t &Result) const;
1156
  std::error_code getHintNameRVA(uint32_t &Result) const;
1157
1158
private:
1159
  const import_lookup_table_entry32 *Entry32;
1160
  const import_lookup_table_entry64 *Entry64;
1161
  uint32_t Index;
1162
  const COFFObjectFile *OwningObject = nullptr;
1163
};
1164
1165
class BaseRelocRef {
1166
public:
1167
  BaseRelocRef() = default;
1168
  BaseRelocRef(const coff_base_reloc_block_header *Header,
1169
               const COFFObjectFile *Owner)
1170
26
      : Header(Header), Index(0) {}
1171
1172
  bool operator==(const BaseRelocRef &Other) const;
1173
  void moveNext();
1174
1175
  std::error_code getType(uint8_t &Type) const;
1176
  std::error_code getRVA(uint32_t &Result) const;
1177
1178
private:
1179
  const coff_base_reloc_block_header *Header;
1180
  uint32_t Index;
1181
};
1182
1183
class ResourceSectionRef {
1184
public:
1185
  ResourceSectionRef() = default;
1186
  explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {}
1187
1188
  Expected<ArrayRef<UTF16>>
1189
  getEntryNameString(const coff_resource_dir_entry &Entry);
1190
  Expected<const coff_resource_dir_table &>
1191
  getEntrySubDir(const coff_resource_dir_entry &Entry);
1192
  Expected<const coff_resource_dir_table &> getBaseTable();
1193
1194
private:
1195
  BinaryByteStream BBS;
1196
1197
  Expected<const coff_resource_dir_table &> getTableAtOffset(uint32_t Offset);
1198
  Expected<ArrayRef<UTF16>> getDirStringAtOffset(uint32_t Offset);
1199
};
1200
1201
// Corresponds to `_FPO_DATA` structure in the PE/COFF spec.
1202
struct FpoData {
1203
  support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code
1204
  support::ulittle32_t Size;   // cbProcSize: # bytes in function
1205
  support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4
1206
  support::ulittle16_t NumParams; // cdwParams: # bytes in params/4
1207
  support::ulittle16_t Attributes;
1208
1209
  // cbProlog: # bytes in prolog
1210
  int getPrologSize() const { return Attributes & 0xF; }
1211
1212
  // cbRegs: # regs saved
1213
  int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; }
1214
1215
  // fHasSEH: true if seh is func
1216
  bool hasSEH() const { return (Attributes >> 9) & 1; }
1217
1218
  // fUseBP: true if EBP has been allocated
1219
  bool useBP() const { return (Attributes >> 10) & 1; }
1220
1221
  // cbFrame: frame pointer
1222
  int getFP() const { return Attributes >> 14; }
1223
};
1224
1225
} // end namespace object
1226
1227
} // end namespace llvm
1228
1229
#endif // LLVM_OBJECT_COFF_H