-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathDebugScriptCompiler.cs
More file actions
7728 lines (7526 loc) · 391 KB
/
DebugScriptCompiler.cs
File metadata and controls
7728 lines (7526 loc) · 391 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.ComponentModel.DataAnnotations;
using ScriptableFramework;
using DotnetStoryScript.CommonFunctions;
#nullable enable
namespace CppDebugScript
{
/// <summary>
/// Array is alias name for continuous variable, Can only be used in init/mov/arrget/arrset, not in calc and API.
/// The API can treat 64-bit integers as pointers, so it can do a lot of things.
/// But the script itself can only operate on three types: long/double/string, without going through the API.
/// </summary>
public enum InsEnum : int
{
CALLEXTERN = 0,
RET,
JMP,
JMPIF,
JMPIFNOT,
INC,
INCFLT,
INCV,
INCVFLT,
DEC,
DECFLT,
DECV,
DECVFLT,
MOV,
MOVFLT,
MOVSTR,
ARRGET,
ARRGETFLT,
ARRGETSTR,
ARRSET,
ARRSETFLT,
ARRSETSTR,
NEG,
NEGFLT,
ADD,
ADDFLT,
ADDSTR,
SUB,
SUBFLT,
MUL,
MULFLT,
DIV,
DIVFLT,
MOD,
MODFLT,
AND,
OR,
NOT,
GT,
GTFLT,
GTSTR,
GE,
GEFLT,
GESTR,
EQ,
EQFLT,
EQSTR,
NE,
NEFLT,
NESTR,
LE,
LEFLT,
LESTR,
LT,
LTFLT,
LTSTR,
LSHIFT,
RSHIFT,
URSHIFT,
BITAND,
BITOR,
BITXOR,
BITNOT,
INT2STR,
FLT2STR,
STR2INT,
STR2FLT,
CASTFLTINT,
CASTSTRINT,
CASTINTFLT,
CASTINTSTR,
ASINT,
ASFLOAT,
ASLONG,
ASDOUBLE,
ARGC,
ARGV,
ADDR,
ADDRFLT,
ADDRSTR,
PTRGET,
PTRGETFLT,
PTRGETSTR,
PTRSET,
PTRSETFLT,
PTRSETSTR,
CASCADEPTR,
STKIX,
HOOKID,
HOOKVER,
FFIAUTO,
FFIMANUAL,
FFIMANUALSTACK,
FFIMANUALDBL,
FFIMANUALSTACKDBL,
RESERVE5,
RESERVE4,
RESERVE3,
RESERVE2,
RESERVE1,
CALLINTERN_FIRST = 100,
CALLINTERN_LAST = 255,
NUM
}
public sealed class DebugScriptCompiler
{
public string LoadApiDefine(string txt)
{
int apiId = 0;
int externApiId = 0;
m_Apis.Clear();
m_Protos.Clear();
Dsl.DslFile file = new Dsl.DslFile();
var err = new StringBuilder();
if (file.LoadFromString(txt, (msg) => { err.AppendLine(msg); })) {
foreach (var dslInfo in file.DslInfos) {
var id = dslInfo.GetId();
if (id == "defapi" || id == "defexternapi") {
bool handled = false;
var fd = dslInfo as Dsl.FunctionData;
Debug.Assert(fd != null);
var call = fd;
bool existsOptions = false;
if (fd.IsHighOrder && fd.LowerOrderFunction.IsParenthesesParamClass() && fd.HaveStatement()) {
call = fd.LowerOrderFunction;
existsOptions = true;
}
if (null != call && !call.IsHighOrder && call.IsParenthesesParamClass()) {
int pnum = call.GetParamNum();
if (pnum == 4) {
var name = call.GetParamId(0);
var type = call.GetParamId(1);
var paramsStr = call.GetParamId(2);
s_Type2Ids.TryGetValue(type, out var rty);
ParamsEnum paramsEnum = ParamsEnum.NoParams;
if (paramsStr.Length > 0 && char.IsNumber(paramsStr[0])) {
int.TryParse(paramsStr, out var v);
paramsEnum = (ParamsEnum)v;
}
else {
Enum.TryParse<ParamsEnum>(paramsStr, true, out paramsEnum);
}
bool isExternApi = id == "defexternapi";
var api = new ApiInfo { isExtern = isExternApi, ApiId = isExternApi ? externApiId : apiId, Name = name, Type = rty, Params = paramsEnum };
if (isExternApi)
++externApiId;
else
++apiId;
var pts = call.GetParam(3) as Dsl.FunctionData;
Debug.Assert(pts != null);
foreach (var p in pts.Params) {
string pt = ParseType(p, err, out var ct);
s_Type2Ids.TryGetValue(pt, out var ty);
api.ParamTypes.Add(new ApiParamType { Type = ty, Count = ct });
}
if (existsOptions) {
foreach (var syn in fd.Params) {
var fcall = syn as Dsl.FunctionData;
if (null != fcall) {
string pname = fcall.GetId();
if (pname == "minparamnum") {
int.TryParse(fcall.GetParamId(0), out api.MinParamNum);
}
}
}
}
if (api.MinParamNum == 0)
api.MinParamNum = api.ParamTypes.Count;
m_Apis.Add(name, api);
handled = true;
}
}
if (!handled) {
err.AppendFormat("expect defapi/defexternapi(name,ret_type,params_type,[param_type,...]); code:{0}, line:{1}", dslInfo.ToScriptString(false, Dsl.DelimiterInfo.Default), dslInfo.GetLine());
err.AppendLine();
}
}
else if (id == "defproto") {
bool handled = false;
var fd = dslInfo as Dsl.FunctionData;
var call = fd;
bool existsOptions = false;
Debug.Assert(fd != null);
if (fd.IsHighOrder && fd.LowerOrderFunction.IsParenthesesParamClass() && fd.HaveStatement()) {
call = fd.LowerOrderFunction;
existsOptions = true;
}
if (null != call && !call.IsHighOrder && call.IsParenthesesParamClass()) {
int pnum = call.GetParamNum();
if (pnum >= 4 && pnum <= 6) {
var name = call.GetParamId(0);
var type = call.GetParamId(1);
var paramsStr = call.GetParamId(2);
s_Type2Ids.TryGetValue(type, out var rty);
ParamsEnum paramsEnum = ParamsEnum.NoParams;
if (paramsStr.Length > 0 && char.IsNumber(paramsStr[0])) {
int.TryParse(paramsStr, out var v);
paramsEnum = (ParamsEnum)v;
}
else {
Enum.TryParse<ParamsEnum>(paramsStr, true, out paramsEnum);
}
var proto = new ProtoInfo { Name = name, Type = rty, Params = paramsEnum };
if (pnum >= 4) {
var ptsInt = call.GetParam(3) as Dsl.FunctionData;
Debug.Assert(ptsInt != null);
foreach (var p in ptsInt.Params) {
s_Type2Ids.TryGetValue(p.GetId(), out var ty);
proto.IntParams.Add(ty);
}
}
if (pnum >= 5) {
var ptsFloat = call.GetParam(4) as Dsl.FunctionData;
Debug.Assert(ptsFloat != null);
foreach (var p in ptsFloat.Params) {
s_Type2Ids.TryGetValue(p.GetId(), out var ty);
proto.FloatParams.Add(ty);
}
}
if (pnum >= 6) {
var ptsStack = call.GetParam(5) as Dsl.FunctionData;
Debug.Assert(ptsStack != null);
foreach (var p in ptsStack.Params) {
s_Type2Ids.TryGetValue(p.GetId(), out var ty);
proto.StackParams.Add(ty);
}
}
if (existsOptions) {
foreach (var syn in fd.Params) {
var fcall = syn as Dsl.FunctionData;
if (null != fcall) {
string pname = fcall.GetId();
if (pname == "minstackparamnum") {
int.TryParse(fcall.GetParamId(0), out proto.MinStackParamNum);
}
else if (pname == "manualstack") {
proto.ManualStack = fcall.GetParamId(0) == "true";
}
else if (pname == "doublefloat") {
proto.DoubleFloat = fcall.GetParamId(0) == "true";
}
}
}
}
if (proto.MinStackParamNum == 0) {
proto.MinStackParamNum = proto.StackParams.Count;
}
if (proto.ManualStack) {
proto.MinStackParamNum = 2;
proto.StackParams.Clear();
proto.StackParams.Add(TypeEnum.Int);//addr
proto.StackParams.Add(TypeEnum.Int);//size
}
m_Protos.Add(name, proto);
handled = true;
}
}
if (!handled) {
err.AppendFormat("expect defproto(name,ret_type,params_type,[int_param_type,...],[float_param_type,...],[stack_param_type,...]); code:{0}, line:{1}", dslInfo.ToScriptString(false, Dsl.DelimiterInfo.Default), dslInfo.GetLine());
err.AppendLine();
}
}
}
}
return err.ToString();
}
public string LoadStructDefine(string txt)
{
m_PredefinedStructInfos.Clear();
Dsl.DslFile file = new Dsl.DslFile();
var err = new StringBuilder();
if (file.LoadFromString(txt, (msg) => { err.AppendLine(msg); })) {
foreach (var dslInfo in file.DslInfos) {
var id = dslInfo.GetId();
if (id == "struct") {
var callData = dslInfo as Dsl.FunctionData;
Debug.Assert(callData != null);
if (!callData.IsValid())
continue;
var struInfo = ParseStruct(callData, err);
if (null != struInfo) {
m_PredefinedStructInfos.Add(struInfo.Name, struInfo);
if(!CalcStructOffsetAndSize(struInfo, out var errStr)) {
err.AppendFormat("{0}, code:{1}, line:{2}", errStr, callData.ToScriptString(false, Dsl.DelimiterInfo.Default), callData.GetLine());
err.AppendLine(errStr);
}
}
}
}
}
return err.ToString();
}
public bool Compile(string txt, out string errInfo)
{
Reset();
var err = new StringBuilder();
var file = new Dsl.DslFile();
file.SetNameTags(s_NameTags);
file.onGetToken = (ref Dsl.Common.DslAction dslAction, ref Dsl.Common.DslToken dslToken, ref string tok, ref short val, ref int line) => {
if (tok == "return") {
var oldCurTok = dslToken.getCurToken();
var oldLastTok = dslToken.getLastToken();
if (dslToken.PeekNextValidChar(0) == ';')
return false;
//insert backtick char
dslToken.setCurToken("`");
dslToken.setLastToken(oldCurTok);
dslToken.enqueueToken(dslToken.getCurToken(), dslToken.getOperatorTokenValue(), line);
dslToken.setCurToken(oldCurTok);
dslToken.setLastToken(oldLastTok);
return true;
}
else if (tok == ")") {
if (dslAction.PeekPairTypeStack(out var tag) == Dsl.Common.PairTypeEnum.PAIR_TYPE_PARENTHESES) {
if (tag > 0) {
var oldCurTok = dslToken.getCurToken();
var oldLastTok = dslToken.getLastToken();
char nextChar = dslToken.PeekNextValidChar(0);
if (nextChar == '{' || nextChar == ',' || nextChar == ';')
return false;
//insert backtick char
dslToken.setCurToken("`");
dslToken.setLastToken(oldCurTok);
dslToken.enqueueToken(dslToken.getCurToken(), dslToken.getOperatorTokenValue(), line);
dslToken.setCurToken(oldCurTok);
dslToken.setLastToken(oldLastTok);
return true;
}
}
}
return false;
};
file.onBeforeAddFunction = (ref Dsl.Common.DslAction dslAction, Dsl.StatementData statement) => {
//You can end the current statement here and start a new empty statement.
string fid = statement.GetId();
var func = statement.Last.AsFunction;
if (null != func) {
string lid = func.GetId();
if (func.HaveStatement()) {
if (string.IsNullOrEmpty(fid) || s_FirstLastKeyOfCompoundStatements.TryGetValue(fid, out var lastKey) && lastKey == lid) {
//End the current statement and start a new empty statement.
dslAction.endStatement();
dslAction.beginStatement();
return true;
}
}
}
return false;
};
file.onAddFunction = (ref Dsl.Common.DslAction dslAction, Dsl.StatementData statement, Dsl.FunctionData function) => {
//Do not change the program structure here. At this point, the "function" is still an empty function, and the real function information has not been filled in.
//The difference between this and "onBeforeAddFunction" is that the "function" is constructed and added to the function table of the current statement.
return false;
};
file.onBeforeEndStatement = (ref Dsl.Common.DslAction dslAction, Dsl.StatementData statement) => {
//The statement can be split here.
return false;
};
file.onEndStatement = (ref Dsl.Common.DslAction dslAction, ref Dsl.StatementData statement) => {
//The entire statement can be replaced here, but do not modify other parts of the program structure. The difference between this and "onBeforeEndStatement" is that
//the statement has been popped from the stack at this point, and the simplified statement will be added to the upper-level syntax unit in the future.
return false;
};
file.onBeforeBuildOperator = (ref Dsl.Common.DslAction dslAction, Dsl.Common.OperatorCategoryEnum category, string op, Dsl.StatementData statement) => {
//The statement can be split here.
return false;
};
file.onBuildOperator = (ref Dsl.Common.DslAction dslAction, Dsl.Common.OperatorCategoryEnum category, string op, ref Dsl.StatementData statement) => {
//The statement can be replaced here, but do not modify other syntax structures.
return false;
};
file.onSetFunctionId = (ref Dsl.Common.DslAction dslAction, string name, Dsl.StatementData statement, Dsl.FunctionData function) => {
//The statement can be split here.
string sid = statement.GetId();
var func = statement.Last.AsFunction;
if (null != func && statement.GetFunctionNum() > 1) {
if (s_SuccessorsOfCompoundStatements.TryGetValue(sid, out var successors) && !successors.Contains(name)) {
statement.Functions.Remove(func);
dslAction.endStatement();
dslAction.beginStatement();
var stm = dslAction.getCurStatement();
stm.AddFunction(func);
return true;
}
else if (s_CompoundStatements.Contains(name)) {
statement.Functions.Remove(func);
dslAction.endStatement();
dslAction.beginStatement();
var stm = dslAction.getCurStatement();
stm.AddFunction(func);
return true;
}
}
return false;
};
file.onBeforeBuildHighOrder = (ref Dsl.Common.DslAction dslAction, Dsl.StatementData statement, Dsl.FunctionData function) => {
//The statement can be split here.
return false;
};
file.onBuildHighOrder = (ref Dsl.Common.DslAction dslAction, Dsl.StatementData statement, Dsl.FunctionData function) => {
//The statement can be split here.
return false;
};
if (file.LoadFromString(txt, (msg) => { err.AppendLine(msg); })) {
int count = file.DslInfos.Count;
for (int i = 0; i < count; ++i) {
var call = file.DslInfos[i] as Dsl.FunctionData;
Debug.Assert(call != null);
CompileToplevelSyntax(call, err);
}
}
errInfo = err.ToString();
return string.IsNullOrEmpty(errInfo);
}
public void DumpAsm(StringBuilder txt)
{
int indent = 0;
txt.AppendLine("consts:");
++indent;
foreach (var pair in m_IntConstInfos) {
txt.AppendLine("{0}value:{1} type:{2} index:{3}", Literal.GetIndentString(indent), pair.Key, TypeEnum.Int, c_max_variable_table_size - 1 - pair.Value);
}
foreach (var pair in m_FltConstInfos) {
txt.AppendLine("{0}value:{1} type:{2} index:{3}", Literal.GetIndentString(indent), pair.Key, TypeEnum.Float, c_max_variable_table_size - 1 - pair.Value);
}
foreach (var pair in m_StrConstInfos) {
txt.AppendLine("{0}value:{1} type:{2} index:{3}", Literal.GetIndentString(indent), pair.Key, TypeEnum.String, c_max_variable_table_size - 1 - pair.Value);
}
--indent;
txt.AppendLine();
txt.AppendLine("globals:");
++indent;
foreach (var pair in m_VarInfos) {
string name = pair.Key;
if (pair.Value.TryGetValue(0, out var info)) {
txt.AppendLine("{0}name:{1} type:{2} count:{3} index:{4}", Literal.GetIndentString(indent), info.Name, info.Type, info.Count, info.Index);
++indent;
if (null != info.InitValues) {
foreach (var v in info.InitValues) {
txt.AppendLine("{0}value:{1}", Literal.GetIndentString(indent), v);
}
}
--indent;
}
}
--indent;
txt.AppendLine();
txt.AppendLine("locals:");
++indent;
foreach (var pair in m_VarInfos) {
string name = pair.Key;
foreach (var pair2 in pair.Value) {
int block = pair2.Key;
if (block > 0) {
var info = pair2.Value;
txt.AppendLine("{0}name:{1} type:{2} count:{3} index:{4} block:{5}", Literal.GetIndentString(indent), info.Name, info.Type, info.Count, info.Index, block);
}
}
}
--indent;
txt.AppendLine();
foreach (var hook in m_Hooks) {
if (txt.Length > 0)
txt.AppendLine();
txt.AppendLine("hook:{0}", hook.Name);
if (hook.ShareWith.Count > 0) {
txt.Append("share with:");
foreach (var name in hook.ShareWith) {
txt.Append(' ');
txt.Append(name);
}
txt.AppendLine();
}
txt.AppendLine("{");
++indent;
txt.AppendLine("{0}onenter {{", Literal.GetIndentString(indent));
++indent;
DumpAsm(txt, indent, hook.OnEnter);
--indent;
txt.AppendLine("{0}}}", Literal.GetIndentString(indent));
txt.AppendLine();
txt.AppendLine("{0}onexit {{", Literal.GetIndentString(indent));
++indent;
DumpAsm(txt, indent, hook.OnExit);
--indent;
txt.AppendLine("{0}}}", Literal.GetIndentString(indent));
--indent;
txt.AppendLine("}");
}
}
public void UploadToCppVM()
{
CppDbgScpInterface.CppDbgScp_ResetVM();
var comparer = new ReverseComparer<int>(Comparer<int>.Default);
var consts = new SortedDictionary<int, string>(comparer);
CollectConstInfo(TypeEnum.Int, consts);
foreach (var pair in consts) {
var strv = pair.Value;
TryParseLong(strv, out var v);
CppDbgScpInterface.CppDbgScp_AllocConstInt(v);
}
consts.Clear();
CollectConstInfo(TypeEnum.Float, consts);
foreach (var pair in consts) {
var strv = pair.Value;
TryParseDouble(strv, out var v);
CppDbgScpInterface.CppDbgScp_AllocConstFloat(v);
}
consts.Clear();
CollectConstInfo(TypeEnum.String, consts);
foreach (var pair in consts) {
var strv = pair.Value;
IntPtr str = Marshal.StringToHGlobalAnsi(strv);
CppDbgScpInterface.CppDbgScp_AllocConstString(str);
}
var globals = new SortedDictionary<int, VarInfo>();
CollectGlobalInfo(TypeEnum.Int, globals);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
CppDbgScpInterface.CppDbgScp_AllocGlobalInt(0);
}
else {
foreach (var strVal in info.InitValues) {
TryParseLong(strVal, out var v);
CppDbgScpInterface.CppDbgScp_AllocGlobalInt(v);
}
}
}
globals.Clear();
CollectGlobalInfo(TypeEnum.Float, globals);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
CppDbgScpInterface.CppDbgScp_AllocGlobalFloat(0);
}
else {
foreach (var strVal in info.InitValues) {
TryParseDouble(strVal, out var v);
CppDbgScpInterface.CppDbgScp_AllocGlobalFloat(v);
}
}
}
globals.Clear();
CollectGlobalInfo(TypeEnum.String, globals);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
IntPtr str = Marshal.StringToHGlobalAnsi(string.Empty);
CppDbgScpInterface.CppDbgScp_AllocGlobalString(str);
}
else {
foreach (var strVal in info.InitValues) {
IntPtr str = Marshal.StringToHGlobalAnsi(strVal);
CppDbgScpInterface.CppDbgScp_AllocGlobalString(str);
}
}
}
foreach (var hook in m_Hooks) {
IntPtr name = Marshal.StringToHGlobalAnsi(hook.Name);
IntPtr enterPtr = Marshal.AllocHGlobal(hook.OnEnter.Count * sizeof(int));
IntPtr exitPtr = Marshal.AllocHGlobal(hook.OnExit.Count * sizeof(int));
Marshal.Copy(hook.OnEnter.ToArray(), 0, enterPtr, hook.OnEnter.Count);
Marshal.Copy(hook.OnExit.ToArray(), 0, exitPtr, hook.OnExit.Count);
int hookId = CppDbgScpInterface.CppDbgScp_AddHook(name, enterPtr, hook.OnEnter.Count, exitPtr, hook.OnExit.Count);
LogSystem.Warn("hook:{0} id:{1}", hook.Name, hookId);
foreach (var other in hook.ShareWith) {
IntPtr otherFunc = Marshal.StringToHGlobalAnsi(other);
int rid = CppDbgScpInterface.CppDbgScp_ShareWith(hookId, otherFunc);
LogSystem.Warn("share with:{0} id:{1}", other, rid);
}
Marshal.FreeHGlobal(enterPtr);
Marshal.FreeHGlobal(exitPtr);
}
CppDbgScpInterface.CppDbgScp_StartVM();
}
public void SaveByteCode(string file)
{
//tag:DSBC 0x43425344
using (var sw = new BinaryWriter(new FileStream(file, FileMode.Create))) {
//tag
sw.Write(0x43425344);
//str table offset
sw.Write(0);
var comparer = new ReverseComparer<int>(Comparer<int>.Default);
var consts = new SortedDictionary<int, string>(comparer);
int constNum = CollectConstInfo(TypeEnum.Int, consts);
var strDict = new Dictionary<string, int>();
var strTable = new List<string>();
//int consts num
sw.Write(constNum);
foreach (var pair in consts) {
var strv = pair.Value;
TryParseLong(strv, out var v);
//int const
sw.Write(v);
}
consts.Clear();
constNum = CollectConstInfo(TypeEnum.Float, consts);
//float consts num
sw.Write(constNum);
foreach (var pair in consts) {
var strv = pair.Value;
TryParseDouble(strv, out var v);
//float const
sw.Write(v);
}
consts.Clear();
constNum = CollectConstInfo(TypeEnum.String, consts);
//string consts num
sw.Write(constNum);
foreach (var pair in consts) {
var strv = pair.Value;
//string const
sw.Write(AddStringTable(strv, strDict, strTable));
}
var globals = new SortedDictionary<int, VarInfo>();
int globalNum = CollectGlobalInfo(TypeEnum.Int, globals);
//int globals num
sw.Write(globalNum);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
sw.Write((long)0);
}
else {
foreach (var strVal in info.InitValues) {
TryParseLong(strVal, out var v);
sw.Write(v);
}
}
}
globals.Clear();
globalNum = CollectGlobalInfo(TypeEnum.Float, globals);
//float globals num
sw.Write(globalNum);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
sw.Write((double)0.0);
}
else {
foreach (var strVal in info.InitValues) {
TryParseDouble(strVal, out var v);
sw.Write(v);
}
}
}
globals.Clear();
globalNum = CollectGlobalInfo(TypeEnum.String, globals);
//string globals num
sw.Write(globalNum);
foreach (var pair in globals) {
var info = pair.Value;
if (null == info.InitValues) {
sw.Write(AddStringTable(string.Empty, strDict, strTable));
}
else {
foreach (var strVal in info.InitValues) {
sw.Write(AddStringTable(strVal, strDict, strTable));
}
}
}
sw.Write(m_Hooks.Count);
foreach (var hook in m_Hooks) {
sw.Write(AddStringTable(hook.Name, strDict, strTable));
sw.Write(hook.OnEnter.Count);
foreach (var v in hook.OnEnter) {
sw.Write(v);
}
sw.Write(hook.OnExit.Count);
foreach (var v in hook.OnExit) {
sw.Write(v);
}
sw.Write(hook.ShareWith.Count);
foreach (var other in hook.ShareWith) {
sw.Write(AddStringTable(other, strDict, strTable));
}
}
int strTableOffset = (int)sw.BaseStream.Position;
sw.Write(strTable.Count);
foreach (var str in strTable) {
sw.Write(str);
}
sw.Seek(sizeof(int), SeekOrigin.Begin);
sw.Write(strTableOffset);
sw.Close();
}
}
public void LoadByteCode(string file)
{
CppDbgScpInterface.CppDbgScp_Load(file);
}
private int CollectConstInfo(TypeEnum type, SortedDictionary<int, string> constInfos)
{
switch (type) {
case TypeEnum.Int:
foreach (var pair in m_IntConstInfos) {
constInfos.Add(pair.Value, pair.Key);
}
break;
case TypeEnum.Float:
foreach (var pair in m_FltConstInfos) {
constInfos.Add(pair.Value, pair.Key);
}
break;
case TypeEnum.String:
foreach (var pair in m_StrConstInfos) {
constInfos.Add(pair.Value, pair.Key);
}
break;
}
return constInfos.Count;
}
private int CollectGlobalInfo(TypeEnum type, SortedDictionary<int, VarInfo> varInfos)
{
int ct = 0;
foreach (var pair in m_VarInfos) {
var dict = pair.Value;
foreach (var pair2 in dict) {
int blockId = pair2.Key;
var info = pair2.Value;
if (blockId == 0 && info.Type == type) {
varInfos.Add(info.Index, info);
if (info.Count > 0)
ct += info.Count;
else
++ct;
}
}
}
return ct;
}
private int AddStringTable(string str, Dictionary<string, int> dict, List<string> table)
{
if (!dict.TryGetValue(str, out var ix)) {
ix = table.Count;
table.Add(str);
dict.Add(str, ix);
}
return ix;
}
private void DumpAsm(StringBuilder txt, int indent, List<int> codes)
{
for (int pos = 0; pos < codes.Count; ++pos) {
int opcode = codes[pos];
InsEnum op = DecodeInsEnum(opcode);
switch (op) {
case InsEnum.CALLEXTERN:
DumpCallExtern(txt, indent, codes, ref pos);
break;
case InsEnum.RET:
DumpRet(txt, indent, codes, ref pos);
break;
case InsEnum.JMP:
DumpJmp(txt, indent, codes, ref pos);
break;
case InsEnum.JMPIF:
DumpJmpIf(txt, indent, codes, ref pos);
break;
case InsEnum.JMPIFNOT:
DumpJmpIfNot(txt, indent, codes, ref pos);
break;
case InsEnum.INC:
DumpIncDec(txt, indent, codes, ref pos, "INC");
break;
case InsEnum.INCFLT:
DumpIncDec(txt, indent, codes, ref pos, "INCFLT");
break;
case InsEnum.INCV:
DumpIncDecVal(txt, indent, codes, ref pos, "INCV");
break;
case InsEnum.INCVFLT:
DumpIncDecVal(txt, indent, codes, ref pos, "INCVFLT");
break;
case InsEnum.DEC:
DumpIncDec(txt, indent, codes, ref pos, "DEC");
break;
case InsEnum.DECFLT:
DumpIncDec(txt, indent, codes, ref pos, "DECFLT");
break;
case InsEnum.DECV:
DumpIncDecVal(txt, indent, codes, ref pos, "DECV");
break;
case InsEnum.DECVFLT:
DumpIncDecVal(txt, indent, codes, ref pos, "DECVFLT");
break;
case InsEnum.MOV:
DumpMov(txt, indent, codes, ref pos, "MOV");
break;
case InsEnum.MOVFLT:
DumpMov(txt, indent, codes, ref pos, "MOVFLT");
break;
case InsEnum.MOVSTR:
DumpMov(txt, indent, codes, ref pos, "MOVSTR");
break;
case InsEnum.ARRGET:
DumpArrGet(txt, indent, codes, ref pos, "ARRGET");
break;
case InsEnum.ARRGETFLT:
DumpArrGet(txt, indent, codes, ref pos, "ARRGETFLT");
break;
case InsEnum.ARRGETSTR:
DumpArrGet(txt, indent, codes, ref pos, "ARRGETSTR");
break;
case InsEnum.ARRSET:
DumpArrSet(txt, indent, codes, ref pos, "ARRSET");
break;
case InsEnum.ARRSETFLT:
DumpArrSet(txt, indent, codes, ref pos, "ARRSETFLT");
break;
case InsEnum.ARRSETSTR:
DumpArrSet(txt, indent, codes, ref pos, "ARRSETSTR");
break;
case InsEnum.NEG:
DumpUnary(txt, indent, codes, ref pos, "NEG");
break;
case InsEnum.NEGFLT:
DumpUnary(txt, indent, codes, ref pos, "NEGFLT");
break;
case InsEnum.ADD:
DumpBinary(txt, indent, codes, ref pos, "ADD");
break;
case InsEnum.ADDFLT:
DumpBinary(txt, indent, codes, ref pos, "ADDFLT");
break;
case InsEnum.ADDSTR:
DumpBinary(txt, indent, codes, ref pos, "ADDSTR");
break;
case InsEnum.SUB:
DumpBinary(txt, indent, codes, ref pos, "SUB");
break;
case InsEnum.SUBFLT:
DumpBinary(txt, indent, codes, ref pos, "SUBFLT");
break;
case InsEnum.MUL:
DumpBinary(txt, indent, codes, ref pos, "MUL");
break;
case InsEnum.MULFLT:
DumpBinary(txt, indent, codes, ref pos, "MULFLT");
break;
case InsEnum.DIV:
DumpBinary(txt, indent, codes, ref pos, "DIV");
break;
case InsEnum.DIVFLT:
DumpBinary(txt, indent, codes, ref pos, "DIVFLT");
break;
case InsEnum.MOD:
DumpBinary(txt, indent, codes, ref pos, "MOD");
break;
case InsEnum.MODFLT:
DumpBinary(txt, indent, codes, ref pos, "MODFLT");
break;
case InsEnum.AND:
DumpBinary(txt, indent, codes, ref pos, "AND");
break;
case InsEnum.OR:
DumpBinary(txt, indent, codes, ref pos, "OR");
break;
case InsEnum.NOT:
DumpUnary(txt, indent, codes, ref pos, "NOT");
break;
case InsEnum.GT:
DumpBinary(txt, indent, codes, ref pos, "GT");
break;
case InsEnum.GTFLT:
DumpBinary(txt, indent, codes, ref pos, "GTFLT");
break;
case InsEnum.GTSTR:
DumpBinary(txt, indent, codes, ref pos, "GTSTR");
break;
case InsEnum.GE:
DumpBinary(txt, indent, codes, ref pos, "GE");
break;
case InsEnum.GEFLT:
DumpBinary(txt, indent, codes, ref pos, "GEFLT");
break;
case InsEnum.GESTR:
DumpBinary(txt, indent, codes, ref pos, "GESTR");
break;
case InsEnum.EQ:
DumpBinary(txt, indent, codes, ref pos, "EQ");
break;
case InsEnum.EQFLT:
DumpBinary(txt, indent, codes, ref pos, "EQFLT");
break;
case InsEnum.EQSTR:
DumpBinary(txt, indent, codes, ref pos, "EQSTR");
break;
case InsEnum.NE:
DumpBinary(txt, indent, codes, ref pos, "NE");
break;
case InsEnum.NEFLT:
DumpBinary(txt, indent, codes, ref pos, "NEFLT");
break;
case InsEnum.NESTR:
DumpBinary(txt, indent, codes, ref pos, "NESTR");
break;
case InsEnum.LE:
DumpBinary(txt, indent, codes, ref pos, "LE");
break;
case InsEnum.LEFLT:
DumpBinary(txt, indent, codes, ref pos, "LEFLT");
break;
case InsEnum.LESTR:
DumpBinary(txt, indent, codes, ref pos, "LESTR");
break;
case InsEnum.LT:
DumpBinary(txt, indent, codes, ref pos, "LT");
break;
case InsEnum.LTFLT:
DumpBinary(txt, indent, codes, ref pos, "LTFLT");
break;
case InsEnum.LTSTR:
DumpBinary(txt, indent, codes, ref pos, "LTSTR");
break;
case InsEnum.LSHIFT:
DumpBinary(txt, indent, codes, ref pos, "LSHIFT");
break;
case InsEnum.RSHIFT:
DumpBinary(txt, indent, codes, ref pos, "RSHIFT");
break;
case InsEnum.URSHIFT:
DumpBinary(txt, indent, codes, ref pos, "URSHIFT");