-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTzdCommandSystem.cpp
More file actions
1135 lines (1038 loc) · 44.8 KB
/
Copy pathTzdCommandSystem.cpp
File metadata and controls
1135 lines (1038 loc) · 44.8 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
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include "Res/TzdStrings.h"
#include "TzdDebugger.h"
#include "TzdCommandSystem.h"
#include "TzdExeCompiler.h"
// 包含标准库
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <filesystem>
#include <any>
#include <string>
#include <vector>
#include <iostream>
#include <set>
#include "Generated/TzdConsole.h"
#include "Generated/TzdBytecode.h"
#include "Generated/TzdJit.h"
TzdInterpreter* TzdCommandSystem::interpreter = nullptr;
TzdCommandSystem::TzdCommandSystem() : inputBuffer("") {
if (interpreter == nullptr) {
interpreter = new TzdInterpreter();
}
}
void TzdCommandSystem::registerCmd(std::string name, std::string cn, std::string fmt, std::string desc, std::string opts, std::function<void(const std::vector<std::string>&)> func) {
registry[name] = { name, cn, fmt, desc, opts, func };
}
void TzdCommandSystem::init() {
// 1. 定义一个辅助 Lambda,把脚本传入的 TzdValue 参数转回 string 参数
// 这样就能直接复用现有的 handleXxx 函数
auto argsToStrings = [](const std::vector<TzdValue>& tzdArgs) -> std::vector<std::string> {
std::vector<std::string> strArgs;
for (const auto& arg : tzdArgs) {
if (arg.type == TzdValue::STRING) {
strArgs.push_back(arg.sVal);
}
else if (arg.type == TzdValue::FLOAT) {
std::string s = std::to_string(arg.dVal);
s.erase(s.find_last_not_of('0') + 1, std::string::npos);
if (s.back() == '.') s.pop_back();
strArgs.push_back(s);
}
else if (arg.type == TzdValue::BOOL) {
strArgs.push_back(arg.bVal ? "true" : "false");
}
}
return strArgs;
};
// ============================================================
// StackTrace
// ============================================================
// [指令模式] StackTrace pid;
registerCmd("StackTrace",
"进程堆栈跟踪",
"StackTrace <PID|进程名>",
"输出调用栈。支持不区分大小写的进程名查找。",
"示例: StackTrace qq.exe;",
TzdCommandSystem::handleStackTrace);
// [函数模式] StackTrace("pid");
interpreter->registerNativeFunction("StackTrace", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
// 直接复用 handleStackTrace 逻辑
TzdCommandSystem::handleStackTrace(argsToStrings(args));
return TzdValue();
});
// ============================================================
// MemoryAsm
// ============================================================
// [指令模式]
registerCmd("MemoryAsm",
"内存反汇编分析",
"MemoryAsm <PID|ProcessName>",
"扫描目标进程的所有可执行代码段并翻译为汇编指令。",
"危险操作:可能导致目标进程短暂卡顿。",
TzdCommandSystem::handleMemoryAsm);
// [函数模式]
interpreter->registerNativeFunction("MemoryAsm", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
TzdCommandSystem::handleMemoryAsm(argsToStrings(args));
return TzdValue();
});
// ============================================================
// ScanFunc
// ============================================================
// [指令模式]
registerCmd("ScanFunc",
"扫描进程函数(支持PDB与GUI)",
"ScanFunc <PID|Name> [-m Module] [-p PdbPath] [-g]",
"通过特征码定位函数并进行符号还原。\n"
" -m: 指定目标模块名 (如: UnityPlayer.dll)\n"
" -p: 指定外部 PDB 符号路径\n"
" -g: 开启 DirectX 11 GUI 交互界面 (支持搜索/过滤)",
"示例: ScanFunc notepad.exe -m notepad.exe -g",
TzdCommandSystem::handleScanFunc);
// [函数模式] ScanFunc("notepad.exe", "-g");
interpreter->registerNativeFunction("ScanFunc", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
TzdCommandSystem::handleScanFunc(argsToStrings(args));
return TzdValue();
});
// ============================================================
// Demangle
// ============================================================
// [指令模式]
registerCmd("Demangle",
"C++符号去修饰",
"Demangle <MangledName>",
"将 MSVC 编译器的修饰名转换为可读的函数签名。",
"示例: Demangle ?init@System@@QAEXXZ",
TzdCommandSystem::handleDemangle);
// [函数模式]
interpreter->registerNativeFunction("Demangle", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
TzdCommandSystem::handleDemangle(argsToStrings(args));
return TzdValue();
});
// ============================================================
// PdbInfo
// ============================================================
// [指令模式]
registerCmd("PdbInfo",
"PDB文件分析工具",
"PdbInfo <PdbPath>",
"读取 PDB 文件头信息并尝试提取前 10 个公开符号。",
"示例: PdbInfo C:\\Symbols\\game.pdb",
TzdCommandSystem::handlePdbInfo);
// [函数模式] PdbInfo("C:/path.pdb");
interpreter->registerNativeFunction("PdbInfo", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
TzdCommandSystem::handlePdbInfo(argsToStrings(args));
return TzdValue();
});
// ============================================================
// Run (仅保留为系统指令,无需函数化)
// ============================================================
registerCmd("Run",
"运行脚本",
"Run <Code|FilePath>",
"解析并运行 TzdLang 脚本代码。",
"示例: Run \"a = gxxx 100; b = a ^ 2;\"",
TzdCommandSystem::handleRunScript);
// ============================================================
// Build (编译为独立可执行文件)
// ============================================================
registerCmd("Build",
"编译为独立可执行文件",
"Build <File.tzd|File.tzdc> [-o Out.exe] [--silent] [--no-jit] [--all-stdlib] [--codegen]",
"将 Tzd 源代码或字节码文件直接编译打包为独立的 Windows 原生可执行程序 (.exe)。",
"示例: Build main.tzd -o myapp.exe",
TzdCommandSystem::handleBuildExe);
// [函数模式] build("main.tzd", "-o myapp.exe");
interpreter->registerNativeFunction("build", [argsToStrings](const std::vector<TzdValue>& args) -> TzdValue {
TzdCommandSystem::handleBuildExe(argsToStrings(args));
return TzdValue(0.0);
});
}
void printRuntimeError(const std::string& msg, antlr4::Token* token) {
size_t line = token->getLine();
size_t charPositionInLine = token->getCharPositionInLine();
std::cerr << "==================================================" << std::endl;
std::cerr << "[Tzd 运行时错误] 行 " << line << ":" << charPositionInLine << std::endl;
std::cerr << "[错误详情] " << msg << std::endl;
antlr4::CharStream* stream = token->getInputStream();
if (stream) {
std::string fullText = stream->toString();
std::istringstream iss(fullText);
std::string codeLine;
size_t currentLine = 1;
while (std::getline(iss, codeLine)) {
if (!codeLine.empty() && codeLine.back() == '\r') codeLine.pop_back();
if (currentLine == line) {
std::cerr << "--------------------------------------------------" << std::endl;
std::cerr << " " << codeLine << std::endl;
std::cerr << " ";
for (size_t i = 0; i < charPositionInLine; ++i) {
if (i < codeLine.size() && codeLine[i] == '\t') std::cerr << '\t';
else std::cerr << ' ';
}
std::cerr << "^--- 这里" << std::endl;
break;
}
currentLine++;
}
}
std::cerr << "==================================================" << std::endl;
}
void TzdCommandSystem::handleRunScript(const std::vector<std::string>& args) {
if (args.empty()) return;
std::string code = args[0];
try {
interpreter->loadScript(code);
}
catch (const std::exception& e) {
std::cerr << "[Tzd 系统错误] " << e.what() << std::endl;
}
}
void TzdCommandSystem::handleBuildExe(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "================================================================\n"
<< " TzdLang 原生独立可执行程序编译器 (.exe AOT Generator)\n"
<< "================================================================\n"
<< " 用法: Build <脚本.tzd | 字节码.tzdc> [选项]\n\n"
<< " 基本选项:\n"
<< " -o <输出.exe> 指定输出可执行文件名\n"
<< " -s / --silent 生成程序静默运行\n"
<< " -O0 / -O1 / -O2 / -O3 指定优化级别(默认 -O2)\n"
<< " --opt=<0-3> 同上\n\n"
<< " AOT 机器码与依赖控制:\n"
<< " --buildCpu CPU-Only 模式:完全排除 CUDA/GPU/Torch\n"
<< " 生成的 .exe 纯静态链接,不依赖任何第三方 DLL\n"
<< " --codegen 仅生成对应的原生 C++ 源码包\n"
<< " --keep-cpp 保留编译过程中的原生 C++ 中间源码\n"
<< " --pe-stub 使用旧版 PE Overlay 存根模式(不推荐)\n"
<< "================================================================\n"
<< std::endl;
return;
}
std::string inputFile = "";
std::string outputFile = "";
tzd::ExeCompileOptions options;
// Default to TRUE AOT native machine code compilation!
options.targetMode = tzd::ExeTargetMode::NATIVE_MACHINE_CODE;
for (size_t i = 0; i < args.size(); ++i) {
std::string a = args[i];
if (a == "-o" && i + 1 < args.size()) {
outputFile = args[++i];
}
else if (a.rfind("-o=", 0) == 0 || a.rfind("--output=", 0) == 0) {
outputFile = a.substr(a.find('=') + 1);
}
else if (a == "-s" || a == "--silent") {
options.silent = true;
}
else if (a == "--no-jit" || a == "--noJit") {
options.enableJit = false;
}
else if (a == "--jit") {
options.enableJit = true;
}
else if (a == "--all-stdlib") {
options.bundleAllStdlib = true;
}
else if (a == "--no-bundle-stdlib") {
options.bundleStdlib = false;
}
else if (a == "--copy-dlls") {
options.copyDependencies = true;
}
else if (a == "--no-copy-dlls") {
options.copyDependencies = false;
}
else if (a == "--no-smart-deps") {
options.smartDeps = false;
}
// CPU-only mode: strip all GPU/CUDA/torch
else if (a == "--buildCpu" || a == "--build-cpu" || a == "--cpu-only" || a == "--cpuOnly") {
options.cpuOnly = true;
options.torchGpu = false;
}
// Force Torch integration
else if (a == "--torch" || a == "--torch-gpu") {
options.forceTorch = true;
options.torchGpu = true;
options.cpuOnly = false;
}
else if (a == "--torch-cpu") {
options.forceTorch = true;
options.torchGpu = false;
options.cpuOnly = true;
}
// Compiler toolchain selection: --llvm, --clang, --msvc, --gcc, --mingw
else if (a == "--llvm" || a == "--clang" || a == "--compiler=llvm" || a == "--compiler=clang") {
options.toolchain = tzd::CompilerToolchain::LLVM;
}
else if (a == "--msvc" || a == "--compiler=msvc") {
options.toolchain = tzd::CompilerToolchain::MSVC;
}
else if (a == "--gcc" || a == "--mingw" || a == "--compiler=gcc" || a == "--compiler=mingw") {
options.toolchain = tzd::CompilerToolchain::GCC;
}
else if (a == "--codegen") {
options.targetMode = tzd::ExeTargetMode::NATIVE_CODEGEN;
}
else if (a == "--keep-cpp" || a == "--keepCpp") {
options.keepCpp = true;
}
else if (a == "--pe-stub" || a == "--stub-overlay") {
options.targetMode = tzd::ExeTargetMode::STANDALONE_PE;
}
else if (a.rfind("--stub=", 0) == 0) {
options.customStubPath = a.substr(7);
}
else if (a.rfind("--opt=", 0) == 0 || a.rfind("--opt-level=", 0) == 0 || a.rfind("-O=", 0) == 0) {
options.optLevel = std::stoi(a.substr(a.find('=') + 1));
}
else if (a == "-O0") options.optLevel = 0;
else if (a == "-O1") options.optLevel = 1;
else if (a == "-O2") options.optLevel = 2;
else if (a == "-O3") options.optLevel = 3;
else if (!a.empty() && a[0] != '-') {
if (inputFile.empty()) {
inputFile = a;
}
}
}
if (inputFile.empty()) {
std::cerr << "[Tzd 编译错误] 未指定输入的 .tzd 源代码或 .tzdc 字节码文件。" << std::endl;
return;
}
auto stripQ = [](std::string s) {
if (s.size() >= 2 && (s.front() == '"' || s.front() == '\'') && s.front() == s.back()) {
return s.substr(1, s.size() - 2);
}
return s;
};
inputFile = stripQ(inputFile);
outputFile = stripQ(outputFile);
if (interpreter) {
options.extraIncludePaths = interpreter->m_includePaths;
}
// Silence the old per-step progress callback (we use the bar instead)
options.onProgress = nullptr;
std::cout << "================================================================\n"
<< " TzdLang AOT 独立机器码编译器 (代码/字节码 -> 原生机器码)\n"
<< "================================================================\n"
<< " 源文件 : " << std::filesystem::absolute(inputFile).string() << "\n";
if (!outputFile.empty())
std::cout << " 目标文件 : " << outputFile << "\n";
std::cout << " 优化级别 : -O" << options.optLevel << "\n"
<< " 构建模式 : " << (options.cpuOnly ? "CPU-Only 机器码(零外部 DLL)" : "全功能 AOT 机器码(智能依赖检测)") << "\n"
<< "================================================================\n";
std::cout.flush();
tzd::TzdExeCompiler compiler;
tzd::ExeCompileResult res;
std::string ext = std::filesystem::path(inputFile).extension().string();
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
try {
if (ext == ".tzdc") {
res = compiler.compileBytecode(inputFile, outputFile, options);
}
else {
res = compiler.compileTzd(inputFile, outputFile, options);
}
}
catch (const std::exception& e) {
std::cout << std::endl;
res.success = false;
res.errorMessage = std::string("Unhandled exception during compilation: ") + e.what();
}
catch (...) {
std::cout << std::endl;
res.success = false;
res.errorMessage = "Unknown fatal exception during compilation.";
}
if (res.success) {
std::string outDir = std::filesystem::path(res.outputExePath).parent_path().string();
double sizeKb = res.totalExeSizeBytes / 1024.0;
double sizeMb = sizeKb / 1024.0;
std::cout << "\n"
<< "================================================================\n"
<< " ✓ AOT 机器码编译成功!\n"
<< "================================================================\n"
<< " 源文件路径 : " << std::filesystem::absolute(inputFile).string() << "\n"
<< " 目标可执行 : " << res.outputExePath << "\n"
<< " 输出目录 : " << outDir << "\n";
if (sizeMb >= 1.0) {
std::cout << std::fixed << std::setprecision(2) << " 程序体积 : " << sizeMb << " MB (" << sizeKb << " KB)\n";
} else {
std::cout << std::fixed << std::setprecision(1) << " 程序体积 : " << sizeKb << " KB\n";
}
std::cout << " 优化级别 : -O" << options.optLevel << "\n"
<< " 依赖特性 : 零外部 DLL 依赖(纯静态原生 x86_64 机器码)\n"
<< " 构建架构 : " << (options.cpuOnly ? "CPU-Only Standalone" : "Native Standalone") << "\n"
<< " 编译耗时 : " << std::fixed << std::setprecision(2) << res.durationSeconds << " 秒\n"
<< "================================================================\n"
<< " 运行方式: " << res.outputExePath << "\n"
<< "================================================================\n"
<< std::endl;
}
else {
std::cerr << "\n"
<< "================================================================\n"
<< " ✗ 编译失败\n"
<< "================================================================\n"
<< " " << res.errorMessage << "\n"
<< "================================================================\n"
<< std::endl;
}
}
void TzdCommandSystem::handleDemangle(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "[Tzd] 用法: Demangle <修饰名字符串>" << std::endl;
return;
}
std::string rawName = args[0];
for (size_t i = 1; i < args.size(); ++i) rawName += args[i];
std::string readable = SymbolDemangler::demangle(rawName);
std::cout << "[原始] " << rawName << std::endl;
std::cout << "[结果] " << readable << std::endl;
}
void TzdCommandSystem::handlePdbInfo(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "[Tzd] 用法: PdbInfo <Pdb路径>" << std::endl;
return;
}
std::string path = args[0];
std::cout << "[Tzd] 正在读取 PDB: " << path << " ..." << std::endl;
PdbReader reader(path);
if (!reader.IsValid()) {
std::cout << "[Tzd] 错误: PDB 文件无效或无法打开。" << std::endl;
return;
}
std::cout << "[Tzd] PDB 文件校验通过 (MSF 格式有效)。" << std::endl;
std::vector<uint32_t> mockSections = { 0x1000, 0x2000, 0x3000, 0x4000, 0x5000 };
std::vector<PdbSymbol> symbols;
if (reader.ParsePublicSymbols(mockSections, symbols)) {
std::cout << "[Tzd] 成功解析符号表,共找到 " << symbols.size() << " 个公开符号。" << std::endl;
for (const auto& sym : symbols) {
std::cout << " [0x" << std::hex << std::setw(8) << std::setfill('0') << sym.rva << "] "
<< SymbolDemangler::demangle(sym.name) << std::dec << std::endl;
}
}
else {
std::cout << "[Tzd] 警告: 符号流解析失败。" << std::endl;
}
}
void TzdCommandSystem::handleScanFunc(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "[Tzd] 用法: ScanFunc <PID|进程名> [-m 模块名] [-p PDB路径] [-g (开启GUI)]" << std::endl;
return;
}
DWORD pid = 0;
std::string target = args[0];
std::string moduleName = "";
std::string pdbPath = "";
bool useGui = false;
for (size_t i = 1; i < args.size(); ++i) {
if (args[i] == "-m" && i + 1 < args.size()) {
moduleName = args[++i];
}
else if (args[i] == "-p" && i + 1 < args.size()) {
pdbPath = args[++i];
}
else if (args[i] == "-g") {
useGui = true;
}
}
try {
if (std::all_of(target.begin(), target.end(), ::isdigit)) {
pid = std::stoul(target);
}
else {
pid = TzdStackTrace::getPidByName(target);
}
}
catch (...) {
pid = TzdStackTrace::getPidByName(target);
}
if (pid == 0) {
std::cout << "[Tzd] 错误: 找不到目标进程: " << target << std::endl;
return;
}
std::cout << "[Tzd] 正在扫描进程: " << target << " (" << pid << ")" << std::endl;
if (!moduleName.empty()) std::cout << "[Tzd] 过滤模块: " << moduleName << std::endl;
if (!pdbPath.empty()) std::cout << "[Tzd] 符号文件: " << pdbPath << std::endl;
if (useGui) std::cout << "[Tzd] 模式: GUI 视图" << std::endl;
TzdFuncScanner scanner;
if (useGui) {
std::vector<ScanResult> results;
scanner.scanProcess(pid, moduleName, pdbPath, &results);
if (results.empty()) {
std::cout << "[Tzd] 警告: 未扫描到任何符合特征的函数,GUI 未启动。" << std::endl;
}
}
else {
scanner.scanProcess(pid, moduleName, pdbPath, nullptr);
}
std::cout << "\n[Tzd] 任务已提交,扫描完成。" << std::endl;
}
void TzdCommandSystem::handleMemoryAsm(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "[Tzd] 用法: MemoryAsm <PID|Name>;" << std::endl;
return;
}
DWORD pid = (isdigit(args[0][0])) ? std::stoul(args[0]) : TzdStackTrace::getPidByName(args[0]);
if (pid != 0) {
TzdMemoryAsm::analyzeAndDumpAsm(pid);
}
else {
std::cout << "[Tzd] 错误: 找不到目标进程。" << std::endl;
}
}
void TzdCommandSystem::handleStackTrace(const std::vector<std::string>& args) {
if (args.empty()) {
std::cout << "[Tzd] 错误: 请提供 PID 或进程名。用法: StackTrace <Target>;" << std::endl;
return;
}
std::string target = args[0];
DWORD pid = 0;
if (!target.empty() && std::all_of(target.begin(), target.end(), ::isdigit)) {
pid = std::stoul(target);
}
else {
pid = TzdStackTrace::getPidByName(target);
if (pid == 0) {
std::cout << "[Tzd] 错误: 找不到名为 '" << target << "' 的进程。" << std::endl;
return;
}
std::cout << "[Tzd] 已找到进程 " << target << ",对应 PID: " << pid << std::endl;
}
TzdStackTrace::dumpProcessStack(pid);
}
void TzdCommandSystem::printHelp(std::string cmdName) {
if (cmdName.empty()) {
std::cout << "\n--- " << APP_NAME << " 命令系统 (作者: " << AUTHOR << ") ---" << std::endl;
std::cout << "直接输入命令并以分号(;)结束。常用命令如下:" << std::endl;
for (auto const& [name, meta] : registry) {
std::cout << " > " << name << " \t [" << meta.chineseName << "]" << std::endl;
}
std::cout << "输入 'help <命令名>;' 查看具体详情。" << std::endl;
}
else {
if (registry.count(cmdName)) {
auto& m = registry[cmdName];
std::cout << "\n【命令中文名】: " << m.chineseName << std::endl;
std::cout << "【使用格式】 : " << m.format << std::endl;
std::cout << "【功能介绍】 : " << m.description << std::endl;
std::cout << "【子选项/扩展】: " << m.subOptions << std::endl;
}
else {
std::cout << "[Tzd] 未找到命令 '" << cmdName << "' 的帮助信息。" << std::endl;
}
}
}
void TzdCommandSystem::process(std::string input) {
// 1. 去除首尾空白
std::string trimmed = input;
size_t firstNonSpace = trimmed.find_first_not_of(" \t\r\n");
if (firstNonSpace == std::string::npos) return;
trimmed.erase(0, firstNonSpace);
size_t lastNonSpace = trimmed.find_last_not_of(" \t\r\n");
if (lastNonSpace != std::string::npos) trimmed.erase(lastNonSpace + 1);
if (trimmed.empty()) return;
// 2. 提取首个单词
size_t firstSpace = trimmed.find_first_of(" \t");
std::string cmdHead = (firstSpace == std::string::npos) ? trimmed : trimmed.substr(0, firstSpace);
// 3. 关键字保护
static const std::set<std::string> keywords = {
"fun", "class", "var", "if", "while", "for", "return", "ret",
"print", "new", "sin", "cos", "tan", "log"
};
bool isKeyword = keywords.count(cmdHead);
bool looksLikeFunctionCall = false;
if (trimmed.find('(') != std::string::npos) {
size_t openParen = trimmed.find('(');
std::string potentialName = trimmed.substr(0, openParen);
size_t lastChar = potentialName.find_last_not_of(" \t");
if (lastChar != std::string::npos) potentialName = potentialName.substr(0, lastChar + 1);
if (potentialName == cmdHead) {
looksLikeFunctionCall = true;
}
}
bool isSystemCmd = (cmdHead == "help") || (!isKeyword && !looksLikeFunctionCall && registry.count(cmdHead));
if (!isSystemCmd) {
// --- 脚本模式 ---
std::string scriptCode = trimmed;
if (scriptCode.size() >= 4 && scriptCode.substr(0, 4) == "Run ") {
scriptCode = scriptCode.substr(4);
size_t scriptStart = scriptCode.find_first_not_of(" \t");
if (scriptStart != std::string::npos) scriptCode.erase(0, scriptStart);
}
if (scriptCode.empty()) return;
std::vector<std::string> args = { scriptCode };
try {
handleRunScript(args);
}
catch (const std::exception& e) {
std::cerr << "[Tzd 运行时错误] " << e.what() << std::endl;
}
return;
}
// --- 系统指令模式 ---
std::vector<std::string> tokens;
std::string currentToken;
bool inQuotes = false;
for (size_t i = 0; i < trimmed.length(); ++i) {
char c = trimmed[i];
if (c == '"') { inQuotes = !inQuotes; continue; }
if (std::isspace(c) && !inQuotes) {
if (!currentToken.empty()) { tokens.push_back(currentToken); currentToken.clear(); }
}
else currentToken += c;
}
if (!currentToken.empty()) tokens.push_back(currentToken);
// 重定向处理
std::string outputFile = "";
auto it = std::find(tokens.begin(), tokens.end(), "=>");
if (it != tokens.end()) {
if (std::next(it) != tokens.end()) {
outputFile = *std::next(it);
tokens.erase(it, tokens.end());
}
else {
std::cerr << "[Tzd 语法错误] 重定向符号 '=>' 后缺少文件名。" << std::endl;
return;
}
}
if (tokens.empty()) return;
std::string head = tokens[0];
std::vector<std::string> sysArgs(tokens.begin() + 1, tokens.end());
std::ofstream outFile;
std::streambuf* coutBuf = nullptr;
if (!outputFile.empty()) {
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::filesystem::path finalPath = std::filesystem::path(buffer).parent_path() / outputFile;
outFile.open(finalPath, std::ios::out | std::ios::trunc);
if (outFile.is_open()) {
coutBuf = std::cout.rdbuf();
std::cout.rdbuf(outFile.rdbuf());
}
else {
std::cerr << "[Tzd 错误] 无法创建输出文件" << std::endl;
return;
}
}
if (head == "help") {
if (!sysArgs.empty()) printHelp(sysArgs[0]);
else printHelp();
}
else {
registry[head].handler(sysArgs);
}
if (coutBuf) {
std::cout.rdbuf(coutBuf);
outFile.close();
std::cout << "[Tzd] 输出已保存至: " << outputFile << std::endl;
}
}
void TzdCommandSystem::enterInteractiveMode() {
std::cout << R"(
____________________________________________________________________
| |
| _______ ________ __ _____ |
| |__ __|___ /\ \ / / / ____| _ |
| | | / / \ V / | | ___ _ __ _ __ | |_ _ __ ___ |
| | | / / > < | | / _ \| '_ \| '_ \| __| '__/ _ \ |
| | | / /__ / . \ | |___| (_) | | | | | | | |_| | | (_) | |
| |_| /_____|/_/ \_\ \_____\___/|_| |_|_| |_|\__|_| \___/ |
| |
|_____________________________________ Powered by TzdEngine _________|
)" << std::endl;
std::cout << " [System Info]" << std::endl;
std::cout << " * 版本号 : 1.0.0 Alpha" << std::endl;
std::cout << " * 构建于 : " << __DATE__ << " " << __TIME__ << std::endl;
std::cout << " * 开发者 : " << AUTHOR << std::endl;
std::cout << " * 架构 : " << (sizeof(void*) == 8 ? "x64 (64-bit)" : "x86 (32-bit)") << std::endl;
std::cout << "\n [Module Status]" << std::endl;
std::cout << " * StackTrace ... [OK]" << std::endl;
std::cout << " * MemoryAsm ... [OK]" << std::endl;
std::cout << " * PdbReader ... [OK]" << std::endl;
std::cout << " * GUI System ... [Standby]" << std::endl;
std::cout << "\n [Interactive Shell]" << std::endl;
std::cout << " 输入 'help' 查看完整命令列表。" << std::endl;
std::cout << " 输入 'exit' 退出程序。" << std::endl;
std::cout << " 支持多行输入 (直到大括号闭合或遇到分号)。" << std::endl;
std::cout << " --------------------------------------------------------------------\n" << std::endl;
// Use TzdConsole for interactive mode with syntax highlighting, history, clipboard
TzdConsole console;
console.run("Tzd> ", " > ", [this](const std::string& input) -> bool {
process(input);
return true;
});
}
void TzdCommandSystem::start(int argc, char* argv[]) {
init();
// 0. 命令行独立子命令: build / -b / --build
if (argc > 1 && (_stricmp(argv[1], "build") == 0 || _stricmp(argv[1], "-b") == 0 || _stricmp(argv[1], "--build") == 0)) {
std::vector<std::string> buildArgs;
for (int i = 2; i < argc; ++i) {
buildArgs.push_back(argv[i]);
}
handleBuildExe(buildArgs);
fflush(stdout); fflush(stderr);
TerminateProcess(GetCurrentProcess(), 0);
}
std::string runMainScript = "";
bool hasCustomFlags = false;
bool silentMode = false;
std::string debugHost = "127.0.0.1";
int debugPort = 0;
bool enableDebug = false;
bool explicitJit = false;
bool jitDebugRequested = false;
// 清理尾部引号的 Lambda
auto stripQuotes = [](const std::string& s) -> std::string {
std::string res = s;
if (res.size() >= 2 && res.front() == '"' && res.back() == '"') {
res = res.substr(1, res.size() - 2);
}
else if (res.size() >= 2 && res.front() == '\'' && res.back() == '\'') {
res = res.substr(1, res.size() - 2);
}
return res;
};
// 参数解析
for (int i = 1; i < argc; ++i) {
std::string arg = argv[i];
// 1. 工作目录: --setProjectDirectory="path" 或 --setpd="path"
if (arg.rfind("--setProjectDirectory=", 0) == 0 || arg.rfind("--setpd=", 0) == 0) {
hasCustomFlags = true;
size_t eqPos = arg.find('=');
std::string pathVal = stripQuotes(arg.substr(eqPos + 1));
if (!pathVal.empty()) {
try {
std::filesystem::current_path(pathVal);
interpreter->m_includePaths.push_back(std::filesystem::absolute(pathVal).string());
}
catch (const std::exception& e) {
std::fprintf(stderr, TzdCmd::WORK_DIR_WARN, e.what());
std::cerr << std::endl;
}
}
}
// 2. 库路径: --addLibraryDirectory="path1","path2"
else if (arg.rfind("--addLibraryDirectory=", 0) == 0) {
hasCustomFlags = true;
size_t eqPos = arg.find('=');
std::string valList = arg.substr(eqPos + 1);
// 逗号分隔路径支持
std::vector<std::string> paths;
std::string current;
bool insideQuotes = false;
for (size_t charIdx = 0; charIdx < valList.size(); ++charIdx) {
char c = valList[charIdx];
if (c == '"' || c == '\'') {
insideQuotes = !insideQuotes;
continue;
}
if (c == ',' && !insideQuotes) {
if (!current.empty()) {
paths.push_back(current);
current.clear();
}
}
else {
current += c;
}
}
if (!current.empty()) {
paths.push_back(current);
}
for (const auto& p : paths) {
std::string cleanPath = stripQuotes(p);
if (!cleanPath.empty()) {
interpreter->m_includePaths.push_back(std::filesystem::absolute(cleanPath).string());
}
}
}
// 3. 执行单 tzd 文件: --runMainTzd="path"
else if (arg.rfind("--runMainTzd=", 0) == 0) {
hasCustomFlags = true;
size_t eqPos = arg.find('=');
runMainScript = stripQuotes(arg.substr(eqPos + 1));
}
// 4. 静默模式 (隐藏 >>> 10 的输出)
else if (arg == "--silent" || arg == "-s") {
silentMode = true;
}
// 4b. JIT 控制模式
else if (arg == "--jit") {
interpreter->m_noJit = false;
explicitJit = true;
}
else if (arg == "--noJit" || arg == "--no-jit") {
interpreter->m_noJit = true;
explicitJit = false;
}
// JIT 优化级别: -O0, -O1, -O2, -O3, --opt-level=N, --opt=N, -O=N
else if (arg == "-O0" || arg == "--opt-level=0" || arg == "--opt=0" || arg == "-O=0") {
TzdJitEngine::setOptLevel(0);
interpreter->m_noJit = false;
explicitJit = true;
}
else if (arg == "-O1" || arg == "--opt-level=1" || arg == "--opt=1" || arg == "-O=1") {
TzdJitEngine::setOptLevel(1);
interpreter->m_noJit = false;
explicitJit = true;
}
else if (arg == "-O2" || arg == "--opt-level=2" || arg == "--opt=2" || arg == "-O=2") {
TzdJitEngine::setOptLevel(2);
interpreter->m_noJit = false;
explicitJit = true;
}
else if (arg == "-O3" || arg == "--opt-level=3" || arg == "--opt=3" || arg == "-O=3") {
TzdJitEngine::setOptLevel(3);
interpreter->m_noJit = false;
explicitJit = true;
}
else if (arg.rfind("--opt-level=", 0) == 0 || arg.rfind("--opt=", 0) == 0 || arg.rfind("-O=", 0) == 0) {
size_t eqPos = arg.find('=');
int lvl = std::stoi(arg.substr(eqPos + 1));
TzdJitEngine::setOptLevel(lvl);
interpreter->m_noJit = false;
explicitJit = true;
}
// 内联优化控制: --inline-threshold=N, --no-inline, --inline-depth=N, --inline-stmts=N
else if (arg.rfind("--inline-threshold=", 0) == 0) {
size_t eqPos = arg.find('=');
int th = std::stoi(arg.substr(eqPos + 1));
TzdJitEngine::setInlineThreshold(th);
}
else if (arg == "--no-inline" || arg == "--no-ast-inline") {
TzdJitEngine::setAstInliningEnabled(false);
TzdJitEngine::setInlineThreshold(0);
}
else if (arg.rfind("--inline-depth=", 0) == 0) {
size_t eqPos = arg.find('=');
TzdJitEngine::getConfig().maxInlineDepth = std::stoi(arg.substr(eqPos + 1));
}
else if (arg.rfind("--inline-stmts=", 0) == 0) {
size_t eqPos = arg.find('=');
TzdJitEngine::getConfig().maxInlineStmts = std::stoi(arg.substr(eqPos + 1));
}
// JIT 调试控制与内在函数
else if (arg == "--jit-debug" || arg == "--debug-jit") {
TzdJitEngine::setJitDebugEnabled(true);
interpreter->m_noJit = false;
jitDebugRequested = true;
}
else if (arg == "--no-jit-intrinsics" || arg == "--no-math-intrinsics") {
TzdJitEngine::getConfig().enableMathIntrinsics = false;
}
else if (arg == "--no-unroll" || arg == "--no-loop-unroll") {
TzdJitEngine::getConfig().enableLoopUnroll = false;
}
// 4c. 纯解释器模式 (--interpreter / --tree-walk):禁用 JIT 且禁用字节码 VM
else if (arg == "--interpreter" || arg == "--tree-walk") {
interpreter->m_noJit = true;
interpreter->m_forceInterpreter = true;
interpreter->m_useBytecodeVM = false;
}
// 4d. ANTLR4 解析耗时输出
else if (arg == "--antlrTime") {
interpreter->m_antlrTiming = true;
}
// 4e. BIGINT 运算各阶段耗时输出
else if (arg == "--bigTime") {
interpreter->m_bigTime = true;
}
// 4f. 强制使用GPU进行大数运算
else if (arg == "--forceGPU") {
interpreter->m_forceGPU = true;
}
// 4g. 强制使用CPU进行大数运算(禁用GPU)
else if (arg == "--forceCPU") {
interpreter->m_forceCPU = true;
}
// 4h. 实验性运算(CPU自研极限NTT大数算法)
else if (arg == "--experimental-compute" || arg == "--experimentalCompute") {
interpreter->m_experimentalCompute = true;
}
// 5. 调试端口/主机
else if (arg.rfind("--debug-port=", 0) == 0) {
size_t eqPos = arg.find('=');
debugPort = std::stoi(arg.substr(eqPos + 1));
enableDebug = true;
}
else if (arg.rfind("--debug-host=", 0) == 0) {
size_t eqPos = arg.find('=');
debugHost = stripQuotes(arg.substr(eqPos + 1));
enableDebug = true;
}
else if (arg.rfind("--debug-addr=", 0) == 0) {
size_t eqPos = arg.find('=');
std::string addr = stripQuotes(arg.substr(eqPos + 1));
size_t colon = addr.find(':');
if (colon != std::string::npos) {
debugHost = addr.substr(0, colon);
debugPort = std::stoi(addr.substr(colon + 1));
}
else {
debugPort = std::stoi(addr);
}
enableDebug = true;
}
// 6. 编译为字节码: --compile=file.tzd
else if (arg.rfind("--compile=", 0) == 0) {
size_t eqPos = arg.find('=');
std::string srcPath = stripQuotes(arg.substr(eqPos + 1));
try {
std::ifstream f(srcPath);
std::string code((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
f.close();
std::string outPath = srcPath.substr(0, srcPath.find_last_of('.')) + ".tzdc";
if (interpreter->compileToBytecodeFile(code, outPath)) {
std::cout << "Compiled: " << srcPath << " -> " << outPath << std::endl;
} else {
std::cerr << "Compile failed: syntax errors" << std::endl;
}
}
catch (const std::exception& e) {
std::cerr << "Compile error: " << e.what() << std::endl;
}
fflush(stdout); fflush(stderr);
TerminateProcess(GetCurrentProcess(), 0);
}
// 7. 执行字节码文件: --runbc=file.tzdc
else if (arg.rfind("--runbc=", 0) == 0) {
size_t eqPos = arg.find('=');
std::string bcPath = stripQuotes(arg.substr(eqPos + 1));
try {
interpreter->executeBytecodeFile(bcPath);
}
catch (const std::exception& e) {
std::cerr << "Bytecode execution error: " << e.what() << std::endl;