-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscrlog.cpp
1562 lines (1318 loc) · 45.4 KB
/
scrlog.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
/*
* scrlog.cpp:
* This file contains the higher level implementation of scrlog
*
* Issues (entire SCRLOG project):
* Not thread safe
* Not lightweight
*
* LICENSE:
* (c) 2020 - lazyuselessman, Junior_Djjr
* (c) 2013 - LINK/2012 - <dma_2012@hotmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this plugin and source code, to copy, modify, merge, publish and/or distribute
* as long as you leave the original credits (above copyright notice)
* together with your derived work. Please not you are NOT permited to sell or get money from it
*
* THE SOFTWARE AND SOURCE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#define IS_ADDRESSES_CPP
#include <cstdio> // for C Streams and sprintf
#include <cstring> // for memset
#include <cctype> // for isspace
#include <new> // for std::bad_alloc
#include <string> // for std::string, our buffer
#include "scrlog.h"
#include "GameInfo.h"
#include "Injector.h"
#include "CRunningScript.h"
#include "Events.h"
#include "Shellapi.h"
static GameInfo info;
void init(GameInfo& info)
{
if(!SCRLog::Open())
return;
switch(info.GetGame())
{
case info.III: III_Patch(info); break;
case info.VC: VC_Patch(info); break;
case info.SA: SA_Patch(info); break;
}
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
if(fdwReason == DLL_PROCESS_ATTACH)
{
info.PluginName = "scrlog";
info.DelayedDetect(init);
}
else if(fdwReason == DLL_PROCESS_DETACH)
{
SCRLog::Close();
}
return TRUE;
}
uint32_t pCheatString = 0;
uint32_t pScriptsProcessed = 0;
std::string message;
std::wstring messageWide;
uint32_t lastCommand = 0;
// Util functions
namespace SCRLog
{
bool TestCheat(const char* cheat)
{
char *c = (char *)pCheatString;
char buf[30];
strcpy(buf, cheat);
char *s = _strrev(buf);
if (_strnicmp(s, c, strlen(s))) return false;
c[0] = 0;
return true;
}
// Get this DLL directory
static size_t GetDLLDirectory(char* out_buf, size_t max)
{
// Reference:
// http://stackoverflow.com/questions/6924195/get-dll-path-at-runtime
char *path = out_buf, *p;
HMODULE module;
DWORD r;
// Find module handle by a address (let's use this function pointer for the address)
if(GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR) &GetDLLDirectory, &module))
{
// Get the module path and remove the dll filename
r = GetModuleFileNameA(module, path, max);
if(r != 0 && r != max && (p = strrchr(path, '\\'))!=0)
{
p[1] = 0;
return (p - path) + 1;
}
}
return 0;
}
// Get path for file in dll directory ($GetDLLDirectory()$filename)
static char* GetPathFor(const char* filename, char* out, size_t max)
{
size_t i = GetDLLDirectory(out, max);
if(i == 0)
{
*out = 0;
return out;
}
strcpy(out+i, filename);
return out;
}
// Opens the file based on the DLL path
static FILE* fopen(const char* filename, const char* mode)
{
// We need this function to work properly with scripts\ subfolder with Silent's ASI Loader
// and mss\ folder with miles loader.
// Reference:
// http://stackoverflow.com/questions/6924195/get-dll-path-at-runtime
char path[2048];
// If using Silent's ASI Loader and it was not delayed detect there is no need for this function
// If using III or Vice City it is necessary because our ASI Loader (miles) run on splash screen
//if(info.GetGame() == info.SA && !info.IsDelayed())
// return std::fopen(filename, mode);
GetPathFor(filename, path, sizeof(path));
return std::fopen(path, mode);
}
// WinAPI GetPrivateProfileX, Boolean implementation
static bool GetPrivateProfileBoolA(const char* section, const char* key, bool defaultv, const char* filename)
{
char buf[8];
if(!GetPrivateProfileStringA(section, key, 0, buf, 7, filename))
return defaultv;
else if(buf[1] == 0)
return buf[0] != '0';
else if(!_stricmp(buf, "TRUE"))
return true;
else
return false;
}
}
namespace SCRLog
{
typedef std::string string_buffer;
static const char szLogName[] = "scrlog.log";
static const char szIniName[] = "scrlog.ini";
static char ini[2048];
enum {
EXP_NONE,
EXP_ASSIGN, EXP_ADD, EXP_SUB, EXP_MUL, EXP_DIV,
EXP_EQ, EXP_LEQ, EXP_GEQ, EXP_LE, EXP_GE,
EXP_TIMED_ADD, EXP_TIMED_SUB, EXP_CAST,
EXP_MAX
};
static const char* ExpressionSeparator[EXP_MAX] =
{
" ", " =", " +=", " -=", " *=", " /=", " ==", " <=", " >=", " <", " >",
" +=@ ", " -=@", " =#"
};
enum eFlushTime
{
FLUSH_NEVER,
FLUSH_AUTOMATIC,
FLUSH_ON_SCRIPT,
FLUSH_ON_COMMAND,
FLUSH_ON_COLLECT,
FLUSH_ON_WRITE
};
static const char* aFlushTime[] =
{
"FLUSH_NEVER", "FLUSH_AUTOMATIC", "FLUSH_ON_SCRIPT", "FLUSH_ON_COMMAND",
"FLUSH_ON_COLLECT", "FLUSH_ON_WRITE", 0
};
struct SScriptCommand
{
bool bValid;
char cCommandName[64];
char cArguments[32];
int nExp; // EXPression type
SScriptCommand()
{
nExp = EXP_NONE;
bValid = false;
cCommandName[0] = 0;
memset(cArguments, 0, sizeof(cArguments));
}
};
static void ReadINI(void (*callback)(char* key, char* value));
// fake vftable, set up by the hookers (scmlog_<GAME>.cpp)
void** ppRunningScript;
void* New_CRunningScript__UpdateCompareFlag;
void* CRunningScript__UpdateCompareFlag;
void* AfterScripts;
void* RegisterScript;
void* RegisterCommand;
void* RegisterCommandOut;
void* RegisterCallToCollectParameters;
void* RegisterCallToStoreParameters;
void* RegisterCallToCollectString;
void* RegisterCollectedString;
void* RegisterCollectionAtIndex;
void* RegisterCompareFlagUpdate;
void* RegisterLocalVariable;
void* RegisterGlobalVariable;
void* RegisterVariable;
// Pointers to game executable data, also set up by the hookers
ScriptVar* MissionLocals;
ScriptVar* CollectiveArray;
short* ScriptsUpdated;
char* ScriptSpace;
char* ScriptSpaceEnd;
char* MissionSpace;
char* MissionSpaceEnd;
// SCRLog
FILE* log;
char* pParam; // Pointer to SScriptCommand::cArguments[_CURRENT_ARGUMENT_]
bool bParam; // true if can use pParam to count params
bool bOpened = false; // true if SCRLOG is open
char* StringBuffer; // Buffer to use with sprintf, etc
char* lastLineBuffer; // The last command line to use with crash window
string_buffer LogBuffer; // File buffer, let's use our own
int32_t Command; // Current command being executed
int32_t Exp; // Current expression being executed
bool UsedExpressionThisCommand; // true if the current command already took a expresion string (==, *=, etc)
bool ThisCommandResult; // The result (UpdateCompareFlag) of the current command
int32_t Datatype; // Current datatype, set by the game hookers (scmlog_<GAME>.cpp)
uint32_t nCommandsOnLog; // Number of commands currently on the log file
uint32_t nScriptsOnLog; // Number of scripts currently on the log file
int32_t nHighestCommand = 0x0B20; // Highest command used.
bool bEnabled = true; // Easy way to toggle. Can be toggled like a cheat in-game.
SScriptCommand* Commands; // Pointer to commands data... Commands[nHighestCommand+1]
// Configuration - set up on the INI, see the ini file for descriptions
uint32_t nMaxScriptsOnLog = 600;
uint32_t nMaxOpcodesOnLog = 6000;
uint32_t nStreamBufferSize = 2048;
int FlushTime = FLUSH_NEVER;
bool bShowCrashWindow = true;
bool bClearLogEachFrame = true;
bool bUseBreakpointOpcode = false;
bool bClassicLog = false;
bool bUseParamInfo = true;
bool bUseSimpleFloat = true;
bool bUseExpressions = true;
bool bHookStrncpy = false; // Dont work as expected
bool bHookAfterScripts = true;
bool bHookOnlyRegisterScript= true;
bool bHookCollectString = true;
bool bHookCollectVarPointer = true;
bool bHookRegisterScript = true;
bool bHookRegisterCommand = true;
bool bHookCollectParam = true; // crash 4512bc // same // 1 2 451265 // 1 3 80808080
bool bHookFindDatatype = true; // crash 7e0fc0 without updatecomapre flag // 4511a5 // 2 3 450fcc
bool bHookStoreParam = true; // crash 450fcc without updatecomapre flag // 80808080 // 1 2 3 450fcc // 450fce
bool bHookUpdateCompareFlag = true;
bool bProcessingScriptsNow = false;
char scname[8];
// Setups commands in range a-b to expression exp
inline void SetupCommandExpression(int a, int b, int exp)
{
for(int i = a; i <= b; ++i)
Commands[i].nExp = exp;
}
// Setups all expression commands to their desired values
static void SetupCommandsExpression()
{
if(nHighestCommand >= 0x0093)
{
SetupCommandExpression(0x0004, 0x0007, EXP_ASSIGN);
SetupCommandExpression(0x0008, 0x000B, EXP_ADD);
SetupCommandExpression(0x000C, 0x000F, EXP_SUB);
SetupCommandExpression(0x0010, 0x0013, EXP_MUL);
SetupCommandExpression(0x0014, 0x0017, EXP_DIV);
SetupCommandExpression(0x0018, 0x0027, EXP_GE);
SetupCommandExpression(0x0028, 0x0037, EXP_GEQ);
SetupCommandExpression(0x0038, 0x003C, EXP_EQ);
SetupCommandExpression(0x0042, 0x0046, EXP_EQ);
SetupCommandExpression(0x0058, 0x005F, EXP_ADD);
SetupCommandExpression(0x0060, 0x0067, EXP_SUB);
SetupCommandExpression(0x0068, 0x006F, EXP_MUL);
SetupCommandExpression(0x0070, 0x0077, EXP_DIV);
SetupCommandExpression(0x0078, 0x007D, EXP_TIMED_ADD);
SetupCommandExpression(0x007E, 0x0083, EXP_TIMED_SUB);
SetupCommandExpression(0x0084, 0x008B, EXP_ASSIGN);
SetupCommandExpression(0x008C, 0x0093, EXP_CAST);
}
if(nHighestCommand >= 0x04B7 && info.GetGame() != info.III)
{
Commands[0x04A3].nExp = EXP_EQ;
Commands[0x04A4].nExp = EXP_EQ;
Commands[0x04AE].nExp = EXP_ASSIGN;
Commands[0x04AF].nExp = EXP_ASSIGN;
SetupCommandExpression(0x04B0, 0x04B3, EXP_GE);
SetupCommandExpression(0x04B4, 0x04B7, EXP_GEQ);
}
if(info.GetGame()== info.SA)
{
if(nHighestCommand >= 0x05AE)
{
Commands[0x05A9].nExp = EXP_ASSIGN;
Commands[0x05AA].nExp = EXP_ASSIGN;
Commands[0x05AD].nExp = EXP_EQ;
Commands[0x05AE].nExp = EXP_EQ;
}
if(nHighestCommand >= 0x06D2)
{
Commands[0x06D1].nExp = EXP_ASSIGN;
Commands[0x06D2].nExp = EXP_ASSIGN;
}
if(nHighestCommand >= 0x07D7)
{
Commands[0x07D6].nExp = EXP_EQ;
Commands[0x07D7].nExp = EXP_EQ;
}
}
}
// Exp is setup with the command value, and the separator string is returned
inline const char* GetExpressionSeparator()
{
if(Command <= nHighestCommand && !UsedExpressionThisCommand)
{
UsedExpressionThisCommand = true;
return ExpressionSeparator[ Exp = Commands[Command].nExp ];
}
return ExpressionSeparator[ Exp = EXP_NONE ];
}
// Flush the stream to the disk
inline void Flush(bool bForce = false)
{
if(!bForce && FlushTime == FLUSH_NEVER)
return;
if(LogBuffer.length() > 0)
{
fwrite(LogBuffer.data(), sizeof(char), LogBuffer.length(), log);
LogBuffer.clear();
}
fflush(log);
}
// Logs string with size bytes
inline void Log(const char* string, size_t size)
{
if(FlushTime != FLUSH_ON_WRITE)
{
LogBuffer.append(string, string+size);
if(FlushTime != FLUSH_NEVER && LogBuffer.length() >= nStreamBufferSize)
Flush();
}
else
{
fwrite(string, sizeof(char), size, log);
Flush();
}
}
// Log null terminated string
inline void Log(const char* string)
{
Log(string, strlen(string));
}
// Clear the log file
inline void Reset()
{
nCommandsOnLog = 0;
nScriptsOnLog = 0;
if(FlushTime != FLUSH_NEVER)
{
Flush();
fclose(log);
log = fopen(szLogName, "wb");
//if(log == 0)
// error, what to do?
// throw and error and terminate application
}
else
{
LogBuffer.clear();
}
}
// Setups the pParam pointer
inline char* GetCommandArgs()
{
int cmd = Command;
if(bParam && cmd <= nHighestCommand)
return (pParam = Commands[cmd].cArguments);
return 0;
}
// Get current command name
inline char* GetCommandName()
{
static char cUnkCommand[16];
int cmd = Command, exp;
SScriptCommand* s;
if(cmd <= nHighestCommand)
{
s = &Commands[cmd];
exp = s->nExp;
if(exp != EXP_NONE)
return "";
else if(s->bValid)
return s->cCommandName;
}
sprintf(cUnkCommand, "COMMAND_%.4X", cmd);
return cUnkCommand;
}
// Get argument type for the current parameter
inline int GetArgumentType()
{
int cmd = Command;
SScriptCommand* s;
if(bParam && cmd <= nHighestCommand)
{
s = &Commands[cmd];
if(s->bValid)
{
char x = *pParam++;
if(x != 0 && x != 'a')
return x;
}
}
return Datatype;
}
// Helper function for RegisterParam()
inline char* float2str(float f)
{
static char fbuf[64];
if(bUseSimpleFloat)
{
sprintf(fbuf, "%g", f);
for(char* p = fbuf; ; ++p)
{
if(*p == '.')
{ break; }
else if(*p == 0)
{ p[0] = '.', p[1] = '0'; p[2] = 0; break; }
}
}
else
{
sprintf(fbuf, "%f", f);
}
return fbuf;
}
// Register param to Buffer and returns num chars taken
int RegisterParam(char* Buffer, ScriptVar* data, int n)
{
switch(GetArgumentType())
{
case 1: case 2: case 3: case 4: case 5: // [III|VC|SA] Int32, Global, Local, Int8, Int16
case 'i': case 'm': case 'l':
return sprintf(Buffer, " param %d = %d\r\n", n, data->nParam);
case 'h':
return sprintf(Buffer, " param %d = 0x%X\r\n", n, data->nParam);
case 6: case 'f': // Float
return sprintf(Buffer, " param %d = %s\r\n", n, float2str(data->fParam));
default:
return sprintf(Buffer, " param %d = [UNKNOWN]\r\n", n);
}
}
// Same as above, but for modern logging
int RegisterParamValue(char* Buffer, ScriptVar* data)
{
switch(GetArgumentType())
{
case 1: case 2: case 3: case 4: case 5: // [III|VC|SA] Int32, Global, Local, Int8, Int16
case 'i': case 'm': case 'l':
return sprintf(Buffer, " %d", data->nParam);
case 'h':
return sprintf(Buffer, " 0x%X", data->nParam);
case 6: case 'f': // Float
return sprintf(Buffer, " %s", float2str(data->fParam));
default:
return sprintf(Buffer, " [UNKNOWN]");
}
}
// Base for LogFactory, this have functions that are specific for each game!
// Base for III and Vice City:
template<class TScript>
class LogFactoryBase
{
public:
typedef TScript CRunningScript;
static CRunningScript* pRunningScript;
// Get vars array and num vars for script
static void GetScriptVars(CRunningScript* script, ScriptVar*& aVars, int& nVars)
{
aVars = script->tls;
nVars = 18;
}
// Gets the instruction pointer for script
static char* GetScriptIP(CRunningScript* script, unsigned int& humanIP)
{
char* ip = &ScriptSpace[(size_t)script->ip];
humanIP = (unsigned int) script->ip;
// if ip ain't in main block, then I guess the script has local offsets...
if(ip < ScriptSpace || ip >= ScriptSpaceEnd)
{
// if ip ain't in mission block, it is a CLEO script (XXX: Anyone wanting to reverse III\VC CLEO.asi?)
if(ip >= MissionSpace || ip < MissionSpaceEnd)
humanIP = (unsigned int)(ip - MissionSpace);
}
return ip;
}
// Gets the variable type and value (offset if global, index if local)
// Returns the var type (2 if global, 3 if local, -1 if pointer)
static int __stdcall GetVariableOffset(CRunningScript* script, ScriptVar* var, int& out)
{
// Check entire script struct bounds, 'cause someone may want to replace something there
// in favour of a variable
if(var >= (ScriptVar*)(script) && var < (ScriptVar*)(script + sizeof(*script)) )
return (out = var - script->tls), 3; // << return 3
// Not local, try globals
char* pv = (char*)var;
if(pv >= ScriptSpace && pv < ScriptSpaceEnd)
return (out = pv - ScriptSpace), 2; // << return 2
// I have no idea what is this...
out = (int)(var);
return -1;
}
//
};
// Base for San Andreas:
template<>
class LogFactoryBase<CRunningScript_SA>
{
public:
typedef CRunningScript_SA CRunningScript;
static CRunningScript* pRunningScript;
// Get vars array and num vars for script
static void __stdcall GetScriptVars(CRunningScript* script, ScriptVar*& aVars, int& nVars)
{
if(script->missionFlag)
{
aVars = MissionLocals;
nVars = 1024;
}
else
{
aVars = script->tls;
nVars = 34;
}
}
// Gets the instruction pointer for script
static char* __stdcall GetScriptIP(CRunningScript* script, unsigned int& humanIP)
{
char *ip = script->ip, *base = script->base? script->base : ScriptSpace;
humanIP = ip - base;
return ip;
}
// Gets the variable type and value (offset if global, index if local)
// Returns the var type (2 if global, 3 if local, -1 if pointer)
static int __stdcall GetVariableOffset(CRunningScript* script, ScriptVar* var, int& out)
{
// Check locals first, since they're in a place higher in memory
// The above statement is only true in non-mission scripts, but who cares for 1 script in a group of 100.
if(!script->missionFlag)
{
// Check entire script struct bounds, 'cause someone may want to replace something there
// in favour of a variable
if(var >= (ScriptVar*)(script) && var < (ScriptVar*)(script + sizeof(*script)) )
return (out = var - script->tls), 3; // << return 3
}
else
{
if(var >= MissionLocals && var < &MissionLocals[1024])
return (out =var - MissionLocals), 3; // << return 3
}
// Not local, try globals
char* pv = (char*) var;
if(pv >= ScriptSpace && pv < ScriptSpaceEnd)
return (out = pv - ScriptSpace), 2; // << return 2
// I have no idea what is this... thread memory? super vars?
out = (int)(var);
return -1;
}
};
// The factory itself, the factory will produce our functions for each game without any effort.
// Write once, get 3 outputs, thanks generic programming.
template<class TScript>
class LogFactory : public LogFactoryBase<TScript>
{
public:
// We need to replace the UpdateCompareFlag method =|
static void __stdcall CRunningScript__UpdateCompareFlag(CRunningScript* script, char v)
{
char b = script->notFlag? v == 0 : v != 0;
ThisCommandResult = b != 0;
int logic = script->logicalOp;
if(logic == 0)
{
script->compareFlag = b;
}
else
{
bool e;
if(logic >= 1 && logic <= 8) // &&
script->compareFlag &= b, e = logic == 1;
else if(logic >= 21 && logic <= 28) // ||
script->compareFlag |= b, e = logic == 21;
if(e) script->logicalOp = 0;
else --script->logicalOp;
}
if(script == pRunningScript)
{
typedef void (__stdcall *fn_t)(void);
fn_t fn = (fn_t) RegisterCompareFlagUpdate;
fn();
}
}
// Script finalized
static void __stdcall AfterScripts(CRunningScript* script)
{
if (bEnabled) Log("\r\nFinished processing.");
if (pCheatString) {
// I don't want to make another hook just to add TestCheat, so, just run it for first script.
// If pScriptsProcessed isn't available, fuck off this optimization for now.
if (pScriptsProcessed == 0x0 || *(uint32_t*)pScriptsProcessed == 1) {
if (TestCheat("SCRL")) {
bEnabled = !bEnabled;
WritePrivateProfileStringA("CONFIG", "ENABLED", (bEnabled) ? "TRUE" : "FALSE", ini);
if (bEnabled) message = "SCRLog is ENABLED!"; else message = "SCRLog is DISABLED!";
Log("\r\n\r\n");
Log(&message[0]);
Log("\r\n");
wchar_t* wMessage = nullptr;
if (info.GetGame() != info.SA) {
int wchars_num = MultiByteToWideChar(CP_UTF8, 0, message.c_str(), -1, NULL, 0);
wMessage = new wchar_t[wchars_num];
MultiByteToWideChar(CP_UTF8, 0, message.c_str(), -1, wMessage, wchars_num);
}
switch (info.GetGame())
{
case info.III: IIICHudSetHelpMessage(wMessage, 1); break;
case info.VC: VCCHudSetHelpMessage(wMessage, 1, 0); break;
case info.SA: SACHudSetHelpMessage(message.c_str(), 1, 0, 0); break;
}
if (wMessage) delete[] wMessage;
}
}
}
bProcessingScriptsNow = false;
scname[0] = 0;
lastLineBuffer[0] = 0;
}
// Start logging script
static void __stdcall RegisterScript(CRunningScript* script)
{
if (!bEnabled) return;
int i, nVars;
ScriptVar* aVars;
char* buffer = StringBuffer;
// Set running script pointer
pRunningScript = script;
++nScriptsOnLog;
bProcessingScriptsNow = true;
// Reset the log file if I must clear the file on each frame
if((bClearLogEachFrame && *ScriptsUpdated == 1) || nScriptsOnLog > nMaxScriptsOnLog)
Reset();
// Get the pointer to the script variables (and num vars)
GetScriptVars(script, aVars, nVars);
// Get script name...
strncpy(scname, pRunningScript->scriptName, 8);
scname[7] = 0; // Safe for buggy scripts that use names with >=8 chars
// Create log string...
{
// Log script name
buffer += sprintf(buffer,
"\r\n\r\n********************************************\r\n"
" script %s\r\n"
" Local variables dump:",
scname);
// Log local variables
for(i = 0; i < nVars; ++i)
{
if((i % 16) == 0) strcpy(buffer, "\r\n"), buffer += 2;
buffer += sprintf(buffer, " %d", aVars[i]);
}
// ha!
if (bHookOnlyRegisterScript) {
buffer += sprintf(buffer, "\r\n********************************************\r\n");
buffer += sprintf(buffer, "HOOK_ONLY_REGISTER_SCRIPT=TRUE set in the ini.\r\nThis log isn't useful for asking help!\r\nDisable it or also send other crash log.");
}
buffer += sprintf(buffer, "\r\n********************************************\r\n");
}
if(FlushTime == FLUSH_ON_SCRIPT)
Flush();
// Send it to the stream
Log(StringBuffer, buffer - StringBuffer);
}
};
template<class TScript>
class LogClassic : public LogFactory<TScript>
{
public:
static void __stdcall RegisterCommand()
{
if (!bEnabled) return;
char* ip;
unsigned int humanIP;
unsigned short command;
char* buffer = StringBuffer;
CRunningScript* script = pRunningScript;
++nCommandsOnLog;
// If too many commands, clear the log
if(nCommandsOnLog > nMaxOpcodesOnLog)
Reset();
// Get ip and command
ip = GetScriptIP(pRunningScript, humanIP);
command = *(uint16_t*)ip;
lastCommand = command;
//
Command = command & 0x7FFF;
UsedExpressionThisCommand = false;
GetCommandArgs();
Log(buffer, sprintf(buffer, "\r\n%.8u&%d: %.4X\r\n", humanIP, script->compareFlag, command));
if(FlushTime == FLUSH_ON_COMMAND)
Flush();
if (lastCommand == 0xED0 /* RETURN_SCRIPT_EVENT from CLEO+ */) bProcessingScriptsNow = false;
}
static void __stdcall RegisterCompareFlagUpdate()
{
if (!bEnabled) return;
Log(StringBuffer, sprintf(StringBuffer, " update compare flag: %s\r\n",
ThisCommandResult? "true" : "false"));
}
static void __stdcall RegisterCallToCollectParameters(unsigned short n)
{
if (!bEnabled) return;
Log(StringBuffer, sprintf(StringBuffer, " collect params: %d\r\n", n));
}
static void __stdcall RegisterCallToCollectString()
{
if (!bEnabled) return;
Log(" collect string: ");
}
static void __stdcall RegisterCallToStoreParameters(int n)
{
if (!bEnabled) return;
if (!bProcessingScriptsNow)
return;
char* buffer = StringBuffer;
buffer += sprintf(buffer, " store params: %d\r\n", n);
for(int i = 0; i < n; ++i)
buffer += RegisterParam(buffer, &CollectiveArray[i], i+1);
Log(StringBuffer, buffer - StringBuffer);
if(FlushTime == FLUSH_ON_COLLECT)
Flush();
}
static void __stdcall RegisterCollectionAtIndex(int n)
{
if (!bEnabled) return;
Log(StringBuffer, RegisterParam(StringBuffer, &CollectiveArray[n-1], n));
if(FlushTime == FLUSH_ON_COLLECT)
Flush();
}
// This is just used for temp fix on RegisterCollectedString
// Maybe strnlen_s instead?
static size_t safe_strlen(const char *str, size_t max_len)
{
const char * end = (const char *)memchr(str, '\0', max_len);
if (end == NULL)
return 0;
else
return end - str;
}
static void __stdcall RegisterCollectedString(const char* str, size_t max)
{
// Let's make it safe, we can guarante str is null terminated, so let's transfer things to
// our buffer just in case.
if (!bEnabled) return;
if(!pRunningScript) // III\VC hack for strncpy
return;
if(!bProcessingScriptsNow)
return;
char buf[512];
const char* p = 0;
// Register that we are going to another param, and ignore output
ScriptVar dummy;
Datatype = -1;
RegisterParamValue(buf, &dummy);
// TODO: This is just a temp fix for stack bug on new CLEO version.
if (max >= 256)
{
max = safe_strlen(str, 256);
}
// making sure it is null terminated without any peformance effort...
if (max > 0)
{
if (str[max - 1] == 0)
{
p = str;
}
else if (max < sizeof(buf))
{
strncpy(buf, str, max);
buf[max] = 0;
p = buf;
}
}
Log(StringBuffer, sprintf(StringBuffer, "%s\r\n", p? p : "[DAMAGED_STRING]"));
if(FlushTime == FLUSH_ON_COLLECT)
Flush();
}
static void __stdcall RegisterPointer(void* ptr)
{
if (!bEnabled) return;
Log(StringBuffer, sprintf(StringBuffer, " collect pointer %p\r\n", ptr));
}
static void __stdcall RegisterGlobalVariable(int offset)
{
if (!bEnabled) return;
char buffer[64];
RegisterParamValue(buffer, (ScriptVar*)(&ScriptSpace[offset]));
Log(StringBuffer, sprintf(StringBuffer, " collect global var %d: %s\r\n", offset / 4, buffer));
}
static void __stdcall RegisterLocalVariable(int index)
{
if (!bEnabled) return;
char buffer[64]; int n; ScriptVar* var;
GetScriptVars(pRunningScript, var, n);
Log(StringBuffer, sprintf(StringBuffer, " collect local var %d: %s\r\n", index, buffer));
}
static void __stdcall RegisterVariable(ScriptVar* ptr)
{
if (!bEnabled) return;
int value;
switch( GetVariableOffset(pRunningScript, ptr, value) )
{
case -1: RegisterPointer(ptr); break;
case 2: RegisterGlobalVariable(value); break;
case 3: RegisterLocalVariable(value); break;
}
}
};
template<class TScript>
class LogModern : public LogFactory<TScript>
{
public:
static void __stdcall RegisterCommand()
{
if (!bEnabled) return;
static const char notArray1[2][6] = { " ", " NOT " };
static const char notArray2[2][6] = { "", " NOT" };
char* ip, *cmdName;
bool notFlag;
unsigned int humanIP;
unsigned short command;
char* buffer = StringBuffer;
CRunningScript* script = pRunningScript;
++nCommandsOnLog;
// If too many commands, clear the log
if(nCommandsOnLog > nMaxOpcodesOnLog)
Reset();
// Get ip and command
ip = GetScriptIP(pRunningScript, humanIP);
command = *(uint16_t*)ip;
lastCommand = command;