-
Notifications
You must be signed in to change notification settings - Fork 2
/
CompiledScript.cpp
1678 lines (1544 loc) · 58.4 KB
/
CompiledScript.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 "CompiledScript.h"
#include "Decompiler.h"
#include "Compile\ScriptOM.h" // Just for DebugStringOut...
using namespace std;
using namespace sci;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
// Turn on/off decompiler, which is a work in progress.
#define DECOMPILE
#define STATE_CALCBRANCHES 0
#define STATE_OUTPUT 1
//#define TEST_OFFSET 0x000c // Pretend the script was loaded here.
#define TEST_OFFSET 0
//
// Returns the bounds of a function starting at codeStart, in terms of a CodeSection
// codeStart is an iterator into codePointersTo, which is a list of beginnings of functions, methods, etc...
//
bool _FindStartEndCode(set<WORD>::const_iterator codeStart, const set<WORD> &codePointersTO, const vector<CodeSection> &codeSections, CodeSection §ionOut)
{
sectionOut.begin = *codeStart;
// That was easy. Now find the CodeSection this is in.
CodeSection containingSection;
bool fFound = false;
for (size_t i = 0; !fFound && i < codeSections.size(); i++)
{
if ((sectionOut.begin >= codeSections[i].begin) && (sectionOut.begin < codeSections[i].end))
{
fFound = true;
containingSection = codeSections[i];
}
}
if (fFound)
{
++codeStart;
if (codeStart != codePointersTO.end())
{
sectionOut.end = min(*codeStart, containingSection.end);
}
else
{
sectionOut.end = containingSection.end;
}
}
return fFound;
}
void _GetVarType(ostream &out, BYTE bOpcode, WORD wIndex, IObjectFileScriptLookups *pOFLookups)
{
// This is a 0-127 opcode.
// Use the lowest two bits to determine the var type
switch (bOpcode & 0x03)
{
case 0:
// Get the global's name if possible
if (pOFLookups)
{
out << pOFLookups->ReverseLookupGlobalVariableName(wIndex);
}
else
{
out << "global" << setw(4) << setfill('0') << wIndex;
}
break;
case 1:
out << "local" << setw(4) << setfill('0') << wIndex;
break;
case 2:
out << "temp" << setw(4) << setfill('0') << wIndex;
break;
case 3:
if (wIndex == 0)
{
// parameter 0 is the count of parameters.
out << "paramTotal";
}
else
{
out << "param" << setw(4) << setfill('0') << wIndex;
}
break;
}
}
std::string _GetProcNameFromScriptOffset(WORD wOffset)
{
std::stringstream ss;
ss << "localproc_" << wOffset;
return ss.str();
}
sci::istream _GetScriptData(int iScript)
{
sci::istream byteStreamRet;
ResourceEnumerator *pEnum;
if (SUCCEEDED(theApp.GetResourceMap().CreateEnumerator(NULL, ResourceTypeFlagScript, &pEnum)))
{
ResourceBlob *pData;
bool fFound = false;
while (!fFound && (S_OK == pEnum->Next(&pData)))
{
if (pData->GetNumber() == iScript)
{
byteStreamRet = pData->GetReadStream();
fFound = true;
// The following code was for modifying the script to fake loading at a different offset
// (to simulate where it would be loaded during the game)
/*
fFound = true;
ASSERT(pStream == NULL);
sci::istream byteStream = pData->GetReadStream();
WORD wType, wSectionSize;
bool fFoundReloc = false;
while (!fFoundReloc && byteStream.good())
{
byteStream >> wType;
byteStream >> wSectionSize;
if (byteStream.good())
{
if (wType == 8)
{
fFoundReloc = true;
break;
}
else if (wType == 0)
{
break;
}
else
{
byteStream.skip(wSectionSize - 4); // Go to next section
}
}
}
if (fFoundReloc)
{
if ((wSectionSize - 4) > 0)
{
byteStream >> wNumPointers;
for (WORD i = 0; byteStream.good() && (i < wNumPointers); i++)
{
WORD w;
byteStream >> w;
// Modify the address at that location:
}
}
}*/
}
delete pData;
}
delete pEnum;
}
return byteStreamRet;
}
BOOL CompiledScript::Load(int iScriptNumber)
{
_wScript = (WORD)iScriptNumber;
BOOL fRet = FALSE;
sci::istream byteStream(_GetScriptData(iScriptNumber));
fRet = Load(byteStream);
return fRet;
}
bool CompiledScript::_IsInCodeSection(WORD wOffset)
{
for (size_t i = 0; i < _codeSections.size(); i++)
{
if ((wOffset >= _codeSections[i].begin) && (wOffset < _codeSections[i].end))
{
return true;
}
}
return false;
}
bool CompiledScript::Load(sci::istream &byteStream)
{
bool fRet = true;
// Make a copy of everything
_scriptResource.resize(byteStream.GetDataSize());
byteStream.read_data(&_scriptResource[0], byteStream.GetDataSize());
// Then go back to the beginning
byteStream.seekg(0);
// Note: KQ4 has a different script resource format (it's interpreter is an older SCI0)
// There is a WORD at the beginning, but there are more differences than that too.
while (fRet)
{
DWORD dwSavePos = byteStream.tellg();
// Read the type and size.
WORD wType;
WORD wSectionSize;
byteStream >> wType;
if (wType != 0)
{
byteStream >> wSectionSize;
fRet = byteStream.good() && (wSectionSize >= 4);
if (fRet)
{
switch (wType)
{
case 1:
{
// instance
CompiledObjectBase *pObject = new CompiledObjectBase;
WORD wInstanceOffsetTO;
fRet = pObject->Create(byteStream, FALSE, &wInstanceOffsetTO);
if (fRet)
{
_objectsOffsetTO.push_back(wInstanceOffsetTO);
_objects.push_back(pObject);
}
else
{
delete pObject;
}
}
break;
case 2:
{
WORD wCodeLength = wSectionSize - 4;
WORD wCodePosTO = static_cast<WORD>(byteStream.tellg());
byteStream.seekg(wCodeLength); // Skip this section.
CodeSection section = { wCodePosTO, wCodePosTO + wCodeLength };
_codeSections.push_back(section);
}
break;
case 3:
{
// Synonym word lists.
// WORD A - wordgroup,
// WORD B - wordgroup, replacement for a
WORD wNumPairs = ((wSectionSize - 4) / 4);
for (WORD i = 0; fRet && i < wNumPairs; i++)
{
WORD wA;
byteStream >> wA;
WORD wB;
byteStream >> wB;
_synonyms[wA] = wB;
fRet = byteStream.good();
}
}
break;
case 4:
{
// Said specs
fRet = _ReadSaids(byteStream, wSectionSize - 4);
}
break;
case 5:
{
// Strings
fRet = _ReadStrings(byteStream, wSectionSize - 4);
}
break;
case 6:
{
// class
CompiledObjectBase *pObject = new CompiledObjectBase;
WORD wClassOffset;
fRet = pObject->Create(byteStream, TRUE, &wClassOffset);
if (fRet)
{
_objectsOffsetTO.push_back(wClassOffset);
_objects.push_back(pObject);
}
else
{
delete pObject;
}
}
break;
case 7:
{
// Just what are the exports table? Why are there entries in scripts that have no exports???
// Because they have a room, which is a public instance. Unclear what this is supposed to point
// to though... it appears to point to the species selector.
// (also: magic entry point for script 0, entry 0, the play method.
fRet = _ReadExports(byteStream);
}
break;
case 8:
{
// Relocation table.
// This is a list of script-relative pointers to pointers in the script. These are how the
// interpreter tells what it needs to adjust when loading a script.
// This begins with a WORD that indicates how many pointers there are here.
// Brian's compiler seems to use these for the strings, but not for other things like Saids.
// Why would they be needed for strings? It seems like they are only used for the name
// selectors?
// But the main script has 57 of these entries, but only 42 strings. So clearly they are
// used for more than just strings.
// If I compile main, I get 34 offset strings (42 - 8 that aren't object names) and 23 offset properties,
// which were the said strings used in properties.
// So it seems like it's used for object names, and things that are property values (said, string and var)
// That means you can assign local variables to properties. e.g. "x @myLocalVar"
// (Doesn't work with globals though.)
// I guess everywhere else we can use relative offsets!
}
break;
case 9:
{
_fPreloadText = TRUE;
}
break;
case 10:
{
// Local variables.
// Just a series of WORDs. The notion of arrays, etc... is not encoded in the resource.
// That's all just in source code. Although arrays can kind of be infered from which ones
// are accessed in the script.
WORD wNumVars = ((wSectionSize - 4) / 2);
for (WORD i = 0; fRet && i < wNumVars; i++)
{
WORD w;
byteStream >> w;
fRet = byteStream.good();
_localVars.push_back(w);
}
}
break;
default:
// Nada.
break;
}
}
}
if (wType == 0)
{
break; // Done
}
if (fRet)
{
ASSERT(wSectionSize > 0); // else we'll never get anywhere.
if (wSectionSize > 0)
{
byteStream.seekg(dwSavePos + wSectionSize);
fRet = byteStream.good();
}
}
}
return fRet;
}
// Pretend the code has been loaded at an address other than 0x0000
WORD _GetTestStreamPosition(sci::istream *pStream)
{
return (WORD)(pStream->GetPosition()) + TEST_OFFSET;
}
bool CompiledObjectBase::Create(sci::istream &stream, BOOL fClass, WORD *pwOffset)
{
*pwOffset = static_cast<WORD>(stream.tellg());
_fInstance = !fClass;
WORD wMagic;
stream >> wMagic; // ASSERT(wMagic == 0x1234);
if (wMagic != 0x1234)
{
return false; // We'll hit this when loading KQ4 for example, which uses a different format
}
if (stream.good())
{
_wPosInResource = static_cast<WORD>(stream.tellg());
WORD wLocalVarOffset;
stream >> wLocalVarOffset;
WORD wFunctionSelectorOffset;
stream >> wFunctionSelectorOffset;
WORD wNumVarSelectors;
stream >> wNumVarSelectors;
ASSERT(wNumVarSelectors >= 3); // Really 4, but iceman only has 3
if (stream.good())
{
WORD wNumVarValuesLeft = wNumVarSelectors;
while (stream.good() && wNumVarValuesLeft)
{
WORD wValue;
stream >> wValue;
if (stream.good())
{
_propertyValues.push_back(wValue);
}
wNumVarValuesLeft--;
}
}
WORD wName = 0;
if (wNumVarSelectors >= 3)
{
_wSpecies = _propertyValues[0];
_wSuperClass = _propertyValues[1];
_wInfo = _propertyValues[2];
if (wNumVarSelectors >= 4)
{
wName = _propertyValues[3];
}
}
// Now read their selector IDs - but only if this is a class.
// Instances don't need this, since all the selector IDs are defined by its class.
if (stream.good() && fClass)
{
// If this is a class, it's now followed by selector IDs, matching the selectors.
for (INT_PTR i = 0; stream.good() && i < (INT_PTR)wNumVarSelectors; i++)
{
WORD wSelectorID;
stream >> wSelectorID;
if (stream.good())
{
_propertySelectors.push_back(wSelectorID);
}
}
}
// Now their function selectors, for both instances and classes.
WORD wNumFunctionSelectors = 0;
if (stream.good())
{
// Read function selectors.
stream >> wNumFunctionSelectors;
WORD wNumFunctionSelectorsLeft = wNumFunctionSelectors;
//
// The spec here is incorrect.
// http://freesci.linuxgames.com/scihtml/c2890.html#AEN2894
// For classes, it describes the function code pointers coming before the selectors for the functions.
// But the selectors come before for both classes and instances.
//
while(stream.good() && wNumFunctionSelectorsLeft)
{
WORD wSelectorID;
stream >> wSelectorID;
if (stream.good())
{
_functionSelectors.push_back(wSelectorID);
}
wNumFunctionSelectorsLeft--;
}
}
// Now the method code pointers.
WORD wZero;
stream >> wZero;
if (stream.good())
{
ASSERT(wZero == 0); // There is supposed to be a zero here.
while (stream.good() && wNumFunctionSelectors)
{
WORD wPtr;
stream >> wPtr;
if (stream.good())
{
// These are supposed to be offsets to within the script resource, so they
// had better be smaller!
ASSERT(stream.GetDataSize() > wPtr);
_functionOffsetsTO.push_back(wPtr + TEST_OFFSET);
}
wNumFunctionSelectors--;
}
}
if (stream.good() && (wName != 0))
{
// Retrieve the name of the object. wName is a pointer.
DWORD dwSavePos = stream.tellg();
stream.seekg(wName);
stream >> _strName;
// Restore
stream.seekg(dwSavePos);
}
// The rest of the stuff we don't care about!
}
return stream.good();
}
bool CompiledScript::_ReadExports(sci::istream &stream)
{
// These aren't really interesting actually.
WORD wNumExports;
stream >> wNumExports;
if (stream.good())
{
for (WORD i = 0; stream.good() && i < wNumExports; i++)
{
WORD wOffset;
stream >> wOffset;
if (stream.good())
{
_exportsTO.push_back(wOffset + TEST_OFFSET);
}
}
}
return stream.good();
}
bool CompiledScript::_ReadSaids(sci::istream &stream, WORD wDataSize)
{
// A single Said spec consists of wordgroups (0x0000-0x0fff) and BYTE tokens (0xf0-0xf9),
// terminated by 0xff. I don't think there is any count of them. But there is a count of
// the total length of all of them of course.
// We pass the offset of this thing to callk Said. This would be a program-counter-relative
// offset.
DWORD dwMaxPos = stream.tellg() + wDataSize;
while (stream.good() && (stream.tellg() < (dwMaxPos - 1))) // -1 since we need at least a little more data to read...
{
// Store the actual position in the stream (this is how other parts of the script refer to it).
WORD wBeginingOfSaid = static_cast<WORD>(stream.tellg());
vector<WORD> saidSequence;
bool fDone = false;
do
{
BYTE b;
stream >> b;
//fRet = pStream->ReadByte(&b);
if (stream.good())
{
fDone = (b == 0xff);
if (!fDone)
{
if (b >= 0xf0)
{
// It's a operator.
saidSequence.push_back((WORD)b);
}
else
{
// It's a word group.
BYTE b2;
stream >> b2;
//fRet = pStream->ReadByte(&b2);
if (stream.good())
{
saidSequence.push_back((((WORD)b) << 8) | b2);
}
}
}
}
} while (stream.good() && !fDone);
if (stream.good())
{
_saidsOffset.push_back(wBeginingOfSaid);
_saids.push_back(saidSequence);
}
}
// Just return TRUE. Some of the code generated by brian's compiler seems to have an addition byte
// in the overall length, so 0xff doesn't correspond to end the of the data stream (presumably so it ends up on a WORD boundary)
return true;
}
bool CompiledScript::_ReadStrings(sci::istream &stream, WORD wDataSize)
{
// I have a feeling these may map to objects, which would be great for us.
// Look up a string, and then its index corresponds to an object?
DWORD dwMaxPos = stream.tellg() + wDataSize;
while (stream.good() && (stream.tellg() < dwMaxPos))
{
string str;
DWORD dwOffset = stream.tellg();
stream >> str;
if (stream.good())
{
ASSERT(dwOffset <= 0xffff);
_stringsOffset.push_back(static_cast<WORD>(dwOffset));
_strings.push_back(str);
}
}
return stream.good();
}
//
// Calculate the offset wRelOffset from wHere, where wHere is the current location
// of the last operand in an instruction. 1 or 2 will be added to it prior to
// calculating the offset.
//
WORD CalcOffset(WORD wOperandStart, WORD wRelOffset, bool bByte, BYTE bRawOpcode)
{
// Move to the pc post instruction.
WORD wResult = wOperandStart + OpArgs[bRawOpcode];
if (bByte)
{
if (wRelOffset >= 0x0080)
{
// It was a negative number, expressed in a byte.
// We need to "sign extend" this thing.
wRelOffset |= 0xff00;
}
wResult += wRelOffset;
}
else
{
wResult += wRelOffset; // Should just work
}
return wResult;
}
int GetOperandSize(BYTE bOpcode, OperandType operandType)
{
int cIncr = 0;
switch (operandType)
{
case otEMPTY:
cIncr = 0;
break;
case otVAR:
case otPVAR:
case otCLASS:
case otPROP:
case otSTRING:
case otSAID:
case otKERNEL:
case otLABEL:
case otPUBPROC:
case otINT:
case otOFFS:
cIncr = (bOpcode & 1) ? 1 : 2;
break;
case otINT16:
cIncr = 2;
break;
case otINT8:
cIncr = 1;
break;
}
return cIncr;
}
void _Disassemble(ostream &out, ICompiledScriptLookups *pLookups, IObjectFileScriptLookups *pOFLookups, ICompiledScriptSpecificLookups *pScriptThings, ILookupPropertyName *pPropertyNames, const BYTE *pBegin, const BYTE *pEnd, WORD wBaseOffset)
{
try
{
vector<WORD> codeLabelOffsets; // Keep track of places that are branched to.
for (int state = 0; state < 2; state++)
{
const BYTE *pCur = pBegin;
WORD wOffset = wBaseOffset;
int iCurLabelOffset = 0; // for STATE_CALCBRANCHES
while (pCur < pEnd) // Possibility of read AVs here, but we catch exceptions.
{
BYTE bRawOpcode = *pCur;
BYTE bOpcode = bRawOpcode >> 1;
ASSERT(bOpcode < 128);
const char *pszOpcode = OpcodeNames[bOpcode];
bool bByte = (*pCur) & 1; // Is this a "byte" opcode or a "word" opcode.
bool fDone = false;
char szBuf[50];
size_t cchBufLimit = 30;
ASSERT(cchBufLimit < ARRAYSIZE(szBuf));
if (state == STATE_OUTPUT)
{
if (codeLabelOffsets.size() > 0 && (codeLabelOffsets[iCurLabelOffset] == wOffset))
{
// We're at label.
out << endl << " code_" << setw(4) << setfill('0') << wOffset << endl;
iCurLabelOffset++;
}
out << " " << setw(4) << setfill('0') << wOffset << ":";
int indent = 22;
const BYTE *pCurTemp = pCur; // skip past opcode
for (int i = -1; i < 3; i++)
{
int cIncr = (i == -1) ? 1 : GetOperandSize(bRawOpcode, OpArgTypes[bOpcode][i]);
if (cIncr == 0)
{
break;
}
else
{
WORD wOperandTemp = (cIncr == 2) ? *((WORD*)pCurTemp) : *pCurTemp;
out << setw((cIncr == 1) ? 2 : 4);
out << setfill('0') << wOperandTemp << " ";
pCurTemp += cIncr;
indent -= (cIncr == 1) ? 3 : 5; // How many chars were written...
}
}
ASSERT(indent > 0);
out << setw(indent) << setfill(' ') << pszOpcode << " "; // Indent x chars, and print opcode
}
pCur++; // skip past opcode
wOffset++;
WORD wOperandStart = wOffset;
if (state == STATE_CALCBRANCHES)
{
// Keep track of the targets of branch instructions
if ((bOpcode == acBNT) || (bOpcode == acBT) || (bOpcode == acJMP))
{
// This is a branch instruction. Figure out the offset.
// The relative offset is either a byte or word, and is calculated post instruction
// (hence we add 1 or 2 to our calculation)
codeLabelOffsets.push_back(CalcOffset(wOperandStart, (bByte ? ((WORD)*pCur) : (*((WORD*)pCur))), bByte, bRawOpcode));
}
}
WORD wOperands[3];
for (int i = 0; !fDone && i < 3; i++)
{
szBuf[0] = 0;
int cIncr = GetOperandSize(bRawOpcode, OpArgTypes[bOpcode][i]);
if (cIncr == 0)
{
break;
}
if (state == STATE_OUTPUT)
{
wOperands[i] = (cIncr == 2) ? *((WORD*)pCur) : *pCur;
switch (OpArgTypes[bOpcode][i])
{
case otINT:
case otINT16:
case otINT8:
out << wOperands[i];
break;
case otKERNEL:
out << pLookups->LookupKernelName(wOperands[i]);
break;
case otPUBPROC:
out << "procedure_" << setw(4) << setfill('0') << wOperands[i];
break;
case otSAID:
out << "said_" << setw(4) << setfill('0') << wOperands[i];
break;
case otOFFS:
// This is a bit of a hack here. We're making the assumption that a otOFFS parameter
// is the one and only parameter for this opcode. CalcOffset makes this assumption
// in order to calculate the offset.
ASSERT(OpArgTypes[bOpcode][i+1] == otEMPTY);
// Kind of hokey, we reassign the operand here.
wOperands[i] = CalcOffset(wOperandStart, wOperands[i], bByte, bRawOpcode);
out << "$" << setw(4) << setfill('0') << wOperands[i];
break;
case otEMPTY:
break;
case otPROP:
// This value is an offset from the beginning of this object's species
// So, get the species, and then divide this value by 2, and use it as an index into its
// selector thang.
//
if (pPropertyNames)
{
out << pPropertyNames->LookupPropertyName(pLookups, wOperands[i]);
}
else
{
out << "**ENCOUNTERED PROPERTY OPCODE IN NON-OBJECT CODE**";
}
break;
case otCLASS:
out << pLookups->LookupClassName(wOperands[i]);
break;
case otVAR:
_GetVarType(out, bOpcode, wOperands[i], pOFLookups);
break;
case otLABEL:
// This is a relative position from the post pc
out << ((bOpcode == acCALL) ? "proc" : "code") << "_" << setw(4) << setfill('0') << CalcOffset(wOperandStart, wOperands[i], bByte, bRawOpcode);
break;
default:
out << "$" << setw(4) << setfill('0') << wOperands[i];
break;
}
out << " ";
}
pCur += cIncr;
wOffset += cIncr;
}
if (state == STATE_OUTPUT)
{
// Time for comments (for some instructions)
szBuf[0] = 0;
switch (bOpcode)
{
case acLINK:
out << "// (var $" << wOperands[0] << ")";
break;
case acLOFSS:
case acLOFSA:
// This is an offset... it could be an interesting one, like a string or said.
ICompiledScriptSpecificLookups::ObjectType type;
out << "// " << pScriptThings->LookupObjectName(wOperands[0], type);
break;
case acPUSHI:
out << "// $" << wOperands[0] << " " << pLookups->LookupSelectorName(wOperands[0]);
break;
// could do it for push0, push1, etc..., but it's just clutter, and rarely the intention.
case acCALLE:
case acCALLB:
// Try to get the public export name.
if (pOFLookups)
{
WORD wScript;
WORD wIndex;
if (acCALLB == bOpcode)
{
wScript = 0;
wIndex = wOperands[0];
}
else
{
wScript = wOperands[0];
wIndex = wOperands[1];
}
out << "// " << pOFLookups->ReverseLookupPublicExportName(wScript, wIndex) << " ";
}
break;
}
out << endl;
switch (bOpcode)
{
case acSEND:
case acCALL:
case acCALLB:
case acCALLE:
case acCALLK:
case acSELF:
case acSUPER:
// Add another carriage return after these instructions
out << endl;
break;
}
}
}
if (state == STATE_CALCBRANCHES)
{
sort(codeLabelOffsets.begin(), codeLabelOffsets.end());
}
}
}
catch (...)
{
// In case we read more than there was.
theApp.LogInfo("Error while disassembling script.");
}
}
//
// Scan for direct access to local variables, to find out if they are arrays or not.
//
/*
void _ScanForLocalVarUsage(BYTE *rgRawCode, WORD wCodeBase, WORD wCodeLength)
{
// REVIEW: coalesce this code with _FindInternalCalls
WORD wCurrentOffset = wCodeBase;
BYTE *pCur = rgRawCode;
BYTE *pEnd = pCur + wCodeLength;
while (pCur < pEnd)
{
WORD wRelOffset;
BYTE bRawOpcode = *pCur;
BYTE bOpcode = bRawOpcode >> 1;
bool bByte = (bRawOpcode & 1);
pCur++;
wCurrentOffset++;
if (OpArgTypes[bOpcode][0] == otVAR)
{
if ((bOpcode & 0x03) == 1)
{
// This was a local var instruction
WORD wIndex = (bByte ? (WORD)*pCur : *((WORD*)pCur));
}
}
// Skip past to the next instruction
pCur += OpArgs[bRawOpcode];
wCurrentOffset += OpArgs[bRawOpcode];
}
}*/
//
// Scan all the code in the script, looking for call instructions
//
set<WORD> CompiledScript::_FindInternalCallsTO()
{
set<WORD> wOffsets;
for (size_t i = 0; i < _codeSections.size(); i++)
{
WORD wCurrentOffsetTO = _codeSections[i].begin;
BYTE *pCur = &_scriptResource[wCurrentOffsetTO];
if (pCur)
{
BYTE *pEnd = &_scriptResource[_codeSections[i].end];
while (pCur < pEnd)
{
WORD wRelOffset;
BYTE bRawOpcode = *pCur;
bool bByte = (bRawOpcode & 1);
pCur++;
wCurrentOffsetTO++;
if ((bRawOpcode >> 1) == acCALL)
{
// This is one. The first operand is a word or byte
wRelOffset = (bByte ? ((WORD)*pCur) : (WORD)*pCur + (((WORD)*(pCur + 1)) << 8));
//wOffsets.push_back(CalcOffset(wCurrentOffset, wRelOffset, bByte, bRawOpcode));
wOffsets.insert(wOffsets.end(), CalcOffset(wCurrentOffsetTO, wRelOffset, bByte, bRawOpcode));
}
// Skip past to the next instruction
pCur += OpArgs[bRawOpcode];
wCurrentOffsetTO += OpArgs[bRawOpcode];
}
}
}
return wOffsets;
}
Script *CompiledScript::Decompile(IDecompileLookups &lookups, ILookupNames *pWords)
{
auto_ptr<Script> pScript(new Script);
// Get readable strings for them
for (size_t i = 0; i < _saids.size(); i++)
{
_saidStrings.push_back(_SaidSequenceToString(_saids[i], pWords));
}
ASSERT(_saidStrings.size() == _saidsOffset.size());
// Synonyms
if (_synonyms.size() > 0)
{
map<WORD, WORD>::iterator it = _synonyms.begin();
while (it != _synonyms.end())
{
auto_ptr<Synonym> pSynonym(new Synonym);
ICompiledScriptSpecificLookups::ObjectType type;
pSynonym->MainWord = lookups.LookupScriptThing(it->first, type);
pSynonym->Replacement = lookups.LookupScriptThing(it->second, type);
pScript->AddSynonym(pSynonym);
++it;
}
}
// Local variables
for (size_t i = 0; i < _localVars.size(); i++)
{
auto_ptr<VariableDecl> pVar(new VariableDecl);
pVar->SetDataType("var"); // For now...
std::stringstream ss;
ss << "local_" << setw(4) << setfill('0') << (int)i;
pVar->SetName(ss.str());
pVar->SetSize(1);
PropertyValue value;
value.SetValue(_localVars[i]);
pVar->AddSimpleInitializer(value);
pScript->AddVariable(pVar);
}
// Now its time for code.
// Make an index of code pointers by looking at the object methods
set<WORD> codePointersTO;
for (size_t i = 0; i < _objects.size(); i++)
{
vector<WORD> &methodPointersTO = _objects[i]->GetMethodCodePointersTO();
codePointersTO.insert(methodPointersTO.begin(), methodPointersTO.end());
}
// and the exports