forked from cleolibrary/CLEO4
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCCustomOpcodeSystem.cpp
More file actions
1253 lines (1094 loc) · 43.2 KB
/
CCustomOpcodeSystem.cpp
File metadata and controls
1253 lines (1094 loc) · 43.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "stdafx.h"
#include "CleoBase.h"
#include "CGameVersionManager.h"
#include "CCustomOpcodeSystem.h"
#include "ScmFunction.h"
namespace CLEO
{
CRunningScript* CCustomOpcodeSystem::lastScript = nullptr;
WORD CCustomOpcodeSystem::lastOpcode = 0xFFFF;
WORD* CCustomOpcodeSystem::lastOpcodePtr = nullptr;
WORD CCustomOpcodeSystem::lastCustomOpcode = 0;
std::string CCustomOpcodeSystem::lastErrorMsg = {};
WORD CCustomOpcodeSystem::prevOpcode = 0xFFFF;
BYTE CCustomOpcodeSystem::handledParamCount = 0;
OpcodeResult CCustomOpcodeSystem::OnOpcodeFinished(CRunningScript* thread, OpcodeResult result)
{
// execute registered callbacks
OpcodeResult callbackResult = OR_NONE;
for (void* func : CleoInstance.GetCallbacks(eCallbackId::ScriptOpcodeProcessAfter))
{
typedef OpcodeResult WINAPI callback(CRunningScript*, DWORD, OpcodeResult);
auto res = ((callback*)func)(thread, CCustomOpcodeSystem::lastOpcode, result);
callbackResult = std::max(res, callbackResult); // store result with highest value from all callbacks
}
thread->bIsProcessing = false; // opcode processing ended
return (callbackResult != OR_NONE) ? callbackResult : result;
}
// opcode handler for custom opcodes
OpcodeResult __fastcall CCustomOpcodeSystem::customOpcodeHandler(CRunningScript* thread, int dummy, WORD opcode)
{
prevOpcode = (thread != lastScript) ? 0xFFFF : lastOpcode;
lastScript = thread;
lastOpcode = opcode;
lastOpcodePtr = (WORD*)thread->GetBytePointer() - 1; // rewind to the opcode start
handledParamCount = 0;
// check if last opcode ended correctly
if (thread->bIsProcessing && !IsLegacyScript(thread))
{
auto result = TrySuspendScript(
thread, true,
"Unexpected opcode [%04X], likely caused by an error that was silently ignored (e.g. in SAMP)", opcode
);
return OnOpcodeFinished(thread, result);
}
thread->bIsProcessing = true; // opcode processing started
// prevent past code execution
if (thread->IsCustom() && !IsLegacyScript(thread))
{
auto cs = (CCustomScript*)thread;
auto endPos = cs->GetBasePointer() + cs->GetCodeSize();
if ((BYTE*)lastOpcodePtr == endPos ||
(BYTE*)lastOpcodePtr == (endPos - 1)) // consider script can end with incomplete opcode
{
auto result = TrySuspendScript(
thread, true,
"Code execution reached end of script. This may be caused by missing TERMINATE_THIS_SCRIPT"
);
return OnOpcodeFinished(thread, result);
}
}
// execute registered callbacks
for (void* func : CleoInstance.GetCallbacks(eCallbackId::ScriptOpcodeProcessBefore))
{
typedef OpcodeResult WINAPI callback(CRunningScript*, DWORD);
if (auto result = ((callback*)func)(thread, opcode); result != OR_NONE)
{
return OnOpcodeFinished(thread, result); // command processed by callback, done
}
}
if (opcode > Opcode_Max)
{
auto result = TrySuspendScript(thread, false, "Opcode [%04X] out of supported range!", opcode);
return OnOpcodeFinished(thread, result);
}
CustomOpcodeHandler handler = customOpcodeProc[opcode];
if (handler != nullptr)
{
lastCustomOpcode = opcode;
return OnOpcodeFinished(thread, handler(thread));
}
// Not registered as custom opcode. Call game's original handler
if (auto result = CallNativeOpcode(thread, opcode); result != OR_ERROR)
{
return OnOpcodeFinished(thread, result);
}
auto extensionMsg = CleoInstance.OpcodeInfoDb.GetExtensionMissingMessage(opcode);
if (!extensionMsg.empty())
{
extensionMsg = " " + extensionMsg;
}
auto result = TrySuspendScript(thread, false, "Opcode [%04X] not found!%s", opcode, extensionMsg.c_str());
return OnOpcodeFinished(thread, result);
}
void CCustomOpcodeSystem::Inject(CCodeInjector& inj)
{
TRACE("Injecting CustomOpcodeSystem...");
CGameVersionManager& gvm = CleoInstance.VersionManager;
// replace all handlers in original table
// store original opcode handlers for later use
auto handlersTable = (OpcodeHandler*)::CRunningScript::CommandHandlerTable;
for (size_t i = 0; i < OriginalOpcodeHandlersCount; i++)
{
originalOpcodeHandlers[i] = handlersTable[i];
handlersTable[i] = (OpcodeHandler)customOpcodeHandler;
}
// initialize and apply new handlers table
for (size_t i = 0; i < CustomOpcodeHandlersCount; i++)
{
customOpcodeHandlers[i] = (OpcodeHandler)customOpcodeHandler;
}
inj.MemoryWrite(gvm.TranslateMemoryAddress(MA_OPCODE_HANDLER_REF_1), &customOpcodeHandlers);
inj.MemoryWrite(gvm.TranslateMemoryAddress(MA_OPCODE_HANDLER_REF_2), &customOpcodeHandlers);
}
void CCustomOpcodeSystem::Init()
{
if (initialized)
{
return;
}
TRACE(""); // separator
TRACE("Initializing CLEO core opcodes...");
CLEO_RegisterOpcode(0x004E, opcode_004E);
CLEO_RegisterOpcode(0x0050, opcode_0050);
CLEO_RegisterOpcode(0x0051, opcode_0051);
CLEO_RegisterOpcode(0x0417, opcode_0417);
CLEO_RegisterOpcode(0x0A92, opcode_0A92);
CLEO_RegisterOpcode(0x0A93, opcode_0A93);
CLEO_RegisterOpcode(0x0A94, opcode_0A94);
CLEO_RegisterOpcode(0x0A95, opcode_0A95);
CLEO_RegisterOpcode(0x0AA0, opcode_0AA0);
CLEO_RegisterOpcode(0x0AA1, opcode_0AA1);
CLEO_RegisterOpcode(0x0AA9, opcode_0AA9);
CLEO_RegisterOpcode(0x0AB1, opcode_0AB1);
CLEO_RegisterOpcode(0x0AB2, opcode_0AB2);
CLEO_RegisterOpcode(0x0AB3, opcode_0AB3);
CLEO_RegisterOpcode(0x0AB4, opcode_0AB4);
CLEO_RegisterOpcode(0x0DD5, opcode_0DD5); // get_platform
CLEO_RegisterOpcode(0x2000, opcode_2000); // get_cleo_arg_count
// 2001 free
CLEO_RegisterOpcode(0x2002, opcode_2002); // cleo_return_with
CLEO_RegisterOpcode(0x2003, opcode_2003); // cleo_return_fail
initialized = true;
}
void CCustomOpcodeSystem::GameEnd()
{
TRACE("Cleaning up script data...");
CleoInstance.CallCallbacks(eCallbackId::ScriptsFinalize);
// clean up after opcode_0AB1
ScmFunction::Clear();
}
CCustomOpcodeSystem::~CCustomOpcodeSystem()
{
TRACE(""); // separator
TRACE("Custom Opcode System finalized:");
TRACE(" Last opcode executed: %04X", lastOpcode);
TRACE(" Previous opcode executed: %04X", prevOpcode);
}
CCustomOpcodeSystem::OpcodeHandler CCustomOpcodeSystem::originalOpcodeHandlers[OriginalOpcodeHandlersCount];
CCustomOpcodeSystem::OpcodeHandler CCustomOpcodeSystem::customOpcodeHandlers[CustomOpcodeHandlersCount];
CustomOpcodeHandler CCustomOpcodeSystem::customOpcodeProc[Opcode_Max + 1];
bool CCustomOpcodeSystem::RegisterOpcode(WORD opcode, CustomOpcodeHandler callback)
{
if (opcode > Opcode_Max)
{
SHOW_ERROR("Can not register [%04X] opcode! Out of supported range.", opcode);
return false;
}
CustomOpcodeHandler& dst = customOpcodeProc[opcode];
if (*dst != nullptr)
{
LOG_WARNING(0, "Opcode [%04X] already registered! Replacing...", opcode);
}
dst = callback;
TRACE("Opcode [%04X] registered", opcode);
return true;
}
OpcodeResult _CallNativeOpcode(CRunningScript* thread, void* handler, DWORD opcode)
{
// wrapped in separate function as otherwise some problems occur in
// debug builds
OpcodeResult result;
_asm
{
push opcode
mov ecx, thread
call handler
mov result, al
}
return result;
}
OpcodeResult CCustomOpcodeSystem::CallNativeOpcode(CRunningScript* thread, WORD opcode)
{
if (opcode > Opcode_Max_Native)
{
return OR_ERROR;
}
size_t tableIdx = opcode / Opcode_Table_Size;
return _CallNativeOpcode(thread, originalOpcodeHandlers[tableIdx], opcode);
}
const char* ReadStringParam(CRunningScript* thread, char* buff, int buffSize)
{
if (buffSize > 0)
{
buff[buffSize - 1] = '\0'; // buffer always terminated
}
return GetScriptStringParam(thread, 0, buff, buffSize - 1); // minus terminator
}
// write output\result string parameter
bool WriteStringParam(CRunningScript* thread, const char* str)
{
auto target = GetStringParamWriteBuffer(thread);
return WriteStringParam(target, str);
}
bool WriteStringParam(const StringParamBufferInfo& target, const char* str)
{
CCustomOpcodeSystem::lastErrorMsg.clear();
if (str != nullptr && (size_t)str <= MinValidAddress)
{
CCustomOpcodeSystem::lastErrorMsg = StringPrintf("Writing string from invalid '0x%X' pointer", target.data);
return false;
}
if ((size_t)target.data <= MinValidAddress)
{
CCustomOpcodeSystem::lastErrorMsg =
StringPrintf("Writing string into invalid '0x%X' pointer argument", target.data);
return false;
}
if (target.size == 0)
{
return false;
}
bool addTerminator = target.needTerminator;
size_t buffLen = target.size - addTerminator;
size_t length = str == nullptr ? 0 : strlen(str);
if (buffLen > length)
{
addTerminator = true; // there is space left for terminator
}
length = std::min(length, buffLen);
if (length > 0)
{
std::memcpy(target.data, str, length);
}
if (addTerminator)
{
target.data[length] = '\0';
}
return true;
}
StringParamBufferInfo GetStringParamWriteBuffer(CRunningScript* thread)
{
StringParamBufferInfo result;
CCustomOpcodeSystem::lastErrorMsg.clear();
auto paramType = thread->PeekDataType();
if (IsImmInteger(paramType) || IsVariable(paramType))
{
// address to output buffer
CScriptEngine::GetScriptParams(thread, 1);
if (opcodeParams[0].dwParam <= MinValidAddress)
{
CCustomOpcodeSystem::lastErrorMsg =
StringPrintf("Writing string into invalid '0x%X' pointer argument", opcodeParams[0].dwParam);
return result; // error
}
result.data = opcodeParams[0].pcParam;
result.size = 0x7FFFFFFF; // user allocated memory block can be any size
result.needTerminator = true;
return result;
}
else if (IsVarString(paramType))
{
switch (paramType)
{
// short string variable
case DT_VAR_TEXTLABEL:
case DT_LVAR_TEXTLABEL:
case DT_VAR_TEXTLABEL_ARRAY:
case DT_LVAR_TEXTLABEL_ARRAY:
result.data = (char*)CScriptEngine::GetScriptParamPointer(thread);
result.size = 8;
result.needTerminator = false;
return result;
// long string variable
case DT_VAR_STRING:
case DT_LVAR_STRING:
case DT_VAR_STRING_ARRAY:
case DT_LVAR_STRING_ARRAY:
result.data = (char*)CScriptEngine::GetScriptParamPointer(thread);
result.size = 16;
result.needTerminator = false;
return result;
}
}
CCustomOpcodeSystem::lastErrorMsg = StringPrintf("Writing string, got argument %s", ToKindStr(paramType));
CLEO_SkipOpcodeParams(thread, 1); // skip unhandled param
return result; // error
}
// perform 'sprintf'-operation for parameters, passed through SCM
char* ReadFormattedString(CRunningScript* thread, const char* format, char* outputStr, DWORD len)
{
if (format == nullptr)
{
LOG_WARNING(thread, "Format string is nullptr in script %s", ScriptInfoStr(thread).c_str());
SkipUnusedVarArgs(thread); // skip terminator too
return nullptr; // error
}
unsigned int written = 0;
const char* iter = format;
char* outIter = outputStr;
char bufa[MAX_STR_LEN + 1], fmtbufa[64], *fmta;
while (*iter)
{
while (*iter && *iter != '%')
{
if (written++ >= len)
{
goto _ReadFormattedString_OutOfMemory;
}
*outIter++ = *iter++;
}
if (*iter == '%')
{
// end of format string
if (iter[1] == '\0')
{
LOG_WARNING(thread, "Incomplete format specifier in script %s", ScriptInfoStr(thread).c_str());
SkipUnusedVarArgs(thread);
return nullptr; // error
}
// escaped % character
if (iter[1] == '%')
{
if (written++ >= len)
{
goto _ReadFormattedString_OutOfMemory;
}
*outIter++ = '%';
iter += 2;
continue;
}
// get flags and width specifier
fmta = fmtbufa;
*fmta++ = *iter++;
while (*iter == '0' || *iter == '+' || *iter == '-' || *iter == ' ' || *iter == '*' || *iter == '#')
{
if (*iter == '*')
{
// get width
if (thread->PeekDataType() == DT_END)
{
goto _ReadFormattedString_ArgMissing;
}
CScriptEngine::GetScriptParams(thread, 1);
_itoa_s(opcodeParams[0].dwParam, bufa, 10);
char* buffiter = bufa;
while (*buffiter)
{
*fmta++ = *buffiter++;
}
}
else
{
*fmta++ = *iter;
}
iter++;
}
// get immediate width value
while (isdigit(*iter))
{
*fmta++ = *iter++;
}
// get precision
if (*iter == '.')
{
*fmta++ = *iter++;
if (*iter == '*')
{
if (thread->PeekDataType() == DT_END)
{
goto _ReadFormattedString_ArgMissing;
}
CScriptEngine::GetScriptParams(thread, 1);
_itoa_s(opcodeParams[0].dwParam, bufa, 10);
char* buffiter = bufa;
while (*buffiter)
{
*fmta++ = *buffiter++;
}
}
else
{
while (isdigit(*iter))
{
*fmta++ = *iter++;
}
}
}
// get size
if (*iter == 'h')
{
// handle h (short)
*fmta++ = *iter++;
if (*iter == 'h')
{
// handle hh (signed char)
*fmta++ = *iter++;
}
}
else if (*iter == 'l')
{
// handle l (long)
*fmta++ = *iter++;
}
// check if argument is available
switch (tolower(*iter))
{
case 's':
case 'c':
case 'p':
case 'd':
case 'i':
case 'o':
case 'u':
case 'x':
case 'a':
case 'e':
case 'f':
case 'g': {
if (thread->PeekDataType() == DT_END)
{
_ReadFormattedString_ArgMissing: // jump here on error
LOG_WARNING(
thread, "More tokens in format string than arguments in script %s",
ScriptInfoStr(thread).c_str()
);
thread->IncPtr(); // skip vararg terminator
outputStr[written] = '\0';
return nullptr; // error
}
}
}
switch (*iter)
{
case 'S':
case 's':
if (ReadStringParam(thread, bufa, sizeof(bufa)) == nullptr)
{
strcpy_s(bufa, "(INVALID_STR)");
}
break;
case 'C':
case 'c':
CScriptEngine::GetScriptParams(thread, 1);
bufa[0] = (char)opcodeParams[0].nParam;
bufa[1] = '\0';
break;
case 'p':
CScriptEngine::GetScriptParams(thread, 1);
sprintf_s(bufa, "%08x", opcodeParams[0].dwParam);
break;
case 'P':
CScriptEngine::GetScriptParams(thread, 1);
sprintf_s(bufa, "%08X", opcodeParams[0].dwParam);
break;
case 'a':
case 'A':
case 'e':
case 'E':
case 'f':
case 'F':
case 'g':
case 'G':
*fmta++ = *iter;
*fmta = '\0';
CScriptEngine::GetScriptParams(thread, 1);
sprintf_s(bufa, fmtbufa, opcodeParams[0].fParam);
break;
case 'd':
case 'D':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
*fmta++ = (char)tolower(*iter); // normalize to lowercase
*fmta = '\0';
CScriptEngine::GetScriptParams(thread, 1);
sprintf_s(bufa, fmtbufa, opcodeParams[0].dwParam);
break;
case 'x':
case 'X':
*fmta++ = *iter;
*fmta = '\0';
CScriptEngine::GetScriptParams(thread, 1);
sprintf_s(bufa, fmtbufa, opcodeParams[0].dwParam);
break;
default:
// unrecognized or incomplete specifier - error
*fmta++ = *iter;
*fmta = '\0';
LOG_WARNING(
thread, "Unknown format specifier '%s' in script %s", fmtbufa, ScriptInfoStr(thread).c_str()
);
SkipUnusedVarArgs(thread);
outputStr[written] = '\0';
return nullptr; // error
}
char* bufaiter = bufa;
while (*bufaiter)
{
if (written++ >= len)
{
goto _ReadFormattedString_OutOfMemory;
}
*outIter++ = *bufaiter++;
}
iter++;
}
}
if (written >= len)
{
_ReadFormattedString_OutOfMemory: // jump here on error
LOG_WARNING(
thread, "Target buffer too small (%d) to read whole formatted string in script %s", len,
ScriptInfoStr(thread).c_str()
);
SkipUnusedVarArgs(thread);
outputStr[len - 1] = '\0';
return nullptr; // error
}
// still more var-args available
if (thread->PeekDataType() != DT_END)
{
LOG_WARNING(
thread, "More arguments than tokens in format string in script %s", ScriptInfoStr(thread).c_str()
);
}
SkipUnusedVarArgs(thread); // skip terminator too
outputStr[written] = '\0';
return outputStr;
}
OpcodeResult CCustomOpcodeSystem::CleoReturnGeneric(
WORD opcode, CRunningScript* thread, bool returnArgs, DWORD returnArgCount, bool strictArgCount
)
{
auto cs = reinterpret_cast<CCustomScript*>(thread);
if (cs->GetScmFunction() == ScmFunction::Id_None)
{
SUSPEND("[%04X] used without preceding [0AB1]", opcode);
}
ScmFunction* scmFunc = ScmFunction::Get(cs->GetScmFunction());
if (scmFunc == nullptr || scmFunc->caller != cs)
{
thread->ScmFunction = ScmFunction::Id_None; // clear invalid reference
thread->BaseIP = nullptr; // might be somebody's else, do not release during cleanup
SUSPEND("Cleo function call stack corruption detected");
}
// store return arguments
static SCRIPT_VAR arguments[32];
static bool argumentIsStr[32];
std::forward_list<std::string> stringParams; // scope guard for strings
auto callIP = scmFunc->callIP; // store call ip for error messages
if (returnArgs)
{
if (returnArgCount > 32)
{
SUSPEND("Opcode [%04X] has too many (%d) args", opcode, returnArgCount);
}
auto nVarArg = GetVarArgCount(thread);
if (returnArgCount > nVarArg)
{
SUSPEND("Opcode [%04X] declared %d args, but %d was provided", opcode, returnArgCount, nVarArg);
}
for (DWORD i = 0; i < returnArgCount; i++)
{
SCRIPT_VAR* arg = arguments + i;
argumentIsStr[i] = false;
auto paramType = (eDataType)*thread->GetBytePointer();
if (IsImmInteger(paramType) || IsVariable(paramType))
{
arg->dwParam = CLEO_GetIntOpcodeParam(thread);
}
else if (paramType == DT_FLOAT)
{
arg->fParam = CLEO_GetFloatOpcodeParam(thread);
}
else if (IsImmString(paramType) || IsVarString(paramType))
{
argumentIsStr[i] = true;
OPCODE_READ_PARAM_STRING(str);
stringParams.emplace_front(str);
arg->pcParam = stringParams.front().data();
}
else
{
SUSPEND("Invalid argument type '0x%02X' in opcode [%04X]", paramType, opcode);
}
}
}
// handle program flow
scmFunc->Return(cs); // jump back to cleo_call, right after last input
// param. Return slot var args starts here
if (returnArgs)
{
DWORD returnSlotCount = GetVarArgCount(cs);
if (returnSlotCount != returnArgCount)
{
if (strictArgCount)
{
SUSPEND_COMPAT(
"Opcode [%04X] returned %d params, while function caller expected %d", opcode, returnArgCount,
returnSlotCount
);
}
else
{
LOG_WARNING(
thread, "Opcode [%04X] returned %d params, while function caller expected %d in script %s",
opcode, returnArgCount, returnSlotCount, cs->GetInfoStr().c_str()
);
}
}
// set return args
for (DWORD i = 0; i < std::min<DWORD>(returnArgCount, returnSlotCount); i++)
{
auto arg = (SCRIPT_VAR*)thread->GetBytePointer();
auto paramType = *(eDataType*)arg;
if (IsVarString(paramType))
{
OPCODE_WRITE_PARAM_STRING(arguments[i].pcParam);
}
else if (IsVariable(paramType))
{
if (argumentIsStr[i]) // source was string, write it into
// provided buffer ptr
{
OPCODE_WRITE_PARAM_STRING(arguments[i].pcParam);
}
else
{
CLEO_SetIntOpcodeParam(thread, arguments[i].dwParam);
}
}
else
{
// We iterate output params in 0AB1 now.
lastOpcodePtr = (WORD*)callIP;
prevOpcode = opcode;
lastOpcode = 0x0AB1;
SUSPEND(
"Expected a variable to store the returned value, found %s in opcode [%04X]", ToStr(paramType),
0x0AB1
);
}
}
}
SkipUnusedVarArgs(thread); // skip var args terminator too
return OR_CONTINUE;
}
void SkipUnusedVarArgs(CRunningScript* thread)
{
while (thread->PeekDataType() != DT_END)
{
CLEO_SkipOpcodeParams(thread, 1);
}
thread->IncPtr(); // skip terminator
}
DWORD GetVarArgCount(CRunningScript* thread)
{
// store state
const auto ip = thread->GetBytePointer();
const auto handledParams = CleoInstance.OpcodeSystem.handledParamCount;
DWORD count = 0;
while (thread->PeekDataType() != DT_END)
{
CLEO_SkipOpcodeParams(thread, 1);
count++;
}
// restore state
thread->SetIp(ip);
CleoInstance.OpcodeSystem.handledParamCount = handledParams;
return count;
}
/************************************************************************/
/* Opcode definitions */
/************************************************************************/
// terminate_this_script
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_004E(CRunningScript* thread)
{
CleoInstance.ScriptEngine.RemoveScript(thread);
return OR_INTERRUPT;
}
// gosub
// gosub [label]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0050(CRunningScript* thread)
{
constexpr auto Stack_Size = _countof(CRunningScript::Stack);
if (thread->SP >= Stack_Size)
{
SUSPEND("Call stack overflow\nMax up to %d nested gosub calls is supported", Stack_Size);
}
return CallNativeOpcode(thread, 0x0050); // call game's original
}
// GOSUB return
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0051(CRunningScript* thread)
{
if (thread->SP == 0 && !IsLegacyScript(thread)) // CLEO5 - allow use of GOSUB `return` to exit cleo calls too
{
OPCODE_CONDITION_RESULT(false);
return CleoInstance.OpcodeSystem.CleoReturnGeneric(0x0051, thread, false); // try CLEO's function return
}
if (thread->SP == 0)
{
SUSPEND("`return` used without preceding `gosub` call");
}
return CallNativeOpcode(thread, 0x0051); // call game's original
}
// load_and_launch_mission_internal
// load_and_launch_mission_internal {index} [int]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0417(CRunningScript* thread)
{
CleoInstance.ScriptEngine.missionIndex = CLEO_PeekIntOpcodeParam(thread);
return CallNativeOpcode(thread, 0x0417); // call game's original
}
// stream_custom_script
// stream_custom_script {scriptFileName} [string] [arguments]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0A92(CRunningScript* thread)
{
OPCODE_READ_PARAM_STRING(path);
// convert path from relative to CLEO directory to relative to game directory
auto filename = reinterpret_cast<CCustomScript*>(thread)->ResolvePath(path, DIR_CLEO);
TRACE(
"[0A92] Starting new custom script %s from thread named '%s'", filename.c_str(), thread->GetName().c_str()
);
auto cs = new CCustomScript(filename.c_str(), false, thread);
thread->SetConditionResult(cs && cs->IsOk());
if (cs && cs->IsOk())
{
CleoInstance.ScriptEngine.AddCustomScript(cs);
((::CRunningScript*)thread)->ReadParametersForNewlyStartedScript((::CRunningScript*)cs);
}
else
{
if (cs)
{
delete cs;
}
SkipUnusedVarArgs(thread);
LOG_WARNING(0, "Failed to load script '%s' in script ", filename.c_str(), ScriptInfoStr(thread).c_str());
}
return OR_CONTINUE;
}
// terminate_this_custom_script
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0A93(CRunningScript* thread)
{
CCustomScript* cs = reinterpret_cast<CCustomScript*>(thread);
if (thread->IsMission() || !cs->IsCustom())
{
LOG_WARNING(
0,
"Incorrect usage of opcode [0A93] in script '%s'. Use [004E] "
"instead.",
ScriptInfoStr(thread).c_str()
);
return OR_CONTINUE; // legacy behavior
}
CleoInstance.ScriptEngine.RemoveScript(thread);
return OR_INTERRUPT;
}
// load_and_launch_custom_mission
// load_and_launch_custom_mission {scriptFileName} [string] [arguments]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0A94(CRunningScript* thread)
{
OPCODE_READ_PARAM_STRING(path);
// convert path from relative to CLEO directory to relative to game directory
auto filename = reinterpret_cast<CCustomScript*>(thread)->ResolvePath(path, DIR_CLEO);
filename += ".cm"; // add custom mission extension
TRACE(
"[0A94] Starting new custom mission '%s' from thread named '%s'", filename.c_str(),
thread->GetName().c_str()
);
auto cs = new CCustomScript(filename.c_str(), true, thread);
thread->SetConditionResult(cs && cs->IsOk());
if (cs && cs->IsOk())
{
CleoInstance.ScriptEngine.AddCustomScript(cs);
CTheScripts::WipeLocalVariableMemoryForMissionScript();
auto fakeScriptAddress =
(BYTE*)missionLocals - offsetof(CRunningScript, LocalVar); // TODO: maybe copy params ourself instead?
((::CRunningScript*)thread)->ReadParametersForNewlyStartedScript((::CRunningScript*)fakeScriptAddress);
}
else
{
if (cs)
{
delete cs;
}
SkipUnusedVarArgs(thread);
LOG_WARNING(
0, "[0A94] Failed to load mission '%s' from script '%s'.", filename.c_str(), thread->GetName().c_str()
);
}
return OR_CONTINUE;
}
// save_this_custom_script
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0A95(CRunningScript* thread)
{
if (thread->IsCustom())
{
reinterpret_cast<CCustomScript*>(thread)->EnableSaving();
}
return OR_CONTINUE;
}
// gosub_if_false
// gosub_if_false [label]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0AA0(CRunningScript* thread)
{
auto offset = OPCODE_READ_PARAM_INT();
if (thread->GetConditionResult())
{
return OR_CONTINUE;
}
constexpr auto Stack_Size = _countof(CRunningScript::Stack);
if (thread->SP >= Stack_Size)
{
SUSPEND("Call stack overflow\nMax up to %d nested gosub calls is supported", Stack_Size);
}
thread->PushStack(thread->GetBytePointer());
thread->Jump(offset);
return OR_CONTINUE;
}
// return_if_false
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0AA1(CRunningScript* thread)
{
if (thread->GetConditionResult())
{
return OR_CONTINUE;
}
if (thread->SP == 0)
{
SUSPEND("`return_if_false` used without preceding `gosub` call");
}
thread->SetIp(thread->PopStack());
return OR_CONTINUE;
}
// is_game_version_original
// is_game_version_original (logical)
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0AA9(CRunningScript* thread)
{
auto gameVer = CleoInstance.VersionManager.GetGameVersion();
auto scriptVer = CLEO_GetScriptVersion(thread);
bool result = (gameVer == GV_US10) || (scriptVer <= CLEO_VER_4_MIN && gameVer == GV_EU10);
OPCODE_CONDITION_RESULT(result);
return OR_CONTINUE;
}
// cleo_call
// cleo_call [label] {numParams} [int] {params} [arguments]
OpcodeResult __stdcall CCustomOpcodeSystem::opcode_0AB1(CRunningScript* thread)
{
int label = 0;
auto callIP = thread->CurrentIP - 2; // back to start of opcode
std::string moduleTxt;
auto paramType = thread->PeekDataType();
if (IsImmInteger(paramType) || IsVariable(paramType))
{
label = CLEO_GetIntOpcodeParam(thread); // label offset
}
else if (IsImmString(paramType) || IsVarString(paramType))
{
char tmp[MAX_STR_LEN + 1];
auto str = ReadStringParam(thread, tmp, sizeof(tmp)); // string with module and export name
if (str != nullptr)
{