forked from kweatherman/IDA_ClassInformer_PlugIn
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
1633 lines (1441 loc) · 49.8 KB
/
Main.cpp
File metadata and controls
1633 lines (1441 loc) · 49.8 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
// Class Informer
#include "stdafx.h"
#include "Main.h"
#include "Vftable.h"
#include "RTTI.h"
#include "MainDialog.h"
#include <map>
//
#include <WaitBoxEx.h>
#include <IdaOgg.h>
// Netnode constants
const static char NETNODE_NAME[] = {"$ClassInformer_node"};
const char NN_DATA_TAG = 'A';
const char NN_TABLE_TAG = 'S';
// Our netnode value indexes
enum NETINDX
{
NIDX_VERSION, // ClassInformer version
NIDX_COUNT // Table entry count
};
// VFTable entry container (fits in a netnode MAXSPECSIZE size)
#pragma pack(push, 1)
struct TBLENTRY
{
ea_t vft;
WORD methods;
WORD flags;
WORD strSize;
char str[MAXSPECSIZE - (sizeof(ea_t) + (sizeof(WORD) * 3))]; // Note: IDA MAXSTR = 1024
};
#pragma pack(pop)
static_assert(sizeof(TBLENTRY) == MAXSPECSIZE);
// Line background color for non parent/top level hierarchy lines
// TOOD: Assumes text background is white. A way to make these user theme/style color aware?
#define GRAY(v) RGB(v,v,v)
static const bgcolor_t NOT_PARENT_COLOR = GRAY(235);
// === Function Prototypes ===
static void cacheSegments();
static BOOL processStaticTables();
static void showEndStats();
static BOOL gatherRttiDataSet(SegSelect::segments &segs);
// === Data ===
static TIMESTAMP s_startTime = 0;
static HMODULE myModuleHandle = NULL;
static UINT32 staticCCtorCnt = 0, staticCppCtorCnt = 0, staticCDtorCnt = 0;
static UINT32 startingFuncCount = 0, staticCtorDtorCnt = 0;
static BOOL initResourcesOnce = FALSE;
static int chooserIcon = 0;
static netnode *netNode = NULL;
static std::vector<SEGMENT> segmentCache;
static eaList colList;
extern eaSet superSet, colSet, vftSet;
#define IN_SUPER(_addr) (superSet.find(_addr) != superSet.end())
// "_initterm*" Static ctor/dtor pattern container
struct INITTERM_ARGPAT
{
LPCSTR pattern;
UINT32 start, end;
};
std::vector<INITTERM_ARGPAT> initTermArgPatterns;
// Options
BOOL g_optionPlaceStructs = TRUE;
BOOL g_optionProcessStatic = TRUE;
BOOL g_optionAudioOnDone = TRUE;
static void freeWorkingData()
{
try
{
RTTI::freeWorkingData();
colList.clear();
segmentCache.clear();
initTermArgPatterns.clear();
if (netNode)
{
delete netNode;
netNode = NULL;
}
}
CATCH()
}
// Initialize
plugmod_t* idaapi init()
{
char procName[IDAINFO_PROCNAME_SIZE + 1] = { 0 };
if(inf_get_procname(procName, sizeof(procName)) && (strncmp(procName, "metapc", IDAINFO_PROCNAME_SIZE) == 0))
{
GetModuleHandleEx((GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS), (LPCTSTR) &init, &myModuleHandle);
return PLUGIN_KEEP;
}
return PLUGIN_SKIP;
}
// Uninitialize
// Normally doesn't happen as we need to stay resident for the modal windows
void idaapi term()
{
try
{
OggPlay::endPlay();
freeWorkingData();
if (initResourcesOnce)
{
if (chooserIcon)
{
free_custom_icon(chooserIcon);
chooserIcon = 0;
}
Q_CLEANUP_RESOURCE(ClassInformerRes);
initResourcesOnce = FALSE;
}
}
CATCH()
}
// Init new netnode storage
#define DB_FORMAT_VERSION MAKEWORD(6, 0)
static void newNetnodeStore()
{
// Kill any existing store data first
netNode->altdel_all(NN_DATA_TAG);
netNode->supdel_all(NN_TABLE_TAG);
// Init defaults
netNode->altset_idx8(NIDX_VERSION, DB_FORMAT_VERSION, NN_DATA_TAG);
netNode->altset_idx8(NIDX_COUNT, 0, NN_DATA_TAG);
}
static WORD getStoreVersion(){ return((WORD) netNode->altval_idx8(NIDX_VERSION, NN_DATA_TAG)); }
static UINT32 getTableCount(){ return(netNode->altval_idx8(NIDX_COUNT, NN_DATA_TAG)); }
static BOOL setTableCount(UINT32 count){ return(netNode->altset_idx8(NIDX_COUNT, count, NN_DATA_TAG)); }
static BOOL getTableEntry(TBLENTRY &entry, UINT32 index){ return(netNode->supval(index, &entry, sizeof(TBLENTRY), NN_TABLE_TAG) > 0); }
static BOOL setTableEntry(TBLENTRY &entry, UINT32 index){ return(netNode->supset(index, &entry, (offsetof(TBLENTRY, str) + entry.strSize), NN_TABLE_TAG)); }
// Add an entry to the vftable list
void addTableEntry(UINT32 flags, ea_t vft, int methodCount, LPCSTR format, ...)
{
TBLENTRY e;
e.vft = vft;
e.methods = methodCount;
e.flags = flags;
va_list vl;
va_start(vl, format);
vsnprintf_s(e.str, sizeof(e.str), SIZESTR(e.str), format, vl);
va_end(vl);
e.strSize = (WORD) (strlen(e.str) + 1);
UINT32 count = getTableCount();
setTableEntry(e, count);
setTableCount(++count);
}
// RTTI list chooser
static const char LBTITLE[] = { "[Class Informer]" };
static const UINT32 LBCOLUMNCOUNT = 5;
static const int LBWIDTHS[LBCOLUMNCOUNT] = { (8 | CHCOL_HEX), (4 | CHCOL_DEC), 3, 19, 500 };
static const char *const LBHEADER[LBCOLUMNCOUNT] =
{
"Vftable",
"Methods",
"Flags",
"Type",
"Hierarchy"
};
class rtti_chooser : public chooser_multi_t
{
public:
rtti_chooser() : chooser_multi_t(CH_QFTYP_DEFAULT, LBCOLUMNCOUNT, LBWIDTHS, LBHEADER, LBTITLE)
{
// Create a minimal hex address format string w/leading zero
UINT32 count = getTableCount();
ea_t largestAddres = 0;
for (UINT32 i = 0; i < count; i++)
{
TBLENTRY e; e.vft = 0;
getTableEntry(e, i);
if (e.vft > largestAddres)
largestAddres = e.vft;
}
GetEaFormatString(largestAddres, addressFormat);
// Chooser icon
icon = chooserIcon;
}
virtual const void *get_obj_id(size_t *len) const
{
*len = sizeof(LBTITLE);
return LBTITLE;
}
virtual size_t get_count() const { return (size_t)getTableCount(); }
virtual void get_row(qstrvec_t *cols_, int *icon_, chooser_item_attrs_t *attributes, size_t n) const
{
try
{
if (netNode)
{
// Generate the line
TBLENTRY e;
getTableEntry(e, (UINT32)n);
// vft address
qstrvec_t &cols = *cols_;
cols[0].sprnt(addressFormat, e.vft);
// Method count
if (e.methods > 0)
cols[1].sprnt("%u", e.methods); // "%04u"
else
cols[1].sprnt("???");
// Flags
char flags[4];
int pos = 0;
if (e.flags & RTTI::CHD_MULTINH) flags[pos++] = 'M';
if (e.flags & RTTI::CHD_VIRTINH) flags[pos++] = 'V';
if (e.flags & RTTI::CHD_AMBIGUOUS) flags[pos++] = 'A';
flags[pos++] = 0;
cols[2] = flags;
// Type
LPCSTR tag = strchr(e.str, '@');
if (tag)
{
char buffer[MAXSTR];
int pos = (tag - e.str);
if (pos > SIZESTR(buffer)) pos = SIZESTR(buffer);
memcpy(buffer, e.str, pos);
buffer[pos] = 0;
cols[3] = buffer;
++tag;
}
else
{
// Can happen when string is MAXSTR and greater
cols[3] = "??** MAXSTR overflow!";
tag = e.str;
}
// Composition/hierarchy
cols[4] = tag;
//*icon_ = ((e.flags & RTTI::IS_TOP_LEVEL) ? 77 : 191);
*icon_ = 191;
// Indicate entry is not a top/parent level by color
if (!(e.flags & RTTI::IS_TOP_LEVEL))
attributes->color = NOT_PARENT_COLOR;
}
}
CATCH()
}
virtual cbres_t enter(sizevec_t *sel)
{
size_t n = sel->front();
if (n < get_count())
{
TBLENTRY e;
getTableEntry(e, (UINT32)n);
jumpto(e.vft);
}
return NOTHING_CHANGED;
}
virtual void closed()
{
freeWorkingData();
}
private:
char addressFormat[20];
};
// Locate Qt widget by class name
static QWidget *findChildByClass(QWidgetList &wl, LPCSTR className)
{
Q_FOREACH(QWidget *w, wl)
{
if (strcmp(w->metaObject()->className(), className) == 0)
return w;
}
return NULL;
}
// Find widget by title text
// If IDs are constant can use "static QWidget *QWidget::find(WId);"?
void customizeChooseWindow()
{
try
{
QApplication::processEvents();
// Mod the chooser view
QWidgetList pl = QApplication::activeWindow()->findChildren<QWidget*>("[Class Informer]");
if (QWidget *dw = findChildByClass(pl, "TChooser"))
{
QFile file(QT_RES_PATH "view-style.qss");
if (file.open(QFile::ReadOnly | QFile::Text))
dw->setStyleSheet(QTextStream(&file).readAll());
}
else
msg("** customizeChooseWindow(): \"TChooser\" not found!\n");
// Mod chooser widget to our own preferences
if (QTableView *tv = (QTableView *) findChildByClass(pl, "tchooser_table_widget_t"))
{
// Set sort by type name
tv->sortByColumn(3, Qt::DescendingOrder);
// Resize to contents to push the class hierarchy view to the right
tv->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents);
tv->resizeColumnsToContents();
tv->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
// Tweak the row height
UINT32 count = getTableCount();
for (UINT32 row = 0; row < count; row++)
tv->setRowHeight(row, 24);
}
else
msg("** customizeChooseWindow(): \"tchooser_table_widget_t\" not found!\n");
}
CATCH()
}
bool idaapi run(size_t arg)
{
try
{
qstring version;
msg("\n>> Class Informer: v%s, built %s.\n", GetVersionString(MY_VERSION, version).c_str(), __DATE__);
if (!auto_is_ok())
{
msg("** Class Informer: Must wait for IDA to finish processing before starting plug-in! **\n*** Aborted ***\n\n");
return TRUE;
}
WaitBox::processIdaEvents();
// Configure platform specifics
plat.Configure();
if (!initResourcesOnce)
{
initResourcesOnce = TRUE;
QResource::registerResource(":/resources.qrc");
QFile file(QT_RES_PATH "icon.png");
if (file.open(QFile::ReadOnly))
{
QByteArray ba = file.readAll();
chooserIcon = load_custom_icon(ba.constData(), ba.size(), "png");
}
}
OggPlay::endPlay();
freeWorkingData();
g_optionAudioOnDone = TRUE;
g_optionProcessStatic = TRUE;
g_optionPlaceStructs = TRUE;
startingFuncCount = (UINT32) get_func_qty();
staticCppCtorCnt = staticCCtorCnt = staticCtorDtorCnt = staticCDtorCnt = 0;
colList.clear();
// Create storage netnode
if(!(netNode = new netnode(NETNODE_NAME, SIZESTR(NETNODE_NAME), TRUE)))
{
_ASSERT(FALSE);
return TRUE;
}
// Read existing storage if any
UINT32 tableCount = getTableCount();
WORD storageVersion = getStoreVersion();
BOOL storageExists = (tableCount > 0);
// Ask if we should use storage or process again
if (storageExists)
{
// Version 2.3 didn't change the format
if (storageVersion != DB_FORMAT_VERSION)
{
msg("* Storage version mismatch, must rescan *\n");
storageExists = FALSE;
}
else
storageExists = (ask_yn(1, "TITLE Class Informer \nHIDECANCEL\nUse previously stored result? ") == 1);
}
BOOL aborted = FALSE;
if(!storageExists)
{
newNetnodeStore();
// Only MS Visual C++ targets are known
comp_t cmp = get_comp(default_compiler());
if (cmp != COMP_MS)
{
msg("** IDA reports target compiler: \"%s\"\n", get_compiler_name(cmp));
int iResult = ask_buttons(NULL, NULL, NULL, 0, "TITLE Class Informer\nHIDECANCEL\nIDA reports this IDB's compiler as: \"%s\" \n\nThis plug-in only understands MS Visual C++ targets.\nRunning it on other targets (like Borland� compiled, etc.) will have unpredicted results. \n\nDo you want to continue anyhow?", get_compiler_name(cmp));
if (iResult != 1)
{
msg("- Aborted -\n\n");
return TRUE;
}
}
// Do UI
SegSelect::segments segs;
if (doMainDialog(g_optionPlaceStructs, g_optionProcessStatic, g_optionAudioOnDone, segs, version, arg))
{
msg("- Canceled -\n\n");
freeWorkingData();
return TRUE;
}
WaitBox::show("Class Informer", "Please wait..", "url(" QT_RES_PATH "progress-style.qss)", QT_RES_PATH "icon.png");
WaitBox::updateAndCancelCheck(-1);
s_startTime = GetTimeStamp();
try
{
// Add RTTI type definitions to IDA once per session
static BOOL createStructsOnce = FALSE;
if (g_optionPlaceStructs && !createStructsOnce)
{
createStructsOnce = TRUE;
RTTI::addDefinitionsToIda();
}
msg("Caching data and code segments:\n");
WaitBox::processIdaEvents();
cacheSegments();
if(g_optionProcessStatic)
{
// Process global and static ctor sections
msg("\nProcessing C/C++ ctor & dtor tables:\n");
msg("-------------------------------------------------\n");
WaitBox::processIdaEvents();
if (!(aborted = processStaticTables()))
{
//msg("Processing time: %s.\n", TimeString(GetTimeStamp() - s_startTime));
}
}
if (!aborted)
{
// Get RTTI data
if (!(aborted = gatherRttiDataSet(segs)))
{
// Optionally play completion sound if processing took more than a few seconds to notify user
if (g_optionAudioOnDone)
{
TIMESTAMP endTime = (GetTimeStamp() - s_startTime);
if (endTime > (TIMESTAMP) 2.4)
{
OggPlay::endPlay();
QFile file(QT_RES_PATH "completed.ogg");
if (file.open(QFile::ReadOnly))
{
QByteArray ba = file.readAll();
OggPlay::playFromMemory((const PVOID)ba.constData(), ba.size(), TRUE);
}
}
}
showEndStats();
}
}
}
CATCH()
WaitBox::hide();
refresh_idaview_anyway();
if (aborted)
{
msg("- Aborted -\n\n");
return TRUE;
}
}
// Show list result window
if (!aborted && (getTableCount() > 0))
{
// The chooser allocation will free it's self automatically
rtti_chooser *chooserPtr = new rtti_chooser();
chooserPtr->choose();
customizeChooseWindow();
}
}
CATCH()
return TRUE;
}
// Print out end stats
static void showEndStats()
{
try
{
msg("\n-------------------------------------------------\n");
char buffer[32];
msg("RTTI vftables located: %s\n", NumberCommaString(getTableCount(), buffer));
UINT32 functionsFixed = ((UINT32) get_func_qty() - startingFuncCount);
if(functionsFixed)
msg("Missing functions fixed: %s\n", NumberCommaString(functionsFixed, buffer));
msg("Done. Total processing time: %s\n\n", TimeString(GetTimeStamp() - s_startTime));
}
CATCH()
}
// ================================================================================================
// Fix/create label and comment C/C++ initializer tables
static void setIntializerTable(ea_t start, ea_t end, BOOL isCpp)
{
try
{
if (UINT32 count = ((end - start) / plat.ptrSize))
{
// Set table elements as pointers
ea_t ea = start;
while (ea <= end)
{
fixEa(ea);
// Might fix missing/messed stubs
if (ea_t func = plat.getEa(ea))
fixFunction(func);
ea += (ea_t) plat.ptrSize;
};
// Start label
if (!hasName(start))
{
char name[MAXSTR];
if (isCpp)
sprintf_s(name, sizeof(name), "__xc_a_%d", staticCppCtorCnt);
else
sprintf_s(name, sizeof(name), "__xi_a_%d", staticCCtorCnt);
setName(start, name);
}
// End label
if (!hasName(end))
{
char name[MAXSTR];
if (isCpp)
sprintf_s(name, sizeof(name), "__xc_z_%d", staticCppCtorCnt);
else
sprintf_s(name, sizeof(name), "__xi_z_%d", staticCCtorCnt);
setName(end, name);
}
// Comment
// Never overwrite, it might be the segment comment
if (!hasAnteriorComment(start))
{
if (isCpp)
setAnteriorComment(start, "%d C++ static ctors (#classinformer)", count);
else
setAnteriorComment(start, "%d C initializers (#classinformer)", count);
}
else
// Place comment @ address instead
if (!hasComment(start))
{
if (isCpp)
{
char comment[MAXSTR];
sprintf_s(comment, sizeof(comment), "%d C++ static ctors (#classinformer)", count);
setComment(start, comment, TRUE);
}
else
{
char comment[MAXSTR];
sprintf_s(comment, sizeof(comment), "%d C initializers (#classinformer)", count);
setComment(start, comment, TRUE);
}
}
if (isCpp)
staticCppCtorCnt++;
else
staticCCtorCnt++;
}
}
CATCH()
}
// Fix/create label and comment C/C++ terminator tables
static void setTerminatorTable(ea_t start, ea_t end)
{
try
{
if (UINT32 count = ((end - start) / plat.ptrSize))
{
// Set table elements as pointers
ea_t ea = start;
while (ea <= end)
{
// Fix pointer as needed
fixEa(ea);
// Fix function as needed
if (ea_t func = plat.getEa(ea))
fixFunction(func);
ea += (ea_t) plat.ptrSize;
};
// Start label
if (!hasName(start))
{
char name[MAXSTR];
_snprintf_s(name, sizeof(name), SIZESTR(name), "__xt_a_%d", staticCDtorCnt);
setName(start, name);
}
// End label
if (!hasName(end))
{
char name[MAXSTR];
_snprintf_s(name, sizeof(name), SIZESTR(name), "__xt_z_%d", staticCDtorCnt);
setName(end, name);
}
// Comment
// Never overwrite, it might be the segment comment
if (!hasAnteriorComment(start))
setAnteriorComment(start, "%d C terminators (#classinformer)", count);
else
// Place comment @ address instead
if (!hasComment(start))
{
char comment[MAXSTR];
_snprintf_s(comment, sizeof(comment), SIZESTR(comment), "%d C terminators (#classinformer)", count);
setComment(start, comment, TRUE);
}
staticCDtorCnt++;
}
}
CATCH()
}
// "" for when we are uncertain of ctor or dtor type table
static void setCtorDtorTable(ea_t start, ea_t end)
{
try
{
if (UINT32 count = ((end - start) / plat.ptrSize))
{
// Set table elements as pointers
ea_t ea = start;
while (ea <= end)
{
// Fix pointer as needed
fixEa(ea);
// Fix function as needed
if (ea_t func = plat.getEa(ea))
fixFunction(func);
ea += (ea_t) plat.ptrSize;
};
// Start label
if (!hasName(start))
{
char name[MAXSTR];
_snprintf_s(name, sizeof(name), SIZESTR(name), "__x?_a_%d", staticCtorDtorCnt);
setName(start, name);
}
// End label
if (!hasName(end))
{
char name[MAXSTR];
_snprintf_s(name, sizeof(name), SIZESTR(name), "__x?_z_%d", staticCtorDtorCnt);
setName(end, name);
}
// Comment
// Never overwrite, it might be the segment comment
if (!hasAnteriorComment(start))
setAnteriorComment(start, "%d C initializers/terminators (#classinformer)", count);
else
// Place comment @ address instead
if (!hasComment(start))
{
char comment[MAXSTR];
_snprintf_s(comment, sizeof(comment), SIZESTR(comment), "%d C initializers/terminators (#classinformer)", count);
setComment(start, comment, TRUE);
}
staticCtorDtorCnt++;
}
}
CATCH()
}
// Process redister based _initterm()
static void processRegisterInitterm(ea_t start, ea_t end, ea_t call)
{
if ((end != BADADDR) && (start != BADADDR))
{
// Should be in the same segment
const SEGMENT *startSeg = FindCachedSegment(start);
const SEGMENT *endSeg = FindCachedSegment(end);
if ((startSeg && endSeg) && (startSeg == endSeg))
{
if (start > end)
swap_t(start, end);
msg(" %llX to %llX CTOR table.\n", start, end);
setIntializerTable(start, end, TRUE);
if(!hasComment(call))
setComment(call, "_initterm", TRUE);
}
else
msg(" ** Bad address range of %llX, %llX for \"_initterm\" type ** <click address>.\n", start, end);
}
}
static UINT32 doInittermTable(func_t *func, ea_t start, ea_t end, LPCSTR name)
{
UINT32 found = FALSE;
if ((start != BADADDR) && (end != BADADDR))
{
// Should be in the same segment
const SEGMENT *startSeg = FindCachedSegment(start);
const SEGMENT *endSeg = FindCachedSegment(end);
if ((startSeg && endSeg) && (startSeg == endSeg))
{
if (start > end)
swap_t(start, end);
// Try to determine if we are in dtor or ctor section
if (func)
{
qstring qstr;
if (get_long_name(&qstr, func->start_ea) > 0)
{
char funcName[MAXSTR];
strncpy_s(funcName, MAXSTR, qstr.c_str(), (MAXSTR - 1));
_strlwr(funcName);
// Start/ctor?
if (strstr(funcName, "cinit") || strstr(funcName, "tmaincrtstartup") || strstr(funcName, "start"))
{
msg(" %llX to %llX CTOR table.\n", start, end);
setIntializerTable(start, end, TRUE);
found = TRUE;
}
else
// Exit/dtor function?
if (strstr(funcName, "exit"))
{
msg(" %llX to %llX DTOR table.\n", start, end);
setTerminatorTable(start, end);
found = TRUE;
}
}
}
if (!found)
{
// Fall back to generic assumption
msg(" %llX to %llX CTOR/DTOR table.\n", start, end);
setCtorDtorTable(start, end);
found = TRUE;
}
}
else
msg(" ** Miss matched segment table addresses %llX, %llX for \"%s\" type **\n", start, end, name);
}
else
msg(" ** Bad input address range of %llX, %llX for \"%s\" type **\n", start, end, name);
return(found);
}
// Process _initterm function
// Returns TRUE if at least one found
static BOOL processInitterm(ea_t address, LPCSTR name)
{
msg("%llX process initterm: \"%s\" \n", address, name);
UINT32 count = 0;
// Walk xrefs
ea_t xref = get_first_fcref_to(address);
while (xref && (xref != BADADDR))
{
msg(" %llX \"%s\" xref.\n", xref, name);
// Should be code
if (is_code(get_flags(xref)))
{
do
{
// The most common are two instruction arguments
// Back up two instructions
ea_t instruction1 = prev_head(xref, 0);
if (instruction1 == BADADDR)
break;
ea_t instruction2 = prev_head(instruction1, 0);
if (instruction2 == BADADDR)
break;
// Bail instructions are past the function start now
func_t *func = get_func(xref);
if (func && (instruction2 < func->start_ea))
{
//msg(" %llX arg2 outside of contained function **\n", func->start_ea);
break;
}
BOOL matched = FALSE;
UINT32 patternCount = (UINT32) initTermArgPatterns.size();
for (UINT32 i = 0; (i < patternCount) && !matched; i++)
{
ea_t match = FIND_BINARY(instruction2, xref, initTermArgPatterns[i].pattern);
if (match != BADADDR)
{
ea_t start, end;
if (!plat.is64)
{
start = plat.getEa32(match + initTermArgPatterns[i].start);
end = plat.getEa32(match + initTermArgPatterns[i].end);
}
else
{
UINT32 startOffset = get_32bit(instruction1 + initTermArgPatterns[i].start);
UINT32 endOffset = get_32bit(instruction2 + initTermArgPatterns[i].end);
start = (instruction1 + 7 + *((PINT32) &startOffset)); // TODO: 7 is hard coded instruction length, put this in arg2pat table?
end = (instruction2 + 7 + *((PINT32) &endOffset));
}
msg(" %llX Two instruction pattern match #%d\n", match, i);
count += doInittermTable(func, start, end, name);
matched = TRUE;
break;
}
}
// 3 instruction
/*
searchStart = prev_head(searchStart, BADADDR);
if (searchStart == BADADDR)
break;
if (func && (searchStart < func->start_ea))
break;
if (func && (searchStart < func->start_ea))
{
msg(" %llX arg3 outside of contained function **\n", func->start_ea);
break;
}
.text:10008F78 push offset unk_1000B1B8
.text:10008F7D push offset unk_1000B1B0
.text:10008F82 mov dword_1000F83C, 1
"68 ?? ?? ?? ?? 68 ?? ?? ?? ?? C7 05 ?? ?? ?? ?? ?? ?? ?? ??"
*/
if (!matched)
msg(" ** arguments not located!\n");
} while (FALSE);
}
else
msg(" %llX ** \"%s\" xref is not code! **\n", xref, name);
xref = get_next_fcref_to(address, xref);
};
if(count > 0)
msg(" \n");
return(count > 0);
}
// Cache code and data segments for fast indexing
static void cacheSegments()
{
segmentCache.clear();
// Special case for a single segment, probably from a binary blob
int count = get_segm_qty();
if (count == 1)
{
segment_t *seg = getnseg(0);
SEGMENT ns = { seg->start_ea, seg->end_ea, (_CODE_SEG | _DATA_SEG) };
// Max PE COFF segment names are 8 chars
ns.name[0] = 0;
qstring name;
if (get_segm_name(&name, seg, 0) > 0)
strncpy_s(ns.name, 9, name.c_str(), 8);
segmentCache.push_back(ns);
}
else
{
for (int i = 0; i < count; i++)
{
if (segment_t *seg = getnseg(i))
{
UINT32 type = 0;
if (seg->type == SEG_DATA)
type |= _DATA_SEG;
else
if (seg->type == SEG_CODE)
type |= _CODE_SEG;
if (type)
{
SEGMENT ns = { seg->start_ea, seg->end_ea, type };
ns.name[0] = 0;
qstring name;
if (get_segm_name(&name, seg, 0) > 0)
strncpy_s(ns.name, 9, name.c_str(), 8);
segmentCache.push_back(ns);
}
}
}
}
// Ensure sort by ascending address
std::sort(segmentCache.begin(), segmentCache.end(), [](const SEGMENT &a, const SEGMENT &b) { return a.start < b.start; });
}
// Segment cache O(log n) binary search lookup
const SEGMENT *FindCachedSegment(ea_t addr)
{
int left = 0;
int right = (int) segmentCache.size();
while (left != (right - 1))
{
int mid = (left + (right - left) / 2);
if (addr <= segmentCache[mid - 1].end)
right = mid;
else
if (addr >= segmentCache[mid].start)
left = mid;
else
{
// Gap between regions
return NULL;
}
};
const SEGMENT *seg = &segmentCache[left];
if ((addr >= seg->start) && (addr <= seg->end))
return seg;
// Below or above all regions
return NULL;
}
// Process global/static ctor & dtor tables.
// Returns TRUE if user aborted
static BOOL processStaticTables()
{
staticCppCtorCnt = staticCCtorCnt = staticCtorDtorCnt = staticCDtorCnt = 0;
try