-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathcoffview.cpp
More file actions
1713 lines (1540 loc) · 71.2 KB
/
coffview.cpp
File metadata and controls
1713 lines (1540 loc) · 71.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <algorithm>
#include <cstring>
#include <cctype>
#include <string.h>
#include <inttypes.h>
#include <iomanip>
#include <mutex>
#include <sstream>
#include <type_traits>
#include <utility>
#include "coffview.h"
#define STRING_READ_CHUNK_SIZE 32
#define DEBUG_COFF_VERBOSELY 0
#if DEBUG_COFF_VERBOSELY
#define DEBUG_COFF(s) s
#else
#define DEBUG_COFF(s)
#endif
// Define an Enumeration from an EnumerationBuilder:
// Ref<Enumeration> prefixEnum
// Ref<Type> prefixEnumType
// string prefixEnumName
// string prefixEnumId
// QualifiedName prefixEnumTypeName
#define BUILD_ENUM_TYPE(prefix, name, width) \
Ref<Enumeration> prefix ## Enum = prefix ## Builder.Finalize(); \
Ref<Type> prefix ## EnumType = Type::EnumerationType(GetParentView()->GetDefaultArchitecture(), prefix ## Enum, width, false); \
string prefix ## EnumName = name; \
string prefix ## EnumId = Type::GenerateAutoTypeId("coff", prefix ## EnumName); \
QualifiedName prefix ## EnumTypeName = DefineType(prefix ## EnumId, prefix ## EnumName, prefix ## EnumType)
// Add member to an EnumerationBuilder:
#define ADD_ENUM_MEMBER(type, name) type ## Builder.AddMemberWithValue(#name, name)
using namespace BinaryNinja;
using namespace std;
// From LLVM COFF.h:
// https://github.com/llvm/llvm-project/blob/main/llvm/include/llvm/BinaryFormat/COFF.h#L37-L45
static const char BigObjMagic[] = {
'\xc7', '\xa1', '\xba', '\xd1', '\xee', '\xba', '\xa9', '\x4b',
'\xaf', '\x20', '\xfa', '\xf6', '\x6a', '\xa4', '\xdc', '\xb8',
};
static const char ClGlObjMagic[] = {
'\x38', '\xfe', '\xb3', '\x0c', '\xa5', '\xd9', '\xab', '\x4d',
'\xac', '\x9b', '\xd6', '\xb6', '\x22', '\x26', '\x53', '\xc2',
};
static COFFViewType* g_coffViewType = nullptr;
void BinaryNinja::InitCOFFViewType()
{
static COFFViewType type;
BinaryViewType::Register(&type);
g_coffViewType = &type;
}
COFFView::COFFView(BinaryView* data, bool parseOnly): BinaryView("COFF", data->GetFile(), data), m_parseOnly(parseOnly)
{
CreateLogger("BinaryView");
m_logger = CreateLogger("BinaryView.COFFView");
}
bool COFFView::Init()
{
std::chrono::steady_clock::time_point startTime = std::chrono::steady_clock::now();
map<string, size_t> usedSectionNames;
BinaryReader reader(GetParentView(), LittleEndian);
uint64_t entryPointAddress;
Ref<Platform> platform;
Ref<Settings> settings;
COFFHeader header;
BigObj_COFFHeader header2;
memset(&header, 0, sizeof(header));
memset(&header2, 0, sizeof(header2));
size_t sectionIndexSize = sizeof(header.sectionCount);
size_t sizeofCOFFSymbol = sizeof(COFFSymbol16);
size_t sectionHeadersOffset = sizeof(COFFHeader);
uint32_t sectionCount = 0;
bool isCLRBinary = false;
bool isBigCOFF = false;
m_is64 = false;
try
{
// Read COFF header
reader.Seek(0);
header.machine = reader.Read16();
if (header.machine == IMAGE_FILE_MACHINE_UNKNOWN)
{
uint16_t sig2 = reader.Read16();
if (sig2 == 0xFFFF)
{
header2.sig1 = header.machine;
header2.sig2 = sig2;
sectionIndexSize = sizeof(header2.sectionCount);
sizeofCOFFSymbol = sizeof(COFFSymbol32);
sectionHeadersOffset = sizeof(BigObj_COFFHeader);
header2.version = reader.Read16();
header.machine = header2.machine = reader.Read16();
header.timestamp = header2.timestamp = reader.Read32();
reader.Read(&header2.UUID, sizeof(header2.UUID));
if (memcmp(&header2.UUID, BigObjMagic, sizeof(BigObjMagic)) == 0)
{
m_logger->LogDebug("COFF Header UUID is big object");
}
else if (memcmp(&header2.UUID, ClGlObjMagic, sizeof(ClGlObjMagic)) == 0)
{
m_logger->LogError("COFF: header UUID is CL.exe LTO object, no native code to disassemble.");
return false;
}
else
{
m_logger->LogError("COFF: header UUID unknown, probably COFF import library (unsupported).");
return false;
}
header2.unused1 = reader.Read32();
header2.unused2 = reader.Read32();
header2.unused3 = reader.Read32();
header2.unused4 = reader.Read32();
sectionCount = header2.sectionCount = reader.Read32();
header.coffSymbolTable = header2.coffSymbolTable = reader.Read32();
header.coffSymbolCount = header2.coffSymbolCount = reader.Read32();
m_logger->LogDebug("COFFHeader (big):\n"
"\tsig1: 0x%04x\n"
"\tsig2: 0x%04x\n"
"\tmachine: 0x%04x\n"
"\tsectionCount: 0x%08x\n"
"\ttimestamp: 0x%08x\n"
"\tcoffSymbolTable: 0x%08x\n"
"\tcoffSymbolCount: 0x%08x\n",
header2.sig1,
header2.sig2,
header2.machine,
header2.sectionCount,
header2.timestamp,
header2.coffSymbolTable,
header2.coffSymbolCount);
}
else
{
sectionCount = header.sectionCount = sig2;
}
}
else
{
sectionCount = header.sectionCount = reader.Read16();
}
if (header2.sig2 != 0xFFFF)
{
header.timestamp = reader.Read32();
header.coffSymbolTable = reader.Read32();
header.coffSymbolCount = reader.Read32();
header.optionalHeaderSize = reader.Read16();
header.characteristics = reader.Read16();
m_logger->LogDebug("COFFHeader:\n"
"\tmachine: 0x%04x\n"
"\tsectionCount: 0x%04x\n"
"\ttimestamp: 0x%08x\n"
"\tcoffSymbolTable: 0x%08x\n"
"\tcoffSymbolCount: 0x%08x\n"
"\toptionalHeaderSize: 0x%04x\n"
"\tcharacteristics: 0x%04x %s, %s, %s\n",
header.machine,
header.sectionCount,
header.timestamp,
header.coffSymbolTable,
header.coffSymbolCount,
header.optionalHeaderSize,
header.characteristics,
header.characteristics & 1 ? "No Relocations" : "",
header.characteristics & 2 ? "Executable" : "",
header.characteristics & 0x2000 ? "Dll" : "Unknown");
}
isBigCOFF = sectionIndexSize != sizeof(header.sectionCount);
// TODO: Optional Header for executable COFF files: https://wiki.osdev.org/COFF#Optional_Header
// Add the entry point as a function if the architecture is supported
// set m_arch early so the to make it available for the demangler
m_arch = g_coffViewType->GetArchitecture(header.machine, LittleEndian);
if (!m_arch)
{
m_logger->LogError("COFF: Invalid or unknown machine type %#" PRIx16, header.machine);
return false;
}
m_logger->LogDebug("COFF: Architecture(%#x): %s", header.machine, m_arch->GetName().c_str());
m_is64 = m_arch->GetAddressSize() == 8;
m_imageBase = 0; // 0 for COFF? opt.imageBase;
bool platformSetByUser = false;
settings = GetLoadSettings(GetTypeName());
if (settings)
{
if (settings->Contains("loader.imageBase"))
m_imageBase = settings->Get<uint64_t>("loader.imageBase", this);
if (settings->Contains("loader.platform"))
{
BNSettingsScope scope = SettingsAutoScope;
Ref<Platform> platform = Platform::GetByName(settings->Get<string>("loader.platform", this, &scope));
if (platform)
{
m_arch = platform->GetArchitecture();
platformSetByUser = (scope == SettingsResourceScope);
}
}
}
Ref<Settings> viewSettings = Settings::Instance();
m_extractMangledTypes = viewSettings->Get<bool>("analysis.extractTypesFromMangledNames", this);
m_simplifyTemplates = viewSettings->Get<bool>("analysis.types.templateSimplifier", this);
// Add extra segment to hold header so that it can be viewed. This must be first so
// that real sections take priority.
if (sectionCount)
{
m_sizeOfHeaders = sectionHeadersOffset + sectionCount * sizeof(COFFSectionHeader);
AddAutoSegment(m_imageBase, m_sizeOfHeaders, 0, m_sizeOfHeaders, SegmentReadable);
}
else
{
m_logger->LogWarn("COFF header sectionCount is 0, no sections added");
return false;
}
// Since COFF files are not image files, they don't have an entry point. So set the entry point
// to the beginning of the first executable section.
m_entryPoint = 0;
// COFF files are object files, to be relocated by the linker, so are always relocatable.
m_relocatable = true;
// Read sections
reader.Seek(sectionHeadersOffset);
BinaryReader sectionNameReader(GetParentView(), LittleEndian);
BeginBulkAddSegments();
for (uint32_t i = 0; i < sectionCount; i++)
{
COFFSection section;
char name[9];
memset(name, 0, sizeof(name));
reader.Read(name, 8);
string resolvedName = name;
if (name[0] == '/' && header.coffSymbolTable)
{
errno = 0;
uint32_t offset = strtoul(name+1, nullptr, 10);
if (errno == 0 && offset > 0)
{
BinaryReader stringReader(GetParentView(), LittleEndian);
uint64_t stringTableBase = header.coffSymbolTable + (header.coffSymbolCount * 18);
stringReader.Seek(stringTableBase);
uint32_t stringTableLen = stringReader.Read32();
if ((stringTableBase + stringTableLen) > GetParentView()->GetEnd())
{
m_logger->LogError("Cannot resolve section name \"%s\": String table is invalid length", name);
}
else if (stringTableBase + offset < GetParentView()->GetEnd())
{
sectionNameReader.Seek(stringTableBase + offset);
resolvedName = sectionNameReader.ReadCString();
}
else
{
m_logger->LogError("Cannot resolve section name \"%s\": Offset is past end of string table", name);
}
}
}
section.name = resolvedName;
section.virtualSize = reader.Read32();
section.virtualAddress = reader.Read32();
section.sizeOfRawData = reader.Read32();
section.pointerToRawData = reader.Read32();
section.pointerToRelocs = reader.Read32();
section.pointerToLineNumbers = reader.Read32();
section.relocCount = reader.Read16();
section.lineNumberCount = reader.Read16();
section.characteristics = reader.Read32();
if (section.virtualSize == 0)
{
section.virtualSize = section.sizeOfRawData;
}
if (section.virtualAddress == 0)
{
section.virtualAddress = section.pointerToRawData;
}
if (i > 0)
{
auto previous = m_sections[i-1];
DEBUG_COFF(m_logger->LogDebug("COFF: previous section (%#" PRIx32 ", %#" PRIx32 ", %#" PRIx32 ") new section: %#" PRIx32 ", %#" PRIx32 ")",
previous.virtualAddress,
previous.virtualSize,
previous.virtualAddress + previous.virtualSize + previous.relocCount * sizeof(COFFRelocation),
section.virtualAddress,
section.virtualSize));
if (section.virtualAddress < previous.virtualAddress + previous.virtualSize + previous.relocCount * sizeof(COFFRelocation))
{
section.virtualAddress = previous.virtualAddress + previous.virtualSize + previous.relocCount * sizeof(COFFRelocation);
}
}
uint32_t flags = 0;
if (section.characteristics & 0x80000000)
flags |= SegmentWritable;
if (section.characteristics & 0x40000000)
flags |= SegmentReadable;
if (section.characteristics & 0x20000000)
flags |= SegmentExecutable;
if (section.characteristics & 0x80)
flags |= SegmentContainsData;
if (section.characteristics & 0x40)
flags |= SegmentContainsData;
if (section.characteristics & 0x20)
flags |= SegmentContainsCode;
uint32_t align_characteristic = (section.characteristics & (0x00F00000));
DEBUG_COFF(m_logger->LogDebug("COFF: align_characteristic: %#" PRIx32 ", %#" PRIx32 "\n", align_characteristic, align_characteristic >> 20));
if (align_characteristic != 0)
{
uint32_t alignment = 1 << ((align_characteristic >> 20) - 1);
uint32_t mask = alignment - 1;
DEBUG_COFF(m_logger->LogDebug("COFF: section alignment: %#" PRIx32 ", mask: %#" PRIx32 "\n", alignment, mask));
section.virtualAddress += (-section.virtualAddress & mask);
}
m_logger->LogDebug("COFF: Section [%d]\n"
"\tsection.name %s\n"\
"\tsection.virtualSize: %#" PRIx32 "\n"\
/* "\tsection.physicalAddress: %#" PRIx32 "\n" */\
"\tsection.sizeOfRawData: %#" PRIx32 "\n"\
"\tsection.pointerToRawData: %#" PRIx32 "\n"\
"\tsection.pointerToRelocs: %#" PRIx32 "\n"\
"\tsection.pointerToLineNumbers: %#" PRIx32 "\n"\
"\tsection.relocCount: %#" PRIx16 "\n"\
"\tsection.lineNumberCount: %#" PRIx16 "\n"\
"\tsection.characteristics: %#" PRIx32 "\n"\
"\tsection.virtualAddress: %#" PRIx32 "\n",\
i, section.name.c_str(),
section.virtualSize,
// section.physicalAddress,
section.sizeOfRawData,
section.pointerToRawData,
section.pointerToRelocs,
section.pointerToLineNumbers,
section.relocCount,
section.lineNumberCount,
section.characteristics,
section.virtualAddress
);
m_logger->LogDebug("COFF: Segment: Vaddr: %08" PRIx64 " Vsize: %08" PRIx32 \
" Offset: %08" PRIx32 " Rawsize: %08" PRIx32 " %c%c%c %s\n",
section.virtualAddress + m_imageBase,
section.virtualSize,
section.pointerToRawData,
section.sizeOfRawData,
(flags & SegmentExecutable) > 0 ? 'x':'-',
(flags & SegmentReadable) > 0 ? 'r':'-',
(flags & SegmentWritable) > 0 ? 'w':'-',
section.name.c_str());
m_sections.push_back(section);
if (!isCLRBinary && section.name == ".cormeta")
isCLRBinary = true;
if (!section.virtualSize)
continue;
AddAutoSegment(section.virtualAddress + m_imageBase, section.virtualSize, section.pointerToRawData, section.sizeOfRawData, flags);
// Since COFF files are not image files, they don't have an entry point. So if the entry point isn't
// already set and this is an executable section, set the entry point to its beginning.
if (m_entryPoint == 0 && (flags & SegmentExecutable) != 0)
{
m_entryPoint = section.virtualAddress;
}
BNSectionSemantics semantics = DefaultSectionSemantics;
uint32_t pFlags = flags & 0x7;
if (pFlags == (SegmentReadable | SegmentExecutable))
semantics = ReadOnlyCodeSectionSemantics;
else if (pFlags == SegmentReadable)
semantics = ReadOnlyDataSectionSemantics;
else if (pFlags == (SegmentReadable | SegmentWritable))
semantics = ReadWriteDataSectionSemantics;
// FIXME: (from peview.cpp) For now override semantics for well known section names and warn about the semantic promotion
static map<string, BNSectionSemantics> promotedSectionSemantics =
{
{"text", ReadOnlyCodeSectionSemantics},
{"code", ReadOnlyCodeSectionSemantics},
{"rdata", ReadOnlyDataSectionSemantics},
{"data", ReadWriteDataSectionSemantics},
{"bss", ReadWriteDataSectionSemantics}
};
string shortName = section.name;
if (shortName.length() && shortName[0] == '.')
shortName.erase(shortName.begin());
transform(shortName.begin(), shortName.end(), shortName.begin(), ::tolower);
if (auto itr = promotedSectionSemantics.find(shortName); (itr != promotedSectionSemantics.end()) && (itr->second != semantics))
{
m_logger->LogInfo("COFF: %s section semantics have been promoted to facilitate analysis.", section.name.c_str());
semantics = itr->second;
}
auto emplaced = usedSectionNames.emplace(section.name, 1);
if (emplaced.second)
{
AddAutoSection(section.name, section.virtualAddress + m_imageBase, section.virtualSize, semantics);
}
else
{
stringstream ss;
ss << section.name << "_" << ++emplaced.first->second;
AddAutoSection(ss.str(), section.virtualAddress + m_imageBase, section.virtualSize, semantics);
}
}
EndBulkAddSegments();
// Apply architecture and platform
if (!m_arch)
{
switch (header.machine)
{
case IMAGE_FILE_MACHINE_I386:
m_logger->LogError("Support for COFF architecture 'x86' is not present");
break;
case IMAGE_FILE_MACHINE_ARM:
m_logger->LogError("Support for COFF architecture 'armv7' is not present");
break;
case IMAGE_FILE_MACHINE_ARMNT:
m_logger->LogError("Support for COFF architecture 'thumb2' is not present");
break;
case IMAGE_FILE_MACHINE_AMD64:
m_logger->LogError("Support for COFF architecture 'x86_64' is not present");
break;
case IMAGE_FILE_MACHINE_ARM64:
m_logger->LogError("Support for COFF architecture 'aarch64' is not present");
break;
default:
m_logger->LogError("COFF architecture '0x%x' is not supported", header.machine);
break;
}
if (!m_parseOnly)
m_logger->LogWarn("Unable to determine architecture. Please open the file with options and select a valid architecture.");
return false;
}
entryPointAddress = m_entryPoint;
if (header.machine == IMAGE_FILE_MACHINE_ARMNT)
{
// Special case for ARMNT machine type: all code is thumb2
// but low bit of function symbol addresses are not set, so force the
// entry point address to have its low bit set,
// otherwise GetAssociatedPlatformByAddress will say it's armv7
entryPointAddress |= 1;
m_logger->LogDebug("COFF: IMAGE_FILE_MACHINE_ARMNT, setting low bit in entry point %#" PRIx64 " to %#" PRIx64 "", m_entryPoint, entryPointAddress);
m_entryPoint = entryPointAddress;
}
Ref<Architecture> entryPointArch = m_arch->GetAssociatedArchitectureByAddress(entryPointAddress);
entryPointAddress = m_entryPoint;
SetDefaultArchitecture(entryPointArch);
GetParentView()->SetDefaultArchitecture(entryPointArch);
if (!platform)
{
platform = g_coffViewType->GetPlatform(IMAGE_SUBSYSTEM_UNKNOWN, m_arch);
m_logger->LogDebug("COFF: initial platform (%#x, arch: %s): %s", header.machine, m_arch->GetName().c_str(), platform->GetName().c_str());
}
if (!platformSetByUser)
platform = platform->GetAssociatedPlatformByAddress(entryPointAddress);
entryPointAddress = m_entryPoint;
m_logger->LogDebug("COFF: entry point %#" PRIx64 " associated platform (%#x, arch: %s): %s", entryPointAddress, header.machine, m_arch->GetName().c_str(), platform->GetName().c_str());
SetDefaultPlatform(platform);
SetDefaultArchitecture(platform->GetArchitecture());
m_logger->LogDebug("COFF: final entry point %#" PRIx64 " default (%#x, arch: %s): %s", entryPointAddress, header.machine, platform->GetName().c_str(), GetDefaultPlatform()->GetName().c_str());
// Finished for parse only mode
if (m_parseOnly)
return true;
// Create various COFF header yypes
// Create COFF Header Type
EnumerationBuilder coffHeaderMachineBuilder;
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_UNKNOWN);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_AM33);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_AMD64);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_ARM);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_ARM64);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_ARMNT);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_EBC);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_I386);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_IA64);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_M32R);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_MIPS16);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_MIPSFPU);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_MIPSFPU16);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_POWERPC);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_POWERPCFP);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_R4000);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_RISCV32);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_RISCV64);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_RISCV128);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_SH3);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_SH3DSP);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_SH4);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_SH5);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_THUMB);
ADD_ENUM_MEMBER(coffHeaderMachine, IMAGE_FILE_MACHINE_WCEMIPSV2);
BUILD_ENUM_TYPE(coffHeaderMachine, "coff_machine", 2);
// Ref<Enumeration> coffHeaderMachineEnum = coffHeaderMachineBuilder.Finalize();
// Ref<Type> coffHeaderMachineEnumType = Type::EnumerationType(GetParentView()->GetDefaultArchitecture(), coffHeaderMachineEnum, 2, false);
// BUILD_ENUM_TYPE(coffHeaderMachine, "coff_machine");
// string coffHeaderMachineEnumId = Type::GenerateAutoTypeId("coff", coffHeaderMachineEnumName);
// QualifiedName coffHeaderMachineEnumTypeName = DefineType(coffHeaderMachineEnumId, coffHeaderMachineEnumName, coffHeaderMachineEnumType);
EnumerationBuilder coffCharacteristicsBuilder;
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_RELOCS_STRIPPED);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_EXECUTABLE_IMAGE);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_LINE_NUMS_STRIPPED);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_LOCAL_SYMS_STRIPPED);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_AGGRESIVE_WS_TRIM);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_LARGE_ADDRESS_AWARE);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_BYTES_REVERSED_LO);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_32BIT_MACHINE);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_DEBUG_STRIPPED);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_NET_RUN_FROM_SWAP);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_SYSTEM);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_DLL);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_UP_SYSTEM_ONLY);
ADD_ENUM_MEMBER(coffCharacteristics, IMAGE_FILE_BYTES_REVERSED_HI);
// Ref<Enumeration> coffCharacteristicsEnum = coffCharacteristicsBuilder.Finalize();
// Ref<Type> coffCharacteristicsEnumType = Type::EnumerationType(GetParentView()->GetDefaultArchitecture(), coffCharacteristicsEnum, 2, false);
BUILD_ENUM_TYPE(coffCharacteristics, "coff_characteristics", 2);
// string coffCharacteristicsEnumId = Type::GenerateAutoTypeId("coff", coffCharacteristicsEnumName);
// QualifiedName coffCharacteristicsEnumTypeName = DefineType(coffCharacteristicsEnumId, coffCharacteristicsEnumName, coffCharacteristicsEnumType);
// TODO decorate members with comments once comments work with linear view
StructureBuilder coffHeaderBuilder;
coffHeaderBuilder.SetPacked(true);
if (header2.sig2 == 0xFFFF)
{
coffHeaderBuilder.AddMember(Type::IntegerType(2, false), "sig1");
coffHeaderBuilder.AddMember(Type::IntegerType(2, false), "sig2");
coffHeaderBuilder.AddMember(Type::IntegerType(2, false), "version");
coffHeaderBuilder.AddMember(Type::NamedType(this, coffHeaderMachineEnumTypeName), "machine");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "timeDateStamp");
coffHeaderBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 16), "UUID");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "unused1");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "unused2");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "unused3");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "unused4");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "numberOfSections");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "pointerToSymbolTable");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "numberOfSymbols");
}
else
{
coffHeaderBuilder.AddMember(Type::NamedType(this, coffHeaderMachineEnumTypeName), "machine");
coffHeaderBuilder.AddMember(Type::IntegerType(2, false), "numberOfSections");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "timeDateStamp");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "pointerToSymbolTable");
coffHeaderBuilder.AddMember(Type::IntegerType(4, false), "numberOfSymbols");
coffHeaderBuilder.AddMember(Type::IntegerType(2, false), "sizeOfOptionalHeader");
coffHeaderBuilder.AddMember(Type::NamedType(this, coffCharacteristicsEnumTypeName), "characteristics");
}
Ref<Structure> coffHeaderStruct = coffHeaderBuilder.Finalize();
Ref<Type> coffHeaderType = Type::StructureType(coffHeaderStruct);
QualifiedName coffHeaderName = string("COFF_Header");
string coffHeaderTypeId = Type::GenerateAutoTypeId("coff", coffHeaderName);
QualifiedName coffHeaderTypeName = DefineType(coffHeaderTypeId, coffHeaderName, coffHeaderType);
DefineDataVariable(m_imageBase, Type::NamedType(this, coffHeaderTypeName));
DefineAutoSymbol(new Symbol(DataSymbol, "__coff_header", m_imageBase, NoBinding));
EnumerationBuilder coffSectionFlagsBuilder;
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_RESERVED_0001);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_RESERVED_0002);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_RESERVED_0004);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_TYPE_NO_PAD);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_RESERVED_0010);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_CNT_CODE);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_CNT_INITIALIZED_DATA);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_CNT_UNINITIALIZED_DATA);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_LNK_OTHER);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_LNK_INFO);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_RESERVED_0400);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_LNK_REMOVE);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_LNK_COMDAT);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_GPREL);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_PURGEABLE);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_16BIT);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_LOCKED);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_PRELOAD);
// TODO fix the bug that causes flags to not be displayed when these are added to the enumeration
// NOTE: not a bug, it's by design -- the EnumerationData::IsBitFieldEnum() condition isn't satisfied because these members have overlapping bits
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_1BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_2BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_4BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_8BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_16BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_32BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_64BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_128BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_256BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_512BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_1024BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_2048BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_4096BYTES);
// ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_ALIGN_8192BYTES);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_LNK_NRELOC_OVFL);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_DISCARDABLE);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_NOT_CACHED);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_NOT_PAGED);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_SHARED);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_EXECUTE);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_READ);
ADD_ENUM_MEMBER(coffSectionFlags, IMAGE_SCN_MEM_WRITE);
// Ref<Enumeration> coffSectionFlagsEnum = coffSectionFlagsBuilder.Finalize();
// Ref<Type> coffSectionFlagsEnumType = Type::EnumerationType(GetParentView()->GetDefaultArchitecture(), coffSectionFlagsEnum, 4, false);
BUILD_ENUM_TYPE(coffSectionFlags, "coff_section_flags", 4);
// string coffSectionFlagsEnumId = Type::GenerateAutoTypeId("coff", coffSectionFlagsEnumName);
// QualifiedName coffSectionFlagsEnumTypeName = DefineType(coffSectionFlagsEnumId, coffSectionFlagsEnumName, coffSectionFlagsEnumType);
if (sectionCount)
{
StructureBuilder sectionHeaderBuilder;
sectionHeaderBuilder.SetPacked(true);
sectionHeaderBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, true), 8), "name");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "virtualSize");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "virtualAddress");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "sizeOfRawData");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "pointerToRawData");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "pointerToRelocations");
sectionHeaderBuilder.AddMember(Type::IntegerType(4, false), "pointerToLineNumbers");
sectionHeaderBuilder.AddMember(Type::IntegerType(2, false), "numberOfRelocations");
sectionHeaderBuilder.AddMember(Type::IntegerType(2, false), "numberOfLineNumbers");
sectionHeaderBuilder.AddMember(Type::NamedType(this, coffSectionFlagsEnumTypeName), "characteristics");
Ref<Structure> sectionHeaderStruct = sectionHeaderBuilder.Finalize();
Ref<Type> sectionHeaderStructType = Type::StructureType(sectionHeaderStruct);
QualifiedName sectionHeaderName = string("COFF_Section_Header");
string sectionHeaderTypeId = Type::GenerateAutoTypeId("COFF", sectionHeaderName);
QualifiedName sectionHeaderTypeName = DefineType(sectionHeaderTypeId, sectionHeaderName, sectionHeaderStructType);
DefineAutoSymbol(new Symbol(DataSymbol, "__section_headers", m_imageBase + sectionHeadersOffset, NoBinding));
for (uint32_t i = 0; i < sectionCount; i++)
{
auto sectionHeaderOffset = sectionHeadersOffset + i * sizeof(COFFSectionHeader);
string sectionName = m_sections[i].name;
DefineDataVariable(m_imageBase + sectionHeaderOffset, Type::NamedType(this, sectionHeaderTypeName));
DefineAutoSymbol(new Symbol(DataSymbol, "__sec_hdr_" + sectionName, m_imageBase + sectionHeaderOffset, NoBinding));
}
}
}
catch (std::exception& e)
{
m_logger->LogError("Failed to parse COFF headers: %s\n", e.what());
return false;
}
// The offset of the symbol table after adjusting for the alignment of the sections that precede it
uint64_t symbolTableAdjustedOffset = 0;
try
{
// Process COFF symbol table
if (header.coffSymbolCount)
{
EnumerationBuilder coffSymbolTypeBuilder;
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_NULL);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_VOID);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_CHAR);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_SHORT);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_INT);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_LONG);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_FLOAT);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_DOUBLE);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_STRUCT);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_UNION);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_ENUM);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_MOE);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_BYTE);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_WORD);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_UINT);
ADD_ENUM_MEMBER(coffSymbolType, IMAGE_SYM_TYPE_DWORD);
ADD_ENUM_MEMBER(coffSymbolType, MS_IMAGE_SYM_TYPE_FUNCTION);
BUILD_ENUM_TYPE(coffSymbolType, "coff_symbol_type", 2);
EnumerationBuilder coffSymbolStorageClassBuilder;
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_NULL);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_AUTOMATIC);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_EXTERNAL);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_STATIC);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_REGISTER);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_EXTERNAL_DEF);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_LABEL);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_UNDEFINED_LABEL);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_MEMBER_OF_STRUCT);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_ARGUMENT);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_STRUCT_TAG);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_MEMBER_OF_UNION);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_UNION_TAG);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_TYPE_DEFINITION);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_UNDEFINED_STATIC);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_ENUM_TAG);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_MEMBER_OF_ENUM);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_REGISTER_PARAM);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_BIT_FIELD);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_AUTOARG);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_LASTENT);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_BLOCK);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_FUNCTION);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_END_OF_STRUCT);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_FILE);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_SECTION);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_WEAK_EXTERNAL);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_HIDDEN);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_CLR_TOKEN);
ADD_ENUM_MEMBER(coffSymbolStorageClass, IMAGE_SYM_CLASS_END_OF_FUNCTION);
BUILD_ENUM_TYPE(coffSymbolStorageClass, "coff_symbol_storage_class", 1);
StructureBuilder coffSymbolBuilder;
coffSymbolBuilder.SetPacked(true);
StructureBuilder longNameBuilder;
longNameBuilder.SetPacked(true);
longNameBuilder.AddMember(Type::IntegerType(4, false), "zeroes");
longNameBuilder.AddMember(Type::IntegerType(4, false), "offset");
Ref<Structure> longNameStruct = longNameBuilder.Finalize();
Ref<Type> longNameStructType = Type::StructureType(longNameStruct);
StructureBuilder nameUnionBuilder;
nameUnionBuilder.SetStructureType(UnionStructureType);
nameUnionBuilder.SetPacked(true);
nameUnionBuilder.AddMember(longNameStructType, "longName");
nameUnionBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, true), 8), "shortName");
Ref<Structure> nameUnion = nameUnionBuilder.Finalize();
Ref<Type> nameUnionType = Type::StructureType(nameUnion);
coffSymbolBuilder.AddMember(nameUnionType, "name");
coffSymbolBuilder.AddMember(Type::IntegerType(4, false), "value");
coffSymbolBuilder.AddMember(Type::IntegerType(sectionIndexSize, true), "sectionNumber");
coffSymbolBuilder.AddMember(Type::NamedType(this, coffSymbolTypeEnumTypeName), "type");
coffSymbolBuilder.AddMember(Type::NamedType(this, coffSymbolStorageClassEnumTypeName), "storageClass");
coffSymbolBuilder.AddMember(Type::IntegerType(1, false), "numberOfAuxSymbols");
Ref<Structure> coffSymbolStruct = coffSymbolBuilder.Finalize();
Ref<Type> coffSymbolStructType = Type::StructureType(coffSymbolStruct);
QualifiedName coffSymbolName = string("COFF_Symbol");
string coffSymbolTypeId = Type::GenerateAutoTypeId("COFF", coffSymbolName);
QualifiedName coffSymbolTypeName = DefineType(coffSymbolTypeId, coffSymbolName, coffSymbolStructType);
//Auxiliary Format 1: Function Definitions
StructureBuilder coffAuxFunctionDefinitionBuilder;
coffAuxFunctionDefinitionBuilder.SetPacked(true);
coffAuxFunctionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "tagIndex");
coffAuxFunctionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "totalSize");
coffAuxFunctionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "pointerToLineNumber");
coffAuxFunctionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "pointerToNextFunction");
coffAuxFunctionDefinitionBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 2), "unused");
Ref<Structure> coffAuxFunctionDefinitionStruct = coffAuxFunctionDefinitionBuilder.Finalize();
Ref<Type> coffAuxFunctionDefinitionStructType = Type::StructureType(coffAuxFunctionDefinitionStruct);
QualifiedName coffAuxFunctionDefinitionName = string("COFF_AuxFunctionDefinition");
string coffAuxFunctionDefinitionTypeId = Type::GenerateAutoTypeId("COFF", coffAuxFunctionDefinitionName);
QualifiedName coffAuxFunctionDefinitionTypeName = DefineType(coffAuxFunctionDefinitionTypeId, coffAuxFunctionDefinitionName, coffAuxFunctionDefinitionStructType);
// Auxiliary Format 2: .bf and .ef Symbols
StructureBuilder coffAux_bf_And_ef_SymbolBuilder;
coffAux_bf_And_ef_SymbolBuilder.SetPacked(true);
coffAux_bf_And_ef_SymbolBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 4), "unused0");
coffAux_bf_And_ef_SymbolBuilder.AddMember(Type::IntegerType(4, false), "lineNumber");
coffAux_bf_And_ef_SymbolBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 6), "unused6");
coffAux_bf_And_ef_SymbolBuilder.AddMember(Type::IntegerType(4, false), "pointerToNextFunction");
coffAux_bf_And_ef_SymbolBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 2), "unused16");
Ref<Structure> coffAux_bf_And_ef_SymbolStruct = coffAux_bf_And_ef_SymbolBuilder.Finalize();
Ref<Type> coffAux_bf_And_ef_SymbolStructType = Type::StructureType(coffAux_bf_And_ef_SymbolStruct);
QualifiedName coffAux_bf_And_ef_SymbolName = string("COFF_Aux_bf_And_ef_Symbol");
string coffAux_bf_And_ef_SymbolTypeId = Type::GenerateAutoTypeId("COFF", coffAux_bf_And_ef_SymbolName);
QualifiedName coffAux_bf_And_ef_SymbolTypeName = DefineType(coffAux_bf_And_ef_SymbolTypeId, coffAux_bf_And_ef_SymbolName, coffAux_bf_And_ef_SymbolStructType);
// Auxiliary Format 3: Weak Externals
StructureBuilder coffAuxWeakExternalBuilder;
coffAuxWeakExternalBuilder.SetPacked(true);
coffAuxWeakExternalBuilder.AddMember(Type::IntegerType(4, false), "tagIndex");
coffAuxWeakExternalBuilder.AddMember(Type::IntegerType(4, false), "characteristics");
coffAuxWeakExternalBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 10), "unused");
Ref<Structure> coffAuxWeakExternalStruct = coffAuxWeakExternalBuilder.Finalize();
Ref<Type> coffAuxWeakExternalStructType = Type::StructureType(coffAuxWeakExternalStruct);
QualifiedName coffAuxWeakExternalName = string("COFF_AuxWeakExternal");
string coffAuxWeakExternalTypeId = Type::GenerateAutoTypeId("COFF", coffAuxWeakExternalName);
QualifiedName coffAuxWeakExternalTypeName = DefineType(coffAuxWeakExternalTypeId, coffAuxWeakExternalName, coffAuxWeakExternalStructType);
// Auxiliary Format 4: Files
StructureBuilder coffAuxFileBuilder;
coffAuxFileBuilder.SetPacked(true);
coffAuxFileBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, true), 18), "fileName");
Ref<Structure> coffAuxFileStruct = coffAuxFileBuilder.Finalize();
Ref<Type> coffAuxFileStructType = Type::StructureType(coffAuxFileStruct);
QualifiedName coffAuxFileName = string("COFF_AuxFile");
string coffAuxFileTypeId = Type::GenerateAutoTypeId("COFF", coffAuxFileName);
QualifiedName coffAuxFileTypeName = DefineType(coffAuxFileTypeId, coffAuxFileName, coffAuxFileStructType);
// Auxiliary Format 5: Section Definitions
StructureBuilder coffAuxSectionDefinitionBuilder;
coffAuxSectionDefinitionBuilder.SetPacked(true);
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "length");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(2, false), "numberOfRelocations");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(2, false), "numberOfLineNumbers");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(4, false), "checkSum");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(2, false), "number");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(1, false), "selection");
if (!isBigCOFF)
coffAuxSectionDefinitionBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 3), "unused");
else
{
coffAuxSectionDefinitionBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, false), 1), "unused");
coffAuxSectionDefinitionBuilder.AddMember(Type::IntegerType(2, false), "numberHighPart");
}
Ref<Structure> coffAuxSectionDefinitionStruct = coffAuxSectionDefinitionBuilder.Finalize();
Ref<Type> coffAuxSectionDefinitionStructType = Type::StructureType(coffAuxSectionDefinitionStruct);
QualifiedName coffAuxSectionDefinitionName = string("COFF_AuxSectionDefinition");
string coffAuxSectionDefinitionTypeId = Type::GenerateAutoTypeId("COFF", coffAuxSectionDefinitionName);
QualifiedName coffAuxSectionDefinitionTypeName = DefineType(coffAuxSectionDefinitionTypeId, coffAuxSectionDefinitionName, coffAuxSectionDefinitionStructType);
// CLR Token Definition
StructureBuilder coffAuxCLRTokenBuilder;
coffAuxCLRTokenBuilder.SetPacked(true);
coffAuxCLRTokenBuilder.AddMember(Type::IntegerType(1, false), "bAuxType");
coffAuxCLRTokenBuilder.AddMember(Type::IntegerType(1, false), "bReserved");
coffAuxCLRTokenBuilder.AddMember(Type::IntegerType(4, false), "SymbolTableIndex");
coffAuxCLRTokenBuilder.AddMember(Type::ArrayType(Type::IntegerType(1, true), 12), "Reserved");
Ref<Structure> coffAuxCLRTokenStruct = coffAuxCLRTokenBuilder.Finalize();
Ref<Type> coffAuxCLRTokenStructType = Type::StructureType(coffAuxCLRTokenStruct);
QualifiedName coffAuxCLRTokenName = string("COFF_AuxCLRToken");
string coffAuxCLRTokenTypeId = Type::GenerateAutoTypeId("COFF", coffAuxCLRTokenName);
QualifiedName coffAuxCLRTokenTypeName = DefineType(coffAuxCLRTokenTypeId, coffAuxCLRTokenName, coffAuxCLRTokenStructType);
// TODO: combine the aux symbol record struct types into a union:
// StructureBuilder coffAuxSymbolRecordBuilder(UnionStructureType);
size_t symbolTableSize = header.coffSymbolCount * sizeofCOFFSymbol;
auto lastSection = m_sections.back();
symbolTableAdjustedOffset = header.coffSymbolTable - lastSection.pointerToRawData + lastSection.virtualAddress;
auto coffSymbolTableBase = m_imageBase + symbolTableAdjustedOffset;
AddAutoSegment(coffSymbolTableBase, symbolTableSize, header.coffSymbolTable, symbolTableSize, SegmentReadable);
auto emplaced = usedSectionNames.emplace(".symtab", 1);
if (emplaced.second)
{
AddAutoSection(".symtab", coffSymbolTableBase, symbolTableSize, ReadOnlyDataSectionSemantics);
}
else
{
stringstream ss;
ss << ".symtab_" << ++emplaced.first->second;
AddAutoSection(ss.str(), coffSymbolTableBase, symbolTableSize, ReadOnlyDataSectionSemantics);
}
DefineDataVariable(coffSymbolTableBase, Type::ArrayType(Type::NamedType(this, coffSymbolName), header.coffSymbolCount));
DefineAutoSymbol(new Symbol(DataSymbol, "__symtab", coffSymbolTableBase, NoBinding));
BinaryReader stringReader(GetParentView(), LittleEndian);
uint64_t stringTableBaseRaw = header.coffSymbolTable + ((uint64_t) header.coffSymbolCount * sizeofCOFFSymbol);
stringReader.Seek(stringTableBaseRaw);
uint32_t stringTableSize = stringReader.Read32();
if ((stringTableBaseRaw + stringTableSize) > GetParentView()->GetEnd())
{
throw COFFFormatException("invalid COFF string table size");
}
int64_t stringTableBase = stringTableBaseRaw - header.coffSymbolTable + symbolTableAdjustedOffset;
AddAutoSegment(m_imageBase + stringTableBase, stringTableSize, stringTableBaseRaw, stringTableSize, SegmentReadable);
emplaced = usedSectionNames.emplace(".strtab", 1);
if (emplaced.second)
{
AddAutoSection(".strtab", m_imageBase + stringTableBase, stringTableSize, ReadOnlyDataSectionSemantics);
}
else
{
stringstream ss;
ss << ".strtab_" << ++emplaced.first->second;
AddAutoSection(ss.str(), m_imageBase + stringTableBase, stringTableSize, ReadOnlyDataSectionSemantics);
}
DefineDataVariable(m_imageBase + stringTableBase, Type::IntegerType(4, false));
DefineAutoSymbol(new Symbol(DataSymbol, "__strtab_size", m_imageBase + stringTableBase, NoBinding));
DefineAutoSymbol(new Symbol(DataSymbol, "__strtab", m_imageBase + stringTableBase + 4, NoBinding));
for (size_t i = 0; i < header.coffSymbolCount; i++)
{
reader.Seek(header.coffSymbolTable + (i * sizeofCOFFSymbol));
uint32_t e_zeroes = reader.Read32();
uint32_t e_offset = reader.Read32();
uint32_t e_value = reader.Read32();
uint32_t e_scnum = !isBigCOFF ? (uint32_t)reader.Read16() : reader.Read32();
uint16_t e_type = reader.Read16();
uint8_t e_sclass = reader.Read8();
uint8_t e_numaux = reader.Read8();
uint64_t virtualAddress = 0;
switch (e_scnum)
{
case IMAGE_SYM_UNDEFINED:
case (uint16_t)IMAGE_SYM_ABSOLUTE:
case (uint16_t)IMAGE_SYM_DEBUG:
break;
default:
if (size_t(e_scnum - 1) < m_sections.size())
virtualAddress = m_sections[size_t(e_scnum - 1)].virtualAddress + e_value;
break;
}
// read symbol name
string symbolName;
if (e_zeroes)
{
stringReader.Seek(header.coffSymbolTable + (i * sizeofCOFFSymbol));
symbolName = stringReader.ReadCString(8);
symbolName = symbolName.substr(0, strlen(symbolName.c_str()));
}
else
{
stringReader.Seek(stringTableBaseRaw + e_offset);
symbolName = stringReader.ReadCString();
}
BNSymbolBinding binding;
bool clrFunction = false;
switch (e_sclass)
{
case IMAGE_SYM_CLASS_EXTERNAL:
binding = GlobalBinding;
break;
case IMAGE_SYM_CLASS_STATIC:
binding = LocalBinding;
break;
case IMAGE_SYM_CLASS_CLR_TOKEN:
clrFunction = true;
binding = LocalBinding;
break;
default:
binding = NoBinding;
break;
}
uint8_t baseType = (e_type >> 4) & 0x3;
switch (baseType)
{
case IMAGE_SYM_DTYPE_NULL: // no derived type
{
if (virtualAddress)
AddCOFFSymbol(DataSymbol, "", symbolName, virtualAddress, binding);
break;
}
case IMAGE_SYM_DTYPE_POINTER: // pointer to base type
{
break;
}
case IMAGE_SYM_DTYPE_FUNCTION: // function that returns base type
{
if (virtualAddress)
{
if (!isCLRBinary)
{
auto functionAddress = virtualAddress;
if (header.machine == IMAGE_FILE_MACHINE_ARMNT)
{
// NOTE: for IMAGE_FILE_MACHINE_ARMNT, there are only thumb2 functions,
// so we force the low bit on for all function symbols
functionAddress |= 1;
}
AddCOFFSymbol(FunctionSymbol, "", symbolName, functionAddress, binding);
}