-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCore.cpp
More file actions
1841 lines (1622 loc) · 60.7 KB
/
Core.cpp
File metadata and controls
1841 lines (1622 loc) · 60.7 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
// ****************************************************************************
// File: Core.cpp
// Desc: Core of the
//
// ****************************************************************************
#include "stdafx.h"
#include "ContainersInl.h"
#include <WaitBoxEx.h>
//#include <SegSelect.h>
#include <IdaOgg.h>
#include "complete_ogg.h"
#include <hash_set>
typedef stdext::hash_set<ea_t> ADDRSET;
// Preprocessor line backup
// WIN32;NDEBUG;_WINDOWS;_USRDLL;_WINDLL;__NT__;__IDP__;__VC__;NO_OBSOLETE_FUNCS;BUILD_QWINDOW=1;QT_DLL;QT_GUI_LIB;QT_XML_LIB;QT_CORE_LIB;QT_NAMESPACE=QT;QT_THREAD_SUPPORT;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)
//#define VBDEV
//#define LOG_FILE
// Count of eSTATE_PASS_1 unknown byte gather passes
#define UNKNOWN_PASSES 8
// x86 hack for speed in alignment value searching
// Defs from IDA headers, not supposed to be exported but need to because some cases not covered
// by SDK accessors, etc.
//#define MS_VAL 0x000000FFL // Mask for byte value
//#define FF_UNK 0x00000000L // Unknown ?
#define FF_IVL 0x00000100L // Byte has value ?
//#define FF_DATA 0x00000400L // Data ?
//#define FF_TAIL 0x00000200L // Tail ?
#define FF_REF 0x00001000L // has references
#define FF_0OFF 0x00500000L // Offset?
//#define FF_ASCI 0x50000000L // ASCII ?
const flags_t ALIGN_VALUE1 = (FF_IVL | 0xCC); // 0xCC (single byte "int 3") byte type
const flags_t ALIGN_VALUE2 = (FF_IVL | 0x90); // NOP byte type
/*
1st pass. Look for " dd " without "offset". Finds missing code
For each found:
1. Find the extents of the block and undefine it
2. Analise it for code
2nd pass. Look for " dw " without "offset". Finds missing code
Same as above.
3nd pass. Look for " db " without "offset". Finds missing code
Same as above.
4th pass. Look at gaps between functions. Finds missing functions
If code is found try to make a function of it.
5th pass. Look for bad function blocks. These are blocks that are incorrectly placed as function headers, etc.
If found, try to add them to their proper owner functions.
*/
// Process states
enum eSTATES
{
eSTATE_INIT, // Initialize
eSTATE_START, // Start processing up
eSTATE_PASS_1, // Find unknown data in code space
eSTATE_PASS_2, // Find missing "align" blocks
eSTATE_PASS_3, // Find lost code instructions
eSTATE_PASS_4, // Find missing functions part 1
eSTATE_PASS_5, // Find bad function blocks
eSTATE_FINISH, // Done
eSTATE_EXIT,
};
static const char SITE_URL[] = { "http://www.macromonkey.com/bb/" };
// UI options bit flags
// *** Must be same sequence as check box options
static SBITFLAG BitF;
const static WORD OPT_DATATOBYTES = BitF.Next();
const static WORD OPT_ALIGNBLOCKS = BitF.Next();
const static WORD OPT_MISSINGCODE = BitF.Next();
const static WORD OPT_MISSINGFUNC = BitF.Next();
const static WORD OPT_BADBLOCKS = BitF.Next();
// Function info container
struct tFUNCNODE : public Container::NodeEx<Container::ListHT, tFUNCNODE>
{
ea_t uAddress;
UINT uSize;
// Use IDA allocs
static PVOID operator new(size_t size){ return(qalloc(size)); };
static void operator delete(PVOID _Ptr){ return(qfree(_Ptr)); }
};
// === Function Prototypes ===
static void ShowEndStats();
static BOOL CheckBreak();
static void NextState();
static LPCTSTR GetDisasmText(ea_t ea);
static LPCTSTR TimeString(TIMESTAMP Time);
static BOOL BuildFuncionList();
static void FlushFunctionList();
static void ProcessFuncGap(ea_t startEA, UINT uSize);
static bool idaapi IsAlignByte(flags_t flags, void *ud);
static bool idaapi IsData(flags_t flags, void *ud);
static BOOL InCode(ea_t eaAddress);
static BOOL IsBadFuncStart(func_t *pFunc);
static int FixFuncBlock(ea_t eaBlock);
// === Data ===
static TIMESTAMP s_StartTime = 0, s_StepTime = 0;
static segment_t *s_thisSeg = NULL;
static ea_t s_eaSegStart = NULL;
static ea_t s_eaSegEnd = NULL;
static ea_t s_eaCurrentAddress = NULL;
static ea_t s_eaLastAddress = NULL;
#ifdef LOG_FILE
static FILE *s_hLogFile = NULL;
#endif
static BOOL s_bStepStop = TRUE;
static eSTATES s_eState = eSTATE_INIT;
static int s_iStartFuncCount = 0;
static int s_iProgressSteps = 0;
static int s_iProgressStep = 0;
static int s_iPass1Loops = 0;
static UINT s_uStep5Func = 0;
//
static UINT s_uUnknowns = 0;
static UINT s_uAligns = 0;
static UINT s_uBlocksFixed = 0;
//static UINT s_uAlignFails = 0;
//static UINT s_uCodeFixes = 0;
//static UINT s_uCodeFixFails = 0;
//
static BOOL s_bDoDataToBytes = TRUE;
static BOOL s_bDoAlignBlocks = TRUE;
static BOOL s_bDoMissingCode = TRUE;
static BOOL s_bDoMissingFunc = TRUE;
static BOOL s_bDoBadBlocks = TRUE;
static WORD s_wAudioAlertWhenDone = 1;
//static SegSelect::segments *chosen = NULL;
static ALIGN(16) Container::ListEx<Container::ListHT, tFUNCNODE> s_FuncList;
// Options dialog
static const char optionDialog[] =
{
"BUTTON YES* Continue\n" // 'Continue' instead of 'okay'
// Help body
"HELP\n"
"\"ExtraPass PlugIn\""
"An IDA Pro Win32 x86 executable clean up plugin, by Sirmabus\n\n"
"This plugin does an \"extra pass\" to help fix and cleanup the IDB.\n"
"It can find tens of thousands missing functions and alignment blocks making\n"
"your IDB more complete and easier to reverse.\n\n"
"It actually does essentially five processing steps:\n"
"1. Convert stray code section values to \"unknown\".\n"
"2. Fix missing \"align\" blocks.\n"
"3. Fix missing code bytes.\n"
"4. Locate and fix missing/undefined functions.\n"
"5. Locate and fix bad function blocks.\n\n"
"It's intended for, and only tested on typical MSVC and Intel complied Windows\n"
"32bit binary executables but it might still be helpful on Delphi/Borland and\n"
"other complied targets.\n"
"For best results, run the plugin at least two times.\n"
"Will not work well with Borland(r) and other targets that has data mixed with code in the same space.\n"
"See \"ExtraPass.txt\" for more help.\n\n"
"Forum: http://www.macromonkey.com/bb/\n"
"ENDHELP\n"
// Title
"ExtraPass Plugin\n"
// Message text
"-Version: %A build: %A by Sirmabus-\n"
"<#Click to open my site.#www.macromonkey.com:k : 2 : 1::>\n\n"
"Choose processing steps:\n"
// checkbox -> s_wDoDataToBytes
"<#Scan the entire code section converting all unknown DD,DW,DB data declarations to\n"
"unknown bytes, to be reexamined as possible code, functions, and alignment blocks\n"
"in the following passes.#1 Convert unknown data. :C>\n"
// checkbox -> s_wDoAlignBlocks
"<#Fix missing \"align xx\" blocks.#2 Fix align blocks.:C>\n"
// checkbox -> s_wDoMissingCode
"<#Fix lost code instructions.#3 Fix missing code.:C>\n"
// checkbox -> s_wDoMissingFunc
"<#Fix missing/undeclared functions.#4 Fix missing functions.:C>\n"
// checkbox -> s_bDoBadBlocks
"<#Fix bad/unconnected function blocks. Bad blocks incorrectly placed as a function head block\n"
"when in actuality is a tail block, etc.#5 Fix bad function blocks.:C>>\n"
// checkbox -> s_wAudioAlertWhenDone
"<#Play sound on completion.#Play sound on completion. :C>>\n"
"<#Choose the code segment(s) to process.\nElse will use the first CODE segment by default.\n#Choose Code Segments:B:1:8::>\n"
" "
};
// Initialize
void CORE_Init()
{
s_eState = eSTATE_INIT;
}
// Un-initialize
void CORE_Exit()
{
try
{
#ifdef LOG_FILE
if(s_hLogFile)
{
qfclose(s_hLogFile);
s_hLogFile = NULL;
}
#endif
//if (chosen)
//{
// SegSelect::free(chosen);
// chosen = NULL;
//}
FlushFunctionList();
OggPlay::endPlay();
set_user_defined_prefix(0, NULL);
}
CATCH()
}
// Handler for choose code and data segment buttons
static void idaapi ChooseBtnHandler(TView *fields[], int code)
{
//if (chosen = SegSelect::select(SegSelect::CODE_HINT, "Choose code segments"))
//{
// msg("Chosen: ");
// for (SegSelect::segments::iterator it = chosen->begin(); it != chosen->end(); ++it)
// {
// char buffer[64];
// if (get_true_segm_name(*it, buffer, SIZESTR(buffer)) <= 0)
// strcpy(buffer, "????");
// SegSelect::segments::iterator it2 = it; ++it2;
// if (it2 != chosen->end())
// msg("\"%s\", ", buffer);
// else
// msg("\"%s\"", buffer);
// }
// msg("\n");
// WaitBox::processIdaEvents();
//}
}
static void idaapi DoHyperlink(TView *fields[], int code) { open_url(SITE_URL); }
// Plug-in process
void CORE_Process(int iArg)
{
try
{
while (TRUE)
{
switch (s_eState)
{
// Initialize
case eSTATE_INIT:
{
msg("\n== ExtraPass plugin: v: %s, BD: %s, By Sirmabus ==\n", MY_VERSION, __DATE__);
WaitBox::processIdaEvents();
// Do UI for process pass selection
s_bDoDataToBytes = s_bDoAlignBlocks = s_bDoMissingCode = s_bDoMissingFunc = s_bDoBadBlocks = TRUE;
s_wAudioAlertWhenDone = TRUE;
WORD wOptionFlags = 0;
if (s_bDoDataToBytes) wOptionFlags |= OPT_DATATOBYTES;
if (s_bDoAlignBlocks) wOptionFlags |= OPT_ALIGNBLOCKS;
if (s_bDoMissingCode) wOptionFlags |= OPT_MISSINGCODE;
if (s_bDoMissingFunc) wOptionFlags |= OPT_MISSINGFUNC;
if (s_bDoBadBlocks) wOptionFlags |= OPT_BADBLOCKS;
{
// To add forum URL to help box
int iUIResult = AskUsingForm_c(optionDialog, MY_VERSION, __DATE__, DoHyperlink, &wOptionFlags, &s_wAudioAlertWhenDone, ChooseBtnHandler);
if (!iUIResult || (wOptionFlags == 0))
{
// User canceled, or no options selected, bail out
msg(" - Canceled -\n\n");
WaitBox::processIdaEvents();
s_eState = eSTATE_EXIT;
break;
}
s_bDoDataToBytes = ((wOptionFlags & OPT_DATATOBYTES) != 0);
s_bDoAlignBlocks = ((wOptionFlags & OPT_ALIGNBLOCKS) != 0);
s_bDoMissingCode = ((wOptionFlags & OPT_MISSINGCODE) != 0);
s_bDoMissingFunc = ((wOptionFlags & OPT_MISSINGFUNC) != 0);
s_bDoBadBlocks = ((wOptionFlags & OPT_BADBLOCKS) != 0);
}
// IDA must be IDLE
if (autoIsOk())
{
// Ask for the log file name once
#ifdef LOG_FILE
if(!s_hLogFile)
{
if(char *szFileName = askfile_c(1, "*.txt", "Select a log file name:"))
{
// Open it for appending
s_hLogFile = qfopen(szFileName, "ab");
}
}
if(!s_hLogFile)
{
msg("** Log file open failed! Aborted. **\n");
return;
}
#endif
s_thisSeg = NULL;
s_uUnknowns = 0;
s_iProgressStep = 0;
s_iPass1Loops = 0;
s_iStartFuncCount = get_func_qty();
if (s_iStartFuncCount > 0)
{
msg("Starting function count: %d\n", s_iStartFuncCount);
WaitBox::processIdaEvents();
/*
msg("\n=========== Segments ===========\n");
int iSegCount = get_segm_qty();
for(int i = 0; i < iSegCount; i++)
{
if(segment_t *pSegInfo = getnseg(i))
{
char szName[128] = {0};
get_segm_name(pSegInfo, szName, (sizeof(szName) - 1));
char szClass[16] = {0};
get_segm_class(pSegInfo, szClass, (sizeof(szClass) - 1));
msg("[%d] \"%s\", \"%s\".\n", i, szName, szClass);
}
}
*/
// First chosen seg
//if (chosen && !chosen->empty())
//{
// s_thisSeg = chosen->back();
// chosen->pop_back();
//}
//else
// Use the first CODE seg
{
int iSegCount = get_segm_qty();
int iIndex = 0;
for (; iIndex < iSegCount; iIndex++)
{
if (s_thisSeg = getnseg(iIndex))
{
char sclass[32];
if (get_segm_class(s_thisSeg, sclass, SIZESTR(sclass)) <= 0)
break;
else
if (strcmp(sclass, "CODE") == 0)
break;
}
}
if (iIndex >= iSegCount)
s_thisSeg = NULL;
}
if (s_thisSeg)
{
WaitBox::show();
s_eaSegStart = s_thisSeg->startEA;
s_eaSegEnd = s_thisSeg->endEA;
NextState();
break;
}
else
msg("** No code segment found to process! **\n*** Aborted ***\n\n");
}
else
msg("** No functions in DB?! **\n*** Aborted ***\n\n");
}
else
msg("** Wait for IDA to finish processing before starting plugin! **\n*** Aborted ***\n\n");
// Canceled or error'ed, bail out
s_eState = eSTATE_EXIT;
}
break;
// Start up process
case eSTATE_START:
{
// Cheating on the fact: BOOL == (int) 1
s_iProgressSteps = ((s_bDoDataToBytes ? UNKNOWN_PASSES : 0) + (s_bDoAlignBlocks + s_bDoMissingCode + s_bDoMissingFunc + s_bDoBadBlocks));
s_eaCurrentAddress = 0;
s_iProgressStep = 0;
char name[64];
if (get_true_segm_name(s_thisSeg, name, SIZESTR(name)) <= 0)
strcpy(name, "????");
char sclass[32];
if(get_segm_class(s_thisSeg, sclass, SIZESTR(sclass)) <= 0)
strcpy(sclass, "????");
msg("\nProcessing segment: \"%s\", type: %s, address: %08X-%08X, size: %08X\n\n", name, sclass, s_thisSeg->startEA, s_thisSeg->endEA, s_thisSeg->size());
// Move to first process state
s_StartTime = GetTimeStamp();
NextState();
}
break;
// Find unknown data values in code
case eSTATE_PASS_1:
{
// nextthat next_head next_not_tail next_visea nextaddr
if (s_eaCurrentAddress < s_eaSegEnd)
{
// Value at this location data?
autoWait();
flags_t Flags = getFlags(s_eaCurrentAddress);
if (isData(Flags) && !isAlign(Flags))
{
//msg("%08X %08X data\n", s_eaCurrentAddress, Flags);
ea_t eaEnd = next_head(s_eaCurrentAddress, s_eaSegEnd);
// Handle an occasional over run case
if (eaEnd == BADADDR)
{
//msg("%08X **** abort end\n", s_eaCurrentAddress);
s_eaCurrentAddress = (s_eaSegEnd - 1);
break;
}
// Skip if it has offset reference (most common occurance)
BOOL bSkip = FALSE;
if (Flags & FF_0OFF)
{
//msg(" skip offset.\n");
bSkip = TRUE;
}
else
// Has a reference?
if (Flags & FF_REF)
{
ea_t eaDRef = get_first_dref_to(s_eaCurrentAddress);
if (eaDRef != BADADDR)
{
// Ref part an offset?
flags_t ValueRef = getFlags(eaDRef);
if (isCode(ValueRef) && isOff1(ValueRef))
{
// Decide instruction to global "cmd" struct
BOOL bIsByteAccess = FALSE;
if (decode_insn(eaDRef))
{
switch (cmd.itype)
{
// movxx style move a byte?
case NN_movzx:
case NN_movsx:
{
//msg("%08X movzx\n", s_eaCurrentAddress);
bIsByteAccess = TRUE;
}
break;
case NN_mov:
{
if ((cmd.Operands[0].type == o_reg) && (cmd.Operands[1].dtyp == dt_byte))
{
//msg("%08X mov\n", s_eaCurrentAddress);
/*
msg(" [0] T: %d, D: %d, \n", cmd.Operands[0].type, cmd.Operands[0].dtyp);
msg(" [1] T: %d, D: %d, \n", cmd.Operands[1].type, cmd.Operands[1].dtyp);
msg(" [2] T: %d, D: %d, \n", cmd.Operands[2].type, cmd.Operands[2].dtyp);
msg(" [3] T: %d, D: %d, \n", cmd.Operands[3].type, cmd.Operands[3].dtyp);
*/
bIsByteAccess = TRUE;
}
}
break;
};
}
// If it's byte access, assume it's a byte switch table
if (bIsByteAccess)
{
//msg("%08X not byte\n", s_eaCurrentAddress);
autoWait();
do_unknown(s_eaCurrentAddress, DOUNK_SIMPLE);
auto_mark_range(s_eaCurrentAddress, eaEnd, AU_UNK);
autoWait();
// Step through making the array, and any bad size a byte
//for(ea_t i = s_eaCurrentAddress; i < eaEnd; i++){ doByte(i, 1); }
doByte(s_eaCurrentAddress, (eaEnd - s_eaCurrentAddress));
autoWait();
bSkip = TRUE;
}
}
}
}
// Make it unknown bytes
if (!bSkip)
{
//msg("%08X %08X %02X unknown\n", s_eaCurrentAddress, eaEnd, getFlags(s_eaCurrentAddress));
autoWait();
do_unknown(s_eaCurrentAddress, DOUNK_SIMPLE);
for (ea_t i = (s_eaCurrentAddress + 1); i < eaEnd; i++){ do_unknown(i, DOUNK_SIMPLE); }
autoWait();
auto_mark_range(s_eaCurrentAddress, eaEnd, AU_UNK);
s_uUnknowns++;
autoWait();
// Note: Might have triggered auto-analysis and a alignment or function could be here now
}
// Advance to next data value, or the end which ever comes first
s_eaCurrentAddress = eaEnd;
if (s_eaCurrentAddress < s_eaSegEnd)
{
s_eaCurrentAddress = nextthat(s_eaCurrentAddress, s_eaSegEnd, IsData, NULL);
break;
}
}
else
{
// Advance to next data value, or the end which ever comes first
s_eaCurrentAddress = nextthat(s_eaCurrentAddress, s_eaSegEnd, IsData, NULL);
break;
}
}
if (++s_iPass1Loops < UNKNOWN_PASSES)
{
//msg("** Pass %d Unknowns: %u\n", s_iPass1Loops, s_uUnknowns);
s_eaCurrentAddress = s_eaLastAddress = s_eaSegStart;
}
else
{
//msg("** Pass %d Unknowns: %u\n", s_iPass1Loops, s_uUnknowns);
NextState();
}
}
break;
// Find missing align blocks
case eSTATE_PASS_2:
{
#define NEXT(_Here, _Limit) nextthat(_Here, _Limit, IsAlignByte, NULL)
// Still inside this code segment?
ea_t endEA = s_eaSegEnd;
if (s_eaCurrentAddress < endEA)
{
// Look for next unknown alignment type byte
// Will return BADADDR if none found which will catch in the endEA test
autoWait();
flags_t StartValue = getFlags(s_eaCurrentAddress);
if (!IsAlignByte(StartValue, NULL))
s_eaCurrentAddress = NEXT(s_eaCurrentAddress, s_eaSegEnd);
if (s_eaCurrentAddress < endEA)
{
// Catch when we get caught up in an array, etc.
ea_t eaStartAddress = s_eaCurrentAddress;
if (s_eaCurrentAddress <= s_eaLastAddress)
{
// Move to next header and try again..
msg("%08X F: %08X *** Align test in array #1 ***\n", s_eaCurrentAddress);
s_eaCurrentAddress = s_eaLastAddress = nextaddr(s_eaCurrentAddress);
break;
}
//msg("%08X Start.\n", eaStartAddress);
//msg("%08X F: %08X.\n", eaStartAddress, getFlags(eaStartAddress));
s_eaLastAddress = s_eaCurrentAddress;
// Get run count of this align byte
UINT uAlignByteCount = 1;
flags_t StartAlignValue = getFlags(eaStartAddress);
while (TRUE)
{
// Next byte
s_eaCurrentAddress = nextaddr(s_eaCurrentAddress);
//msg("%08X Next.\n", s_eaCurrentAddress);
//msg("%08X F: %08X.\n", s_eaCurrentAddress, getFlags(s_eaCurrentAddress));
if (s_eaCurrentAddress < endEA)
{
// Catch when we get caught up in an array, etc.
if (s_eaCurrentAddress <= s_eaLastAddress)
{
msg("%08X F: %08X *** Align test in array #2 ***\n", eaStartAddress);
s_eaCurrentAddress = s_eaLastAddress = nextaddr(s_eaCurrentAddress);
break;
}
s_eaLastAddress = s_eaCurrentAddress;
// Count if it' still the same byte
if (getFlags(s_eaCurrentAddress) == StartAlignValue)
uAlignByteCount++;
else
break;
}
else
break;
};
// Do these bytes bring about at least a 16 (could be 32) align?
// TODO: Must we consider other alignments such as 4 and 8?
// Probably a compiler option that is not normally used anymore.
if (((eaStartAddress + uAlignByteCount) & (16 - 1)) == 0)
{
// If short count, only try alignment if the line above or a below us has n xref
// We don't want to try to align odd code and switch table bytes, etc.
if (uAlignByteCount <= 2)
{
BOOL bHasRef = FALSE;
// Before us
ea_t eaEndAddress = (eaStartAddress + uAlignByteCount);
ea_t eaRef = get_first_cref_from(eaEndAddress);
if (eaRef != BADADDR)
{
//msg("%08X cref from end.\n", eaEndAddress);
bHasRef = TRUE;
}
else
{
eaRef = get_first_cref_to(eaEndAddress);
if (eaRef != BADADDR)
{
//msg("%08X cref to end.\n", eaEndAddress);
bHasRef = TRUE;
}
}
// After us
if (eaRef == BADADDR)
{
ea_t eaForeAddress = (eaStartAddress - 1);
eaRef = get_first_cref_from(eaForeAddress);
if (eaRef != BADADDR)
{
//msg("%08X cref from start.\n", eaForeAddress);
bHasRef = TRUE;
}
else
{
eaRef = get_first_cref_to(eaForeAddress);
if (eaRef != BADADDR)
{
//msg("%08X cref to start.\n", eaForeAddress);
bHasRef = TRUE;
}
}
}
// No code ref, now look for a broken code ref
if (eaRef == BADADDR)
{
// This is still not complete as it could still be code, but pointing to a vftable
// entry in data.
// But should be fixed on more passes.
ea_t eaEndAddress = (eaStartAddress + uAlignByteCount);
eaRef = get_first_dref_from(eaEndAddress);
if (eaRef != BADADDR)
{
// If it the ref points to code assume code is just broken here
if (isCode(getFlags(eaRef)))
{
//msg("%08X dref from end %08X.\n", eaRef, eaEndAddress);
bHasRef = TRUE;
}
}
else
{
eaRef = get_first_dref_to(eaEndAddress);
if (eaRef != BADADDR)
{
if (isCode(getFlags(eaRef)))
{
//msg("%08X dref to end %08X.\n", eaRef, eaEndAddress);
bHasRef = TRUE;
}
}
}
if (eaRef == BADADDR)
{
//msg("%08X NO REF.\n", eaStartAddress);
}
}
// Assume it's not an alignment byte(s) and bail out
if (!bHasRef) break;
}
// Attempt to make it an align block
bool bResult = doAlign(eaStartAddress, uAlignByteCount, 0);
// IDA will some times fail on 32 aligns for some reason, give it another try
if (!bResult)
{
// Try again with explicit limits
bResult = doAlign(eaStartAddress, uAlignByteCount, 32);
if (!bResult)
bResult = doAlign(eaStartAddress, uAlignByteCount, 16);
}
if (bResult)
{
//msg("%08X %d ALIGN.\n", eaStartAddress, uAlignByteCount);
s_uAligns++;
}
else
{
// There are several times will IDA will fail even when the alignment block is obvious.
// Usually when it's an ALIGN(32) and there is a run of 16 align bytes
// Could at least do a code analize on it. Then IDA will at least make a mini array of it
//msg("%08X %d ** align fail **\n", eaStartAddress, uAlignByteCount);
//s_uAlignFails++;
}
}
}
break;
}
s_eaCurrentAddress = s_eaSegEnd;
CheckBreak();
NextState();
#undef NEXT
}
break;
// Find missing code
case eSTATE_PASS_3:
{
// Still inside segment?
if (s_eaCurrentAddress < s_eaSegEnd)
{
// Look for next unknown value
autoWait();
ea_t eaStartAddress = next_unknown(s_eaCurrentAddress, s_eaSegEnd);
if (eaStartAddress < s_eaSegEnd)
{
s_eaCurrentAddress = eaStartAddress;
//s_uStrayBYTE++;
//msg("%08X Code.\n");
// Catch when we get caught up in an array, etc.
if (s_eaCurrentAddress <= s_eaLastAddress)
{
// Move to next header and try again..
msg("%08X F: %08X *** Align Pass 5 array catch ***\n", s_eaCurrentAddress);
s_eaCurrentAddress = next_unknown(s_eaCurrentAddress, s_eaSegEnd);
s_eaLastAddress = s_eaCurrentAddress;
break;
}
s_eaLastAddress = s_eaCurrentAddress;
// Try to make code of it
#if 0
int iResult = ua_code(s_eaCurrentAddress);
//msg(" Result: %08X.\n", iResult);
if(iResult > 0)
{
//s_uCodeFixes++;
}
else
{
//msg("%08X fix fail.\n", s_eaCurrentAddress);
//s_uCodeFixFails++;
}
#endif
// Start from possible next byte
s_eaCurrentAddress++;
break;
}
}
// Next state
s_eaCurrentAddress = s_eaSegEnd;
CheckBreak();
NextState();
}
break;
// Discover missing functions part 1
case eSTATE_PASS_4:
{
// Process function list top down
if (tFUNCNODE *pHeadNode = s_FuncList.GetHead())
{
// Process it
ProcessFuncGap((s_eaCurrentAddress = pHeadNode->uAddress), pHeadNode->uSize);
// Remove function entry
s_FuncList.RemoveHead();
delete pHeadNode;
}
else
{
s_eaCurrentAddress = s_eaSegEnd;
CheckBreak();
NextState();
}
}
break;
// Discover missing functions part 2
case eSTATE_PASS_5:
{
// Examine next function
if (s_uStep5Func < get_func_qty())
{
if (func_t *pFunc = getn_func(s_uStep5Func))
{
if (IsBadFuncStart(pFunc))
{
s_uBlocksFixed += (UINT)(FixFuncBlock(pFunc->startEA) > 0);
}
}
s_uStep5Func++;
}
else
{
s_eaCurrentAddress = s_eaSegEnd;
CheckBreak();
NextState();
}
}
break;
// Finished processing
case eSTATE_FINISH:
{
NextState();
}
break;
// Done processing
case eSTATE_EXIT:
{
NextState();
goto BailOut;
}
break;
};
// Check & bail out on 'break' press
if (CheckBreak())
goto BailOut;
//Sleep(1); // Breathing room
};
BailOut:;
WaitBox::hide();
}
CATCH()
}
// Decide next state to take
static void NextState()
{
// Rewind
if(s_eState < eSTATE_FINISH)
{
// Top of code seg
s_eaCurrentAddress = s_eaLastAddress = s_eaSegStart;
//SafeJumpTo(s_uCurrentAddress);
autoWait();
}
// Logic
switch(s_eState)
{
// Init
case eSTATE_INIT:
{
s_eState = eSTATE_START;
}
break;
// Start
case eSTATE_START:
{
if(s_bDoDataToBytes)
{
msg("===== Fixing bad code bytes =====\n");
s_StepTime = GetTimeStamp();
s_eState = eSTATE_PASS_1;
}
else
if(s_bDoAlignBlocks)
{
msg("===== Missing align blocks =====\n");
s_StepTime = GetTimeStamp();
s_eState = eSTATE_PASS_2;
}
else
if(s_bDoMissingCode)
{
msg("===== Missing code =====\n");
s_StepTime = GetTimeStamp();
s_eState = eSTATE_PASS_3;
}
else
if(s_bDoMissingFunc)
{
msg("===== Missing functions =====\n");
WaitBox::processIdaEvents();
s_StepTime = GetTimeStamp();
// Function list problem in IDA 6.x still?
BuildFuncionList();
s_eState = eSTATE_PASS_4;
}
else
if(s_bDoBadBlocks)
{
msg("===== Bad function blocks =====\n");
s_StepTime = GetTimeStamp();
s_uStep5Func = 0;
s_eState = eSTATE_PASS_5;
}
else
s_eState = eSTATE_FINISH;
WaitBox::processIdaEvents();
s_iProgressStep = 1;
}
break;
// Find unknown data in code space
case eSTATE_PASS_1:
{
msg("Time: %s.\n\n", TimeString(GetTimeStamp() - s_StepTime));
if(s_bDoAlignBlocks)
{
msg("===== Missing align blocks =====\n");
s_StepTime = GetTimeStamp();
s_eState = eSTATE_PASS_2;
}
else
if(s_bDoMissingCode)
{
msg("===== Missing code =====\n");
s_StepTime = GetTimeStamp();
s_eState = eSTATE_PASS_3;
}
else
if(s_bDoMissingFunc)
{
msg("===== Missing functions =====\n");
WaitBox::processIdaEvents();
s_StepTime = GetTimeStamp();
BuildFuncionList();
s_eState = eSTATE_PASS_4;
}
else
if(s_bDoBadBlocks)
{
msg("===== Bad function blocks =====\n");
s_StepTime = GetTimeStamp();
s_uStep5Func = 0;
s_eState = eSTATE_PASS_5;
}
else