-
Notifications
You must be signed in to change notification settings - Fork 2
/
Decompiler.cpp
2545 lines (2333 loc) · 78.9 KB
/
Decompiler.cpp
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 "stdafx.h"
#include "SCIPicEditor.h"
#include "Decompiler.h"
#include "Compile\PMachine.h"
#include "Compile\ScriptOMAll.h"
#include "Compile\scii.h"
#include <boost/foreach.hpp>
using namespace sci;
using namespace std;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
ValueType _ScriptObjectTypeToPropertyValueType(ICompiledScriptSpecificLookups::ObjectType type)
{
switch (type)
{
case ICompiledScriptSpecificLookups::ObjectTypeSaid:
return ValueTypeToken; // since it already includes the ' '
break;
case ICompiledScriptSpecificLookups::ObjectTypeString:
return ValueTypeString;
break;
case ICompiledScriptSpecificLookups::ObjectTypeClass:
return ValueTypeToken;
break;
}
return ValueTypeToken;
}
//
// Represents whether an instruction consumes or generates stack or accumulator
// In general, values will be 0 or 1, except for cStackConsume which could be
// much larger (e.g. for send or call instruction)
//
struct Consumption
{
Consumption()
{
cAccConsume = 0;
cStackConsume = 0;
cAccGenerate = 0;
cStackGenerate = 0;
}
int cAccConsume;
int cStackConsume;
int cAccGenerate;
int cStackGenerate;
};
bool _IsVOIndexed(BYTE bOpcode)
{
return !!(bOpcode & 0x08);
}
bool _IsVOPureStack(BYTE bOpcode)
{
return !!(bOpcode & 0x04);
}
bool _IsVOStack(BYTE bOpcode)
{
// It's a stack operation if it says it's a stack operation,
// or if the accumulator is being used as an index.
// WARNING PHIL: true for store, but maybe no load???
return _IsVOPureStack(bOpcode) || _IsVOIndexed(bOpcode);
}
bool _IsVOStoreOperation(BYTE bOpcode)
{
return ((bOpcode & 0x30) == 0x10);
}
bool _IsVOIncremented(BYTE bOpcode)
{
return ((bOpcode & 0x30) == VO_INC_AND_LOAD);
}
bool _IsVODecremented(BYTE bOpcode)
{
return ((bOpcode & 0x30) == VO_DEC_AND_LOAD);
}
//
// A currently abandoned attempt at writing a decompiler. Not even close to being done.
//
//
// De-compiler notes
//
// We'll to, in DisassembleFunction, arrange them into scii instructions. Point the branches to each other.
// Each instruction needs to claim whether it puts something onto the stack or acc.
// Some things start new lines, line assignments, sends, calls.
// Could look for patterns. e.g.
// *IF-ELSE*
// blah
// bnt A
// code
// jmp B
// A: code
// B: code
//
// *DO*
// A: code
// code
// bt A
//
// *WHILE*
// code
// A: bnt B
// code
// jmp A:
//
//
// We don't have goto statements, so jmps are a problem.
// I think they only happen in if and switches and loops.
//
// We could have tables of common param names (init/client) and var names ?
//
//
//
std::string _GetPublicProcedureName(WORD wScript, WORD wIndex)
{
std::stringstream ss;
ss << "proc" << wScript << "_" << wIndex;
return ss.str();
}
typedef std::list<scii>::reverse_iterator rcode_pos;
struct Fixup
{
code_pos branchInstruction;
WORD wTarget;
bool fForward;
};
code_pos get_cur_pos(std::list<scii> &code)
{
code_pos pos = code.end();
--pos;
return pos;
}
//
// pBegin/pEnd - bounding pointers for the raw byte code
// wBaseOffset - byte offset in script file where pBegin is (used to calculate absolute code offsets)
// code - (out) list of sci instructions.
//
void _ConvertToInstructions(std::list<scii> &code, const BYTE *pBegin, const BYTE *pEnd, WORD wBaseOffset)
{
std::map<WORD, code_pos> referenceToCodePos;
std::vector<Fixup> branchTargetsToFixup;
code_pos undetermined = code.end();
WORD wReferencePosition = 0;
const BYTE *pCur = pBegin;
while (pCur < pEnd)
{
const BYTE *pThisInstruction = pCur;
BYTE bRawOpcode = *pCur;
bool bByte = (*pCur) & 1;
BYTE bOpcode = bRawOpcode >> 1;
ASSERT(bOpcode < 128);
++pCur; // Advance past opcode.
WORD wOperands[3];
ZeroMemory(wOperands, sizeof(wOperands));
int cIncr = 0;
for (int i = 0; i < 3; i++)
{
cIncr = GetOperandSize(bRawOpcode, OpArgTypes[bOpcode][i]);
switch (cIncr)
{
case 1:
wOperands[i] = (WORD)*pCur;
break;
case 2:
wOperands[i] = *((WORD*)pCur); // REVIEW
break;
default:
break;
}
pCur += cIncr;
if (cIncr == 0) // No more operands
{
break;
}
}
// Add the instruction - use the constructor that takes all arguments, even if
// not all are valid.
WORD wReferenceNextInstruction = (wReferencePosition + (WORD)(pCur - pThisInstruction));
if ((bOpcode == acBNT) || (bOpcode == acBT) || (bOpcode == acJMP))
{
// +1 because its the operand start pos.
WORD wTarget = CalcOffset(wReferencePosition + 1, wOperands[0], bByte, bRawOpcode);
code.push_back(scii(bOpcode, undetermined, true));
bool fForward = (wTarget > wReferencePosition);
Fixup fixup = { get_cur_pos(code), wTarget, fForward };
branchTargetsToFixup.push_back(fixup);
char sz[100];
StringCchPrintf(sz, ARRAYSIZE(sz), "Ref pos: %d --> %d\n", wReferencePosition, wTarget);
OutputDebugString(sz);
}
else
{
code.push_back(scii(bOpcode, wOperands[0], wOperands[1], wOperands[2]));
char sz[100];
StringCchPrintf(sz, ARRAYSIZE(sz), "Ref pos: %d\n", wReferencePosition);
OutputDebugString(sz);
}
// Store the position of the instruction we just added:
referenceToCodePos[wReferencePosition] = get_cur_pos(code);
// Store the actual offset in the instruction itself:
WORD wSize = (WORD)(pCur - pThisInstruction);
get_cur_pos(code)->set_offset_and_size(wReferencePosition + wBaseOffset, wSize);
wReferencePosition += wSize;
}
// Now fixup any branches.
for (size_t i = 0; i < branchTargetsToFixup.size(); i++)
{
Fixup &fixup = branchTargetsToFixup[i];
char sz[100];
StringCchPrintf(sz, ARRAYSIZE(sz), "%s: %d", fixup.fForward ? "fwd" : "back", fixup.wTarget);
OutputDebugString(sz);
std::map<WORD, code_pos>::iterator it = referenceToCodePos.find(fixup.wTarget);
if (it != referenceToCodePos.end())
{
OutputDebugString(" - success\n");
fixup.branchInstruction->set_branch_target(it->second, fixup.fForward);
}
else
{
ASSERT(FALSE);
OutputDebugString(" - Error in script\n");
}
}
// Special hack... function code is placed at even intervals. That means there might be an extra bogus
// instruction at the end, just after a ret statement (often it is acBNOT, which is 0). If the instruction
// before the end is a ret instruction, remove the last instruction (unless it's also a ret - since sometimes
// functions will end with two RETs, both of which are jump targets).
if (code.size() > 1)
{
code_pos theEnd = code.end();
--theEnd; // Last instruction
code_pos maybeRET = theEnd;
--maybeRET;
if ((maybeRET->get_opcode() == acRET) && (theEnd->get_opcode() != acRET))
{
code.erase(theEnd);
}
}
}
struct BranchBlock
{
code_pos begin;
code_pos end;
};
bool IsDelineatingInstruction(code_pos pos)
{
BYTE bOpcode = pos->get_opcode();
return (bOpcode == acBNT) || (bOpcode == acBT) || (bOpcode == acJMP);
}
bool IsBranchInstruction(code_pos pos)
{
return IsDelineatingInstruction(pos);
}
bool _IsVariableUse(code_pos pos, BYTE variableType, WORD &wIndex)
{
bool fRet = false;
BYTE bOpcode = pos->get_opcode();
if (OpArgTypes[bOpcode][0] == otVAR)
{
// It's a variable opcode.
wIndex = pos->get_first_operand();
fRet = ((bOpcode & 0x03) == variableType);
}
else if (bOpcode == acLEA)
{
// The "load effective address" instruction
WORD wType = pos->get_first_operand();
fRet = ((bOpcode & 0x03) == variableType);
if (fRet)
{
wIndex = pos->get_second_operand();
}
}
return fRet;
}
std::string _GetSuitableParameterName(FunctionBase &function, WORD iIndex)
{
if ((function.GetName() == "changeState") && (iIndex == 1))
{
return "newState";
}
if ((function.GetName() == "handleEvent") && (iIndex == 1))
{
return "pEvent";
}
std::stringstream ss;
ss << "param" << iIndex;
return ss.str();
}
void _FigureOutParameters(FunctionBase &function, FunctionSignature &signature, std::list<scii> &code)
{
WORD wBiggest = 0;
for (code_pos pos = code.begin(); pos != code.end(); ++pos)
{
WORD wIndex;
if (_IsVariableUse(pos, 3, wIndex)) // 3 -> param
{
wBiggest = max(wIndex, wBiggest);
}
}
if (wBiggest) // Parameters start at index 1, so 0 means no parameters
{
for (WORD i = 1; i <= wBiggest; i++)
{
std::auto_ptr<FunctionParameter> pParam(new FunctionParameter);
pParam->SetName(_GetSuitableParameterName(function, i));
pParam->SetDataType("var"); // Generic for now... we could try to detect things in the future.
signature.AddParam(pParam, false); // false -> hard to detect if optional or not... serious code analysis req'd
}
}
}
//
// Scans the code for local variable usage, and adds "local0, local1, etc..." variables to function.
//
template<typename _TVarHolder>
void _FigureOutTempVariables(_TVarHolder &function, BYTE variableType, std::list<scii> &code)
{
// Look for the link instruction.
WORD cTotalVariableRoom = 0;
for (code_pos pos = code.begin(); pos != code.end(); ++pos)
{
if (pos->get_opcode() == acLINK)
{
cTotalVariableRoom = pos->get_first_operand();
break;
}
}
if (cTotalVariableRoom)
{
// Track all accesses of variables
std::set<WORD> variableIndexAccess; // Index of accesses.
variableIndexAccess.insert(0); // Always put 0 access at least
for (code_pos pos = code.begin(); pos != code.end(); ++pos)
{
WORD wIndex;
if (_IsVariableUse(pos, variableType, wIndex))
{
variableIndexAccess.insert(wIndex);
}
}
// Now let's create a bunch of variables - but at least one.
WORD cVariables = static_cast<WORD>(variableIndexAccess.size());
std::set<WORD>::iterator accessIt = variableIndexAccess.begin();
for (WORD i = 0; i < cVariables; i++)
{
WORD wBegin = *accessIt;
++accessIt;
WORD wEnd;
if (accessIt != variableIndexAccess.end())
{
wEnd = *accessIt;
}
else
{
wEnd = cTotalVariableRoom;
}
std::auto_ptr<VariableDecl> pVar(new VariableDecl());
std::stringstream ss;
ss << "temp" << i;
pVar->SetName(ss.str());
pVar->SetSize(wEnd - wBegin);
function.AddVariable(pVar);
}
}
}
std::string _indent(int iIndent)
{
std::string theFill;
theFill.insert(theFill.begin(), iIndent, ' ');
return theFill;
}
// Fwd decl
class CodeShape;
//
// Attempt at generating an instruction tree. Used to turn a flat sequence of
// instructions into a tree so that, for example, a send call at the root, would
// have each of its parameters.
//
// e.g. if (5 == gEgo.x)
// would be something like:
//
// bnt
// eq?
// ldi 5
// push
// send
// push0
// pushi
//
class CodeNode
{
public:
CodeNode(code_pos pos) : _pos(pos), _targetLabel(0) {}
~CodeNode()
{
for_each(_children.begin(), _children.end(), delete_object());
}
void SetCode(code_pos pos) { _pos = pos; }
code_pos GetCode() const { return _pos; }
void AddChild(std::auto_ptr<CodeNode> pNode) { _children.insert(_children.begin(), pNode.get()); pNode.release(); }
size_t GetChildCount() { return _children.size(); }
CodeNode *Child(size_t i) { return _children[i]; }
std::vector<CodeNode*>::iterator begin() { return _children.begin(); }
std::vector<CodeNode*>::iterator end() { return _children.end(); }
// For debugging
void SetLabel(char c) { if (!_label.empty()) { _label += ","; } _label += c; }
void SetTargetLabel(char c) { _targetLabel = c; }
void Print(std::ostream &os, int iIndent) const
{
os << _indent(iIndent);
if (!_label.empty())
{
os << _label << ":";
}
os << OpcodeNames[_pos->get_opcode()];
if (_targetLabel)
{
os << "--> " << _targetLabel;
}
os << "\n";
std::vector<CodeNode*>::const_iterator it;
for (it = _children.begin(); it != _children.end(); ++it)
{
(*it)->Print(os, iIndent + 2);
}
}
private:
code_pos _pos; // The instruction
std::vector<CodeNode*> _children; // The child code nodes
std::string _label; // For debugging
char _targetLabel; // For debugging
};
typedef std::vector<CodeNode*>::iterator codenode_it;
Consumption _GetInstructionConsumption(scii &inst)
{
BYTE bOpcode = inst.get_opcode();
ASSERT(bOpcode < 128);
int cEatStack = 0;
bool fChangesAcc = false;
bool fEatsAcc = false;
bool fPutsOnStack = false;
switch (bOpcode)
{
case acSELF:
cEatStack = inst.get_first_operand() / 2;
fChangesAcc = true;
break;
case acSEND:
cEatStack = inst.get_first_operand() / 2;
fChangesAcc = true;
fEatsAcc = true;
break;
case acSUPER:
cEatStack = inst.get_second_operand() / 2;
fChangesAcc = true;
break;
case acBNOT:
case acNOT:
case acNEG:
fChangesAcc = true;
fEatsAcc = true;
break;
case acSUB:
case acMUL:
case acDIV:
case acMOD:
case acSHR:
case acSHL:
case acXOR:
case acAND:
case acOR:
case acADD:
case acEQ:
case acGT:
case acLT:
case acLE:
case acNE:
case acGE:
case acUGT:
case acUGE:
case acULT:
case acULE:
fChangesAcc = true;
fEatsAcc = true;
cEatStack = 1;
break;
case acBT:
case acBNT:
fEatsAcc = true;
break;
case acRET:
// Wreaks havoc
//fEatsAcc = true; // But not always intentional...
break;
case acJMP:
case acLINK:
break;
case acLDI:
fChangesAcc = true;
break;
case acPUSH:
fEatsAcc = true;
fPutsOnStack = true;
break;
case acPUSHI:
case acPUSH0:
case acPUSH1:
case acPUSH2:
fPutsOnStack = true;
break;
case acPUSHSELF:
fPutsOnStack = true;
break;
case acTOSS:
//fChangesAcc = true; // doesn't touch the acc, by definition (toss)
cEatStack = 1;
break;
case acDUP:
fPutsOnStack = true;
break;
case acCALL:
case acCALLK:
case acCALLB:
cEatStack = inst.get_second_operand() / 2;
cEatStack++; // the number didn't include the # of instructions push.
fChangesAcc = true;
break;
case acCALLE:
//fEatsAcc = true;
cEatStack = inst.get_third_operand() / 2;
cEatStack++; // Also a parameter count.
fChangesAcc = true;
break;
case acCLASS:
case acSELFID:
fChangesAcc = true;
break;
case acPPREV:
fPutsOnStack = true;
break;
case acREST:
// Doesn't really affect anything
break;
case acLEA:
fEatsAcc = !!(bOpcode & LEA_ACC_AS_INDEX_MOD);
fChangesAcc = true;
break;
case acPTOA:
case acIPTOA:
case acDPTOA:
fChangesAcc = true;
break;
case acATOP:
fEatsAcc = true;
fChangesAcc = true;
// Not technically, but it leaves the value in the accumulator, so
// it's what people should look at.
break;
case acPTOS:
case acIPTOS:
case acDPTOS:
fPutsOnStack = true;
break;
case acSTOP:
cEatStack = 1;
break;
case acLOFSA:
fChangesAcc = true;
break;
case acLOFSS:
fPutsOnStack = true;
break;
default:
//sali -> store acc in local, indexed by acc
//ac is local4
ASSERT((bOpcode >= 64) && (bOpcode <= 127));
// TODO: use our defines/consts
if (_IsVOStoreOperation(bOpcode))
{
// Store operation
if (_IsVOPureStack(bOpcode))
{
cEatStack = 1;
}
else
{
if (_IsVOStack(bOpcode))
{
cEatStack = 1;
}
fEatsAcc = true;
fChangesAcc = true; // Not really, but leaves a valid thing in the acc.
}
}
else
{
// Load operation
if (_IsVOPureStack(bOpcode))
{
fPutsOnStack = true;
}
else
{
fChangesAcc = true;
}
}
if (_IsVOIndexed(bOpcode))
{
fEatsAcc = true; // index is in acc
}
break;
}
Consumption cons;
if (fEatsAcc)
{
cons.cAccConsume++;
}
if (fChangesAcc)
{
cons.cAccGenerate++;
}
cons.cStackConsume = cEatStack;
if (fPutsOnStack)
{
cons.cStackGenerate++;
}
return cons;
}
bool _IsJumpToPush(code_pos posJump, CodeNode *pNodePush)
{
return (posJump->get_branch_target() == pNodePush->GetCode());
}
// fwd decl
void _InstructionTreeHelper(CodeNode &parent, code_pos begin, code_pos &end);
//
// end -> next instruction before push tree defined by pNodePush
//
code_pos _CheckForTernary(code_pos end, code_pos begin, CodeNode *pNodePush)
{
code_pos endReturn = end;
if ((end->get_opcode() == acJMP) && _IsJumpToPush(end, pNodePush))
{
// Good
--end;
if (end != begin)
{
// Now we're looking for some kind of accumulator thing.
Consumption cons = _GetInstructionConsumption(*end);
if (cons.cAccGenerate == 1)
{
ASSERT(cons.cStackGenerate == 0);
std::auto_ptr<CodeNode> pFirstValue(new CodeNode(end));
_InstructionTreeHelper(*pFirstValue, begin, end);
// Now see if we have a bnt
if (end->get_opcode() == acBNT)
{
// This is it.
std::auto_ptr<CodeNode> pCondition(new CodeNode(end));
_InstructionTreeHelper(*pCondition, begin, end);
// Now we're going to do someting special. Take the original push,
// and add some crap to it.
ASSERT(pNodePush->GetChildCount() == 1); // Should just be the "second" value.
// push
// ldi (2)
//
// We want it to be:
// push
// bnt
// ???
// ldi (1)
// ldi (2)
pNodePush->AddChild(pFirstValue);
pNodePush->AddChild(pCondition);
// Update the end...
endReturn = end;
}
}
}
}
return endReturn;
}
// end is where you start looking.
void _InstructionTreeHelper(CodeNode &parent, code_pos begin, code_pos &end)
{
if (end != begin)
{
// 1) Ok, now check what this thing eats
// 2) Work backwards and add children until that hunger is satisfied.
Consumption consTemp = _GetInstructionConsumption(*end);
int cStackConsume = consTemp.cStackConsume;
int cAccConsume = consTemp.cAccConsume;
--end;
bool fHadAPush = false;
CodeNode *pNodePush = NULL;
bool fHadAJump = false;
bool fHadAccumulatorThing = false;
code_pos posAnomalyBegin = begin;;
// Now we try to bring the stack and acc balance to zero.
while((end != begin) && ((cStackConsume > 0) || (cAccConsume > 0)))
{
Consumption cons = _GetInstructionConsumption(*end);
// phil -> consider only doing acc stuff for the first thing..?
cStackConsume -= cons.cStackGenerate;
cAccConsume -= cons.cAccGenerate;
// Bound the acc consumption at 0... many things put stuff into the acc, but it doesn't mean it
// should be used.
cAccConsume = max(0, cAccConsume);
// On the other hand, the stack should never go below 0 if the code is good - we probably need to handle and bail
// once we've got the analysis down pat - phil
if (cStackConsume < 0)
{
// We have an issue here. This could arise in a case like this:
// ldi 5
// pushi 6
// push // uses the value in the accumulator, which is 5
//
// We need to ignore the pushi 6 then, but only for right here....
if (posAnomalyBegin == begin)
{
// This was our first anomoly. When we exit the function end should be set to this.
posAnomalyBegin = end;
}
cStackConsume = 0;
// ignore this instruction - we took note of it in posAnomaly;
--end;
// phil: We may need a better model... we're essentially skipping instructions. They should be put
// back into a queue to be used somewhere. Think of the following:
// class
// <switch statement stuff where each case puts something in the acc>
// toss
// push //-> we'll let the toss do its thing and become a switch statement, and accidentally
// // eat the class before the switch statement.
// Ok -> I guess this is unrelated. Do we need a special hack for this???
}
else
{
// ASSERT for now, though we'll need to deal with this:
ASSERT((cons.cStackConsume >= 0) && (cons.cAccConsume >= 0));
std::auto_ptr<CodeNode> pChild(new CodeNode(end));
// If it consumes anything, then call recursively
if (cons.cStackConsume || cons.cAccConsume)
{
_InstructionTreeHelper(*pChild, begin, end);
// phil HACK
if (pChild->GetCode()->get_opcode() == acPUSH)
{
end = _CheckForTernary(end, begin, pChild.get());
}
}
else
{
--end;
}
parent.AddChild(pChild);
}
}
if (posAnomalyBegin != begin)
{
// We had to skip some instructions - so reset end to point to where we
// had to start skipping.
end = posAnomalyBegin;
}
}
}
void _GenerateInstructionTree(CodeNode &root, code_pos begin, code_pos &end)
{
if (end != begin) // At least on instruction
{
_InstructionTreeHelper(root, begin, end);
}
}
// fwd decl
SyntaxNode *_CodeNodeToSyntaxNode(CodeNode &node, IDecompileLookups &lookups, CodeNode *pPreviousNode = NULL);
void _ApplySyntaxNodeToCodeNode(CodeNode &node, StatementsNode &statementsNode, IDecompileLookups &lookups, CodeNode *pPreviousNode = NULL);
void _ApplySyntaxNodeToCodeNode1(CodeNode &node, OneStatementNode &statementsNode, IDecompileLookups &lookups, CodeNode *pPreviousNode = NULL);
void _ApplySyntaxNodeToCodeNode2(CodeNode &node, TwoStatementNode &statementsNode, IDecompileLookups &lookups, CodeNode *pPreviousNode = NULL);
// Determines if a code_pos is within a CodeNode...
// TODO: really should just check if a CodeNode *starts* with a code_pos
bool _ScanCodeNodeForCodePos(CodeNode *pNode, code_pos pos)
{
bool fRet = (pNode->GetCode() == pos);
for (size_t i = 0; !fRet && (i < pNode->GetChildCount()); i++)
{
fRet = _ScanCodeNodeForCodePos(pNode->Child(i), pos);
}
return fRet;
}
//
// Scans a series of CodeNodes to find one that contains with code_pos.
// (note: should really be the one that starts with the code_pos, and by starts with
// we don't mean it's at the root of the hierarchy, but simply the first instruction
// that appears in code)
// If none are found, then it returns end.
// If one is found, it doesn't returns the codenode_it with the code_pos (because there
// may be no codenode_it), but the 'root' codenode_it.
//
codenode_it _FindCodeNodeWithCodePos(codenode_it begin, codenode_it end, code_pos pos)
{
while ((begin != end) && !_ScanCodeNodeForCodePos(*begin, pos))
{
++begin;
}
return begin;
}
//
// Defines the "shape" of code, such as if statements, switch statements, loops, etc....
//
class CodeShape
{
public:
virtual SingleStatementPtr DoIt(IDecompileLookups &lookups) = 0;
virtual void Print(std::ostream &os, int iIndent) const = 0;
};
// Fwd decl
void _PopulateCodeShapes(std::vector<CodeShape*> &shapes, codenode_it begin, codenode_it end, IDecompileLookups &lookups);
void _ProcessCodeNodesIntoStatements(StatementsNode &statements, codenode_it begin, codenode_it end, IDecompileLookups &lookups)
{
std::vector<CodeShape*> shapes;
_PopulateCodeShapes(shapes, begin, end, lookups);
std::vector<CodeShape*>::iterator it = shapes.begin();
while (it != shapes.end())
{
auto_ptr<SingleStatement> pStatement((*it)->DoIt(lookups));
statements.AddStatement(pStatement);
++it;
}
for_each(shapes.begin(), shapes.end(), delete_object());
}
class CodeTypeNormal : public CodeShape
{
public:
CodeTypeNormal(codenode_it code) : _code(code) {}
virtual SingleStatementPtr DoIt(IDecompileLookups &lookups)
{
auto_ptr<SingleStatement> pStatement(new SingleStatement);
pStatement->SetSyntaxNode(_CodeNodeToSyntaxNode(*(*_code), lookups));
return pStatement.release();
}
virtual void Print(std::ostream &os, int iIndent) const
{
(*_code)->Print(os, iIndent);
}
private:
codenode_it _code;
};
class CodeTypeSwitch : public CodeShape
{
public:
CodeTypeSwitch() : _fSwitch(false) { }
void SetSwitch(codenode_it switchPivot) { _switch = switchPivot; _fSwitch = true; }
void AddValue(codenode_it switchValue, codenode_it begin, codenode_it end)
{
switchvalue_t value = { switchValue, begin, end };
_values.push_back(value);
}
virtual SingleStatementPtr DoIt(IDecompileLookups &lookups)
{
auto_ptr<SingleStatement> pStatement(new SingleStatement);
if (_fSwitch)
{
auto_ptr<SwitchStatement> pSwitch(new SwitchStatement);
// The switch pivot:
_ApplySyntaxNodeToCodeNode1(*(*_switch), *pSwitch, lookups);
// The cases:
for (size_t i = 0; i < _values.size(); ++i)
{
auto_ptr<CaseStatement> pCase(new CaseStatement);
// Case value:
CodeNode *pNodeValue = *_values[i].value;
CodeNode *pNodeSomething = _IsolateCaseValue(*pNodeValue);
_ApplySyntaxNodeToCodeNode1(*pNodeSomething, *pCase, lookups);
// The code in the case:
_ProcessCodeNodesIntoStatements(*pCase, _values[i].begin, _values[i].end, lookups);
pSwitch->AddCase(pCase);
}
pStatement->SetSyntaxNode(pSwitch);
}
else
{
auto_ptr<Comment> pSwitch(new Comment);
pSwitch->SetName("ERROR");
pStatement->SetSyntaxNode(pSwitch);
}
return pStatement.release();
}
virtual void Print(std::ostream &os, int iIndent) const
{
os << _indent(iIndent) << "[switch]\n";
if (_fSwitch)
{
(*_switch)->Print(os, iIndent + 2);