forked from Jenova-Framework/Jenova-Runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_interpreter.cpp
More file actions
1842 lines (1583 loc) · 82.6 KB
/
Copy pathscript_interpreter.cpp
File metadata and controls
1842 lines (1583 loc) · 82.6 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
/*-------------------------------------------------------------+
| |
| _________ ______ _ _____ |
| / / ____/ | / / __ \ | / / | |
| __ / / __/ / |/ / / / / | / / /| | |
| / /_/ / /___/ /| / /_/ /| |/ / ___ | |
| \____/_____/_/ |_/\____/ |___/_/ |_| |
| |
| Jenova Runtime |
| Developed by Hamid.Memar |
| |
+-------------------------------------------------------------*/
// Jenova SDK
#include "Jenova.hpp"
// Jenova Loader
#include "Jenova.Loader.h"
// AsmJIT
#define ASMJIT_STATIC
#include <AsmJIT/asmjit.h>
// Tiny C Compiler
#include <TinyCC/libtcc.h>
// Helper Macros
#define RESOLVE_PARAMETER(index) JenovaInterpreter::GetResolvedParameterPointer(objectPtr, functionParameters[index], functionParametersType[index + parameterOffset])
// Jenova Interpreter Implementation :: Boot
void JenovaInterpreter::BootInterpreter()
{
// Initialize Interpreter
if (!JenovaInterpreter::IsInterpreterInitialized())
{
if (!JenovaInterpreter::InitializeInterpreter())
{
jenova::Warning("Jenova Interpreter", "Jenova Interpreter Failed to Initialize!");
jenova::ExitWithCode(jenova::ErrorCode::INTERPRETER_INIT_FAILED);
}
}
// Load Module From Database
if (JenovaInterpreter::IsDatabaseAvailable(jenova::GlobalSettings::DefaultModuleDatabaseFile))
{
if (!JenovaInterpreter::DeployFromDatabase(jenova::GlobalSettings::DefaultModuleDatabaseFile))
{
jenova::Warning("Jenova Interpreter", "Module Cache Cannot Be Deployed, Possible Corruption, Rebuild Project.");
}
}
else
{
jenova::Warning("Jenova Interpreter", "Module Cache Cannot Be Found, Rebuild Project.");
}
}
// Jenova Interpreter Implementation :: Initialization/Release
bool JenovaInterpreter::InitializeInterpreter()
{
// Already Initialized
if (isInitialized) return true;
// Initialize Memory Module Loader
if (!JenovaLoader::Initialize()) return false;
// Initialize Mutex
interpreterMutex.instantiate();
// All Good
isInitialized = true;
return true;
}
bool JenovaInterpreter::IsInterpreterInitialized()
{
return isInitialized;
}
bool JenovaInterpreter::ReleaseInterpreter()
{
// It's Not Initialized
if (!isInitialized) return false;
// Initialize Memory Module Loader
if (!JenovaLoader::Release()) return false;
// Release Mutex
interpreterMutex.unref();
// All Good
return true;
}
// Jenova Interpreter Implementation :: Module Management
bool JenovaInterpreter::LoadModule(const uint8_t* moduleDataPtr, const size_t moduleSize, const jenova::SerializedData& metaData)
{
// Check If A Module Is Already Loaded
if (moduleBaseAddress) return false;
// Update Metadata And Configuration
if (!JenovaInterpreter::UpdateConfigurationsFromMetaData(metaData))
{
jenova::Error("Jenova Interpreter", "Failed to Update Interpreter Configurations from Metadata.");
return false;
}
// Create Loader Flags
jenova::LoaderFlags loaderFlags = 0;
if (executeInDebugMode && !QUERY_ENGINE_MODE(Editor)) loaderFlags |= jenova::LoaderFlag::LoadInDebugMode;
// Load And Map Module to Memory
if (hasDebugInformation)
{
// Load Module As Virtual
moduleHandle = JenovaLoader::LoadModuleAsVirtual((void*)moduleDataPtr, moduleSize, "Jenova.Module.dll", moduleDiskPath.c_str(), loaderFlags);
// Load Debug Symbol If MSE Disabled
if (!jenova::GlobalStorage::UseManagedSafeExecution)
{
jenova::LoadSymbolForModule(jenova::GetCurrentProcessHandle(), jenova::LongWord(moduleHandle), moduleDiskPath + "\\Jenova.Module.pdb", moduleSize);
}
}
else
{
// Load Module As Regular
moduleHandle = JenovaLoader::LoadModule((void*)moduleDataPtr, moduleSize, loaderFlags);
}
if (!moduleHandle) return false;
// Get Module Base Address
moduleBaseAddress = JenovaLoader::GetModuleBaseAddress(moduleHandle);
if (!moduleBaseAddress) return false;
// Update Property Storage From Metadata
if (!JenovaInterpreter::UpdatePropertyStorageFromMetaData(metaData))
{
jenova::Error("Jenova Interpreter", "Failed to Update Interpreter Property Database from Metadata.");
return false;
}
// Resolve And Load Addon Modules
if (!jenova::ResolveAndLoadAddonModulesAtRuntime())
{
jenova::Error("Jenova Interpreter", "Failed to Resolve and Load Addon Modules.");
return false;
}
// Solve Functions Inside Module
if(!jenova::InitializeExtensionModule("InitializeJenovaModule", moduleHandle, jenova::ModuleCallMode::Virtual))
{
jenova::Error("Jenova Interpreter", "Failed to Initialize Jenova Module API Solver.");
return false;
}
// Call Module Boot Event If Exists
if (!jenova::CallModuleEvent(jenova::GlobalSettings::JenovaModuleBootEventName, moduleHandle, jenova::ModuleCallMode::Virtual))
{
jenova::Warning("Jenova Interpreter", "Module Boot Event Failed. Unexpected Behaviors May Occur.");
}
// Enable Execution
allowExecution = true;
// All Good
return true;
}
bool JenovaInterpreter::LoadModule(const jenova::BuildResult& buildResult)
{
return LoadModule(buildResult.builtModuleData.data(), buildResult.builtModuleData.size(), buildResult.moduleMetaData);
}
bool JenovaInterpreter::ReloadModule(const uint8_t* moduleDataPtr, const size_t moduleSize, const jenova::SerializedData& metaData)
{
// Reload Not Supported In Debug Mode
if (executeInDebugMode) return false;
// Unload Module
if (!UnloadModule()) return false;
// Load Module
return LoadModule(moduleDataPtr, moduleSize, metaData);
}
bool JenovaInterpreter::ReloadModule(const jenova::BuildResult& buildResult)
{
return ReloadModule(buildResult.builtModuleData.data(), buildResult.builtModuleData.size(), buildResult.moduleMetaData);
}
bool JenovaInterpreter::UnloadModule()
{
// Adjust Agressive Mode [Disable For All For Now]
JenovaLoader::SetAgressiveMode(!(QUERY_ENGINE_MODE(Editor) || QUERY_ENGINE_MODE(Debug) || QUERY_ENGINE_MODE(Runtime)));
// Flush Property Storage
if (!JenovaInterpreter::FlushPropertyStorage())
{
jenova::Error("Jenova Interpreter", "Failed to Flush Interpreter Property Database.");
return false;
}
// Call Module Shutdown Event If Exists
if (!jenova::CallModuleEvent(jenova::GlobalSettings::JenovaModuleShutdownEventName, moduleHandle, jenova::ModuleCallMode::Virtual))
{
jenova::Warning("Jenova Interpreter", "Module Shutdown Event Failed. Unexpected Behaviors May Occur.");
}
// If Debug Mode is Activated Unload Module Loaded From Disk
if (executeInDebugMode) return jenova::ReleaseTemporaryModuleCache();
// Unload Module
if (!moduleHandle) return false;
if (!moduleBaseAddress) return false;
if (!JenovaLoader::ReleaseModule(moduleHandle)) return false;
moduleHandle = nullptr;
moduleBaseAddress = 0;
moduleMetaData = "{}";
// All Good
return true;
}
bool JenovaInterpreter::LoadDebugSymbol(const std::string symbolFilePath)
{
return jenova::LoadSymbolForModule(jenova::GetCurrentProcessHandle(), moduleBaseAddress, symbolFilePath.c_str(), moduleBinarySize);
}
intptr_t JenovaInterpreter::GetModuleBaseAddress()
{
return moduleBaseAddress;
}
jenova::FunctionList JenovaInterpreter::GetFunctionsList(std::string& scriptUID)
{
try
{
// Create Function List
jenova::FunctionList functionNames;
// Get Script Metadata by UID
nlohmann::json scriptMetadata = moduleMetaData["Scripts"][scriptUID]["methods"];
// Add Functions to List
for (const auto& functionName : scriptMetadata.items()) functionNames.push_back(functionName.key());
// Return List
return functionNames;
}
catch (const std::exception&)
{
return jenova::FunctionList();
}
}
jenova::FunctionAddress JenovaInterpreter::GetFunctionAddress(const std::string& functionName, std::string& scriptUID)
{
try
{
// Validate Script UID
if (!moduleMetaData["Scripts"].contains(scriptUID)) return 0;
// Get Script Metadata by UID
nlohmann::json scriptMetadata = moduleMetaData["Scripts"][scriptUID]["methods"];
// Get Function Address
for (const auto& funcName : scriptMetadata.items())
{
if (funcName.key() == functionName)
{
// Calculate Offset + BaseAddress And Return
jenova::FunctionAddress functionOffset = funcName.value()["Offset"].get<jenova::FunctionAddress>();
return moduleBaseAddress + functionOffset;
}
}
}
catch (const std::exception&)
{
// Error Happened
return 0;
}
// Function Was Not Found
return 0;
}
jenova::ParameterTypeList JenovaInterpreter::GetFunctionParameters(const std::string& functionName, std::string& scriptUID)
{
try
{
// Validate Script UID
if (!moduleMetaData["Scripts"].contains(scriptUID)) return jenova::ParameterTypeList();
// Get Script Metadata by UID
nlohmann::json scriptMetadata = moduleMetaData["Scripts"][scriptUID]["methods"];
// Get Function Parameters
for (const auto& funcName : scriptMetadata.items())
{
if (funcName.key() == functionName)
{
jenova::ParameterTypeList parameterTypes;
int paramCount = funcName.value()["ParamCount"].get<int>();
for (int i = 1; i <= paramCount; ++i) parameterTypes.push_back(funcName.value()[jenova::Format("Param%02d", i)].get<std::string>());
return parameterTypes;
}
}
}
catch (const std::exception&)
{
// Error Happened
return jenova::ParameterTypeList();
}
// Not Found
return jenova::ParameterTypeList();
}
std::string JenovaInterpreter::GetFunctionReturn(const std::string& functionName, std::string& scriptUID)
{
try
{
// Validate Script UID
if (!moduleMetaData["Scripts"].contains(scriptUID)) return "Unknown";
// Get Script Metadata by UID
nlohmann::json scriptMetadata = moduleMetaData["Scripts"][scriptUID]["methods"];
// Get Function Return Type
for (const auto& funcName : scriptMetadata.items())
{
if (funcName.key() == functionName)
{
return funcName.value()["ReturnType"].get<std::string>();
}
}
}
catch (const std::exception&)
{
// Error Happened
return "Unknown";
}
// Not Found
return "Unknown";
}
uintptr_t JenovaInterpreter::GetResolvedParameterPointer(const godot::Object* objectPtr, const godot::Variant* functionParameter, const std::string& parameterType)
{
void* valueAddress = (void*)functionParameter;
return reinterpret_cast<uintptr_t>(valueAddress);
}
bool JenovaInterpreter::IsFunctionReturnable(const std::string& returnType)
{
if (returnType == "void") return false;
return true;
}
jenova::ScriptPropertyContainer JenovaInterpreter::GetPropertyContainer(std::string& scriptUID)
{
try
{
// Create Property Container
jenova::ScriptPropertyContainer propertyContainer;
// Check If Script has Database
if (!moduleMetaData["Scripts"][scriptUID].contains("database")) return propertyContainer;
// Get Script Database by UID
nlohmann::json scriptDatabase = moduleMetaData["Scripts"][scriptUID]["database"];
// Check If Script has Properties
if (!scriptDatabase.contains("properties")) return propertyContainer;
// Collect & Create Properties
propertyContainer = jenova::CreatePropertyContainerFromMetadata(scriptDatabase["properties"].dump(), scriptUID);
// Return List
return propertyContainer;
}
catch (const std::exception&)
{
return jenova::ScriptPropertyContainer();
}
}
Variant JenovaInterpreter::CallFunction(const godot::Object* objectPtr, const std::string& functionName, std::string& scriptUID, const Variant** functionParameters, const int functionParametersCount)
{
// Validate Module
if (!allowExecution) return Variant("ERROR::EXECUTION_DENIED");
if (!moduleHandle || !moduleBaseAddress) return Variant("ERROR::INVALID_MODULE");
// Create Profiler Checkpoint [Not Required For Now]
/* JenovaTinyProfiler::CreateCheckpoint("InterpreterCallFunction"); */
// Verbose
jenova::VerboseByID(__LINE__, "Interpreter Calling Function [%s] From Script [%s] On Object [%p]", functionName.c_str(), scriptUID.c_str(), objectPtr);
// Get Function Address Offset
jenova::FunctionAddress functionAddress = JenovaInterpreter::GetFunctionAddress(functionName, scriptUID);
if (!functionAddress) return Variant("ERROR::FUNCTION_ADDRESS_NOT_FOUND");
// Get Function Return Type
std::string functionReturnType = JenovaInterpreter::GetFunctionReturn(functionName, scriptUID);
if (functionReturnType == "Unknown") return Variant("ERROR::FUNCTION_RETURN_TYPE_NOT_FOUND");
// Get Function Parameters Type
jenova::ParameterTypeList functionParametersType = JenovaInterpreter::GetFunctionParameters(functionName, scriptUID);
if (functionParametersType.size() == 0) return Variant("ERROR::FUNCTION_PARAMETERS_TYPE_NOT_FOUND");
// Determine and Set Flags
bool callMustReturn = JenovaInterpreter::IsFunctionReturnable(functionReturnType);
bool callHasParameters = !(functionParametersType.size() == 1 && functionParametersType[0] == "void");
bool needsPassingOwner = functionParametersType[0] == "jenova::sdk::Caller*";
// Create Final Parameter List
std::vector<uintptr_t> resolvedParameters;
// Pass Owner
std::shared_ptr<jenova::ScriptCaller> scriptHandle = nullptr;
if (needsPassingOwner)
{
scriptHandle = std::make_shared<jenova::ScriptCaller>(objectPtr);
resolvedParameters.push_back(reinterpret_cast<uintptr_t>(scriptHandle.get()));
}
// Add Godot Parameters
int parameterOffset = needsPassingOwner ? 1 : 0;
for (size_t i = 0; i < functionParametersCount; i++) resolvedParameters.push_back(RESOLVE_PARAMETER(i));
// Calculate Final Size
int resolvedParametersCount = callHasParameters ? resolvedParameters.size() : 0;
// Generate Code And Call Using Backends
if (interpreterBackend == jenova::InterpreterBackend::AsmJIT)
{
try
{
// Create a JIT Runtime
asmjit::JitRuntime jitRuntime;
// Create Code Holder
asmjit::CodeHolder code;
code.init(jitRuntime.environment());
// Assembler to Emit Code
asmjit::x86::Assembler assembler(&code);
// Calculate Stack Size
int stackAlignmentSize = 0x38; int stackAdjusterSize = 0x08;
if (resolvedParametersCount > 4) stackAlignmentSize += (resolvedParametersCount - 4) * stackAdjusterSize;
// Generate Assembly Caller Code
{
// Push Required Stack Size
assembler.sub(asmjit::x86::rsp, stackAlignmentSize);
// Pushing Parameters
if (resolvedParametersCount > 0)
{
// Microsoft Windows x64 Architecture
if (QUERY_PLATFORM(Windows))
{
// Handle First 4 Parameters in Registers
if (resolvedParametersCount > 0) assembler.mov(asmjit::x86::rcx, resolvedParameters[0]);
if (resolvedParametersCount > 1) assembler.mov(asmjit::x86::rdx, resolvedParameters[1]);
if (resolvedParametersCount > 2) assembler.mov(asmjit::x86::r8, resolvedParameters[2]);
if (resolvedParametersCount > 3) assembler.mov(asmjit::x86::r9, resolvedParameters[3]);
// Push Remaining Parameters Directly to Stack
for (int i = 4; i < resolvedParametersCount; ++i)
{
int offset = 32 + ((i - 4) * stackAdjusterSize); // Offset starts at 32 bytes after the 4th parameter
assembler.mov(asmjit::x86::qword_ptr(asmjit::x86::rsp, offset), resolvedParameters[i]);
}
}
// System V AMD64 ABI Architecture
if (QUERY_PLATFORM(Linux))
{
// Handle First 6 Parameters in Registers
if (resolvedParametersCount > 0) assembler.mov(asmjit::x86::rdi, resolvedParameters[0]);
if (resolvedParametersCount > 1) assembler.mov(asmjit::x86::rsi, resolvedParameters[1]);
if (resolvedParametersCount > 2) assembler.mov(asmjit::x86::rdx, resolvedParameters[2]);
if (resolvedParametersCount > 3) assembler.mov(asmjit::x86::rcx, resolvedParameters[3]);
if (resolvedParametersCount > 4) assembler.mov(asmjit::x86::r8, resolvedParameters[4]);
if (resolvedParametersCount > 5) assembler.mov(asmjit::x86::r9, resolvedParameters[5]);
// Push Remaining Parameters Directly to Stack
for (int i = 6; i < resolvedParametersCount; ++i)
{
int offset = 32 + ((i - 6) * stackAdjusterSize); // Offset starts at 32 bytes after the 6th parameter
assembler.mov(asmjit::x86::qword_ptr(asmjit::x86::rsp, offset), resolvedParameters[i]);
}
}
}
// Push Calling Address and Call
assembler.mov(asmjit::x86::rax, functionAddress);
assembler.call(asmjit::x86::rax);
// Pop Required Stack Size And Return
assembler.add(asmjit::x86::rsp, stackAlignmentSize);
assembler.ret();
}
// Execution
if (callMustReturn)
{
// Typedef for the Generated Function
typedef Variant(*CallerFunction)();
// Allocate and Run Generated Code
CallerFunction callerFunction = nullptr;
jitRuntime.add(&callerFunction, &code);
// Call the JIT-generated Function
Variant result = callerFunction();
// Release Generated Code When Done
jitRuntime.release(callerFunction);
// Return the Result as a Variant
if (result.get_type() == Variant::NIL) return Variant("RESULT::VOID");
return result;
}
else
{
// Void Call
typedef void(*CallerFunction)();
CallerFunction callerFunction = nullptr;
jitRuntime.add(&callerFunction, &code);
callerFunction();
jitRuntime.release(callerFunction);
return Variant(true);
}
}
catch (const std::exception&)
{
// If Failed, Return False
return Variant("ERROR::CALL_FAILED");
}
}
if (interpreterBackend == jenova::InterpreterBackend::TinyCC)
{
// Create Pointer List
jenova::PointerList ptrList;
// Generate Caller Code
std::string interpreterCallerCode;
interpreterCallerCode += jenova::Format("struct Variant { unsigned char opaque[%d]; };\n", GODOT_CPP_VARIANT_SIZE);
interpreterCallerCode += "typedef struct Variant Variant;\n";
interpreterCallerCode += "Variant* MakeVariant(void*, char*);\n";
interpreterCallerCode += "void* interpreter_call()\n";
interpreterCallerCode += "{\n";
interpreterCallerCode += "typedef " + jenova::ResolveReturnTypeForJIT(functionReturnType) + "(*function_t)(";
if (needsPassingOwner) interpreterCallerCode += "void*";
for (size_t i = 0; i < functionParametersCount; i++)
{
if (i == 0 && needsPassingOwner) interpreterCallerCode += ",";
interpreterCallerCode += jenova::ResolveVariantTypeAsString(functionParameters[i]);
if (i != functionParametersCount - 1) interpreterCallerCode += ",";
}
interpreterCallerCode += ");\n";
interpreterCallerCode += jenova::Format("function_t _func = (function_t)0x%llx;\n", functionAddress);
if (callMustReturn) interpreterCallerCode += jenova::ResolveReturnTypeForJIT(functionReturnType) + " result = ";
interpreterCallerCode += "_func(";
if (needsPassingOwner) interpreterCallerCode += jenova::Format("(void*)0x%llx", resolvedParameters[0]);
for (size_t i = 0; i < functionParametersCount; i++)
{
if (i == 0 && needsPassingOwner) interpreterCallerCode += ",";
interpreterCallerCode += jenova::ResolveVariantValueAsString(functionParameters[i], ptrList);
if (i != functionParametersCount - 1) interpreterCallerCode += ",";
}
interpreterCallerCode += ");\n";
if (callMustReturn) interpreterCallerCode += "return MakeVariant(&result,\"" + functionReturnType + "\");\n";
else interpreterCallerCode += "return 0;\n";
interpreterCallerCode += "}";
// Initialize TCC Compiler
TCCState* tcc = tcc_new();
if (!tcc)
{
jenova::Error("Interpreter Backend", "Failed to Initialize JIT Interpreter.");
return Variant(false);
}
// Create Error/Warning Reporter
if (jenova::GlobalStorage::DeveloperModeActivated)
{
jenova::VerboseByID(__LINE__, "JIT Execution Code : \n%s", interpreterCallerCode.c_str());
auto tcc_error_handler = [](void* opaque, const char* msg) -> void
{
jenova::Error("Interpreter Backend", "%s", msg);
};
tcc_set_error_func(tcc, nullptr, tcc_error_handler);
}
// Configure TCC Compiler
tcc_set_output_type(tcc, TCC_OUTPUT_MEMORY);
tcc_set_options(tcc, "-nostdlib");
// Add Symbols
tcc_add_symbol(tcc, "memmove", reinterpret_cast<const void*>(&jenova::RelocateMemory));
tcc_add_symbol(tcc, "MakeVariant", reinterpret_cast<const void*>(&jenova::MakeVariantFromReturnType));
// Compile Generated Code
if (tcc_compile_string(tcc, interpreterCallerCode.c_str()) == -1)
{
jenova::Error("Interpreter Backend", "Failed to Compile Interpreter Code.");
for (void* ptr : ptrList) if (ptr) delete ptr;
tcc_delete(tcc);
return Variant(false);
}
// Prepare For Execution
if (tcc_relocate(tcc, TCC_RELOCATE_AUTO) < 0) {
jenova::Error("Interpreter Backend", "Failed to Resolve Interpreter Code.");
for (void* ptr : ptrList) if (ptr) delete ptr;
tcc_delete(tcc);
return Variant(false);
}
// Get Compiled Caller Function
using MetaCallerType = Variant*(*)();
MetaCallerType interpreterCaller = (MetaCallerType)tcc_get_symbol(tcc, "interpreter_call");
if (!interpreterCaller)
{
jenova::Error("Interpreter Backend", "Failed to Get Interpreter JIT Caller.");
for (void* ptr : ptrList) if (ptr) delete ptr;
tcc_delete(tcc);
return Variant(false);
}
// Execute Caller
Variant* result = interpreterCaller();
// Release Allocated Values
for (void* ptr : ptrList) if (ptr) delete ptr;
ptrList.clear();
// Clean up
tcc_delete(tcc);
// Process Result
if (callMustReturn)
{
if (result)
{
Variant finalResult(*result);
delete result;
return finalResult;
}
}
return Variant(true);
}
if (interpreterBackend == jenova::InterpreterBackend::AkiraJIT)
{
// Removed
}
if (interpreterBackend == jenova::InterpreterBackend::SecureAngel)
{
// Removed
}
// No Valid Backend
return Variant("ERROR::INVALID_INTERPRETER_BACKEND");
}
void JenovaInterpreter::SetExecutionState(bool executionState)
{
// Set Execution State
allowExecution = executionState;
}
jenova::SerializedData JenovaInterpreter::GenerateModuleMetadata(const std::string& mapFilePath, const jenova::ModuleList& scriptModules, const jenova::BuildResult& buildResult)
{
// Windows Compilers
#ifdef TARGET_PLATFORM_WINDOWS
// Microsoft Visual C++ Map Parser
if (buildResult.compilerModel == jenova::CompilerModel::MicrosoftCompiler || buildResult.compilerModel == jenova::CompilerModel::ClangLLVMCompiler)
{
try
{
// Create JSON Serializer
nlohmann::json serializer;
// Variables to Store __ImageBase
uint64_t imageBaseAddress = 0;
// Serialize Script Modules
for (const auto& scriptModule : scriptModules) serializer["Scripts"][AS_STD_STRING(scriptModule.scriptUID)] = nlohmann::json::object();
// Open Map File
if (!std::filesystem::exists(mapFilePath))
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Open Map File.");
return jenova::SerializedData();
}
std::ifstream mapfileReader(mapFilePath);
if (!mapfileReader.is_open())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Read Map File.");
return jenova::SerializedData();
}
// Parse Map File And Generate Metadata
if (buildResult.compilerModel == jenova::CompilerModel::MicrosoftCompiler)
{
// Regex Patterns
std::regex imageBasePattern(R"(^\s*\d+:\d+\s+__ImageBase\s+([0-9A-Fa-f]{16}))");
std::regex jnvNameOffsetFuncPattern(R"(^\s*\d+:(\w+)\s+\?(.*?)@JNV_([a-f0-9]+)@@.*\s+([0-9A-Fa-f]{16})\s+f\s+.*$)");
std::regex jnvNameOffsetPropPattern(R"(^\s*\d+:(\w+)\s+\?(.*?)@JNV_([a-f0-9]+)@@.*\s+([0-9A-Fa-f]{16})\s+\s+.*$)");
std::regex jnvMangledNamePattern(R"(\?\w+@JNV_\w+@@\S+)");
// Process Parsing
std::string mapFileLine; std::smatch match;
while (std::getline(mapfileReader, mapFileLine))
{
// Extract __ImageBase
if (std::regex_search(mapFileLine, match, imageBasePattern))
{
imageBaseAddress = std::stoull(match[1], nullptr, 16);
serializer["ImageBaseAddress"] = imageBaseAddress;
continue; // Skip to the next line after extracting __ImageBase
}
// Parse Functions Name and Offsets
if (std::regex_search(mapFileLine, match, jnvNameOffsetFuncPattern) && imageBaseAddress)
{
// Extract Parsed Data
std::string functionName = match[2];
std::string scriptUID = match[3];
std::string functionOffsetStr = match[4];
// Ignore Classed Functions
if (functionName.find("@") != std::string::npos) continue;
// Calculate Offset
uint64_t functionOffset = std::stoull(functionOffsetStr, nullptr, 16);
uint64_t actualOffset = functionOffset - imageBaseAddress;
// Check for duplicate function names under the same script UID
if (serializer["Scripts"].contains(scriptUID) && serializer["Scripts"][scriptUID].contains(functionName))
{
jenova::Error("Jenova Interpreter", "Duplicate Function Detected : [%s] Under Script UID: [%s]", functionName.c_str(), scriptUID.c_str());
return jenova::SerializedData();
}
// Create Function Metadata Serializer
nlohmann::json funcSerializer;
funcSerializer["Offset"] = actualOffset;
// Parse Functions Mangled Name And Extract Types
if (std::regex_search(mapFileLine, match, jnvMangledNamePattern) && imageBaseAddress)
{
// Extract Parsed Data And Demangle
std::string mangledFunctionSignature = match[0];
std::string demangledFunctionSignature = jenova::GetDemangledFunctionSignature(mangledFunctionSignature, buildResult.compilerModel);
if (demangledFunctionSignature.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Demangle Function [%s] [%s]",
mangledFunctionSignature.c_str(), demangledFunctionSignature.c_str());
return jenova::SerializedData();
}
// Clean Function Signature
std::string cleanedFunctionSignature = jenova::CleanFunctionAndPropertySignature(demangledFunctionSignature, buildResult.compilerModel);
// Exctract Return Type
std::string returnType = jenova::ExtractReturnTypeFromSignature(cleanedFunctionSignature, buildResult.compilerModel);
if (returnType.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Extract Function Return Type [%s] [%s]",
mangledFunctionSignature.c_str(), demangledFunctionSignature.c_str());
return jenova::SerializedData();
}
funcSerializer["ReturnType"] = returnType;
jenova::VerboseByID(__LINE__, "Extracted Return Type [%s]", returnType.c_str());
// Extract Parameter Types
jenova::ParameterTypeList parameterTypes = jenova::ExtractParameterTypesFromSignature(cleanedFunctionSignature, buildResult.compilerModel);
funcSerializer["ParamCount"] = parameterTypes.size();
jenova::VerboseByID(__LINE__, "Extracted Parameters Count [%d]", parameterTypes.size());
for (size_t i = 0; i < parameterTypes.size(); ++i)
{
funcSerializer[jenova::Format("Param%02d", i + 1)] = parameterTypes[i];
jenova::VerboseByID(__LINE__, "Extracted Parameter Type [%s]", parameterTypes[i].c_str());
}
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Demangled Function Name: [%s], UID: [%s]", demangledFunctionSignature.c_str(), scriptUID.c_str());
}
// Store function name and metadata in the serializer
if (serializer["Scripts"].contains(scriptUID))
{
serializer["Scripts"][scriptUID]["methods"][functionName] = funcSerializer;
}
else
{
serializer["Scripts"][scriptUID]["methods"] = { { functionName, funcSerializer } };
}
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Function Name & Offset Extracted > Name: %s, UID: %s, Offset: %llx", functionName.c_str(), scriptUID.c_str(), actualOffset);
}
// Parse Properties Name and Offsets
if (std::regex_search(mapFileLine, match, jnvNameOffsetPropPattern) && imageBaseAddress)
{
// Extract Parsed Data
std::string propertyName = match[2];
std::string scriptUID = match[3];
std::string propertyOffsetStr = match[4];
// Clean Property Name
jenova::ReplaceAllMatchesWithString(propertyName, "__prop_", "");
// Ignore Classed Properties
if (propertyName.find("@") != std::string::npos) continue;
// Calculate Offset
uint64_t propertyOffset = std::stoull(propertyOffsetStr, nullptr, 16);
uint64_t actualOffset = propertyOffset - imageBaseAddress;
// Check for duplicate property names under the same script UID
if (serializer["Scripts"].contains(scriptUID) && serializer["Scripts"][scriptUID].contains(propertyName))
{
jenova::Error("Jenova Interpreter", "Duplicate Property Detected : [%s] Under Script UID: [%s]", propertyName.c_str(), scriptUID.c_str());
return jenova::SerializedData();
}
// Create Property Metadata Serializer
nlohmann::json propSerializer;
propSerializer["Offset"] = actualOffset;
// Parse Properties Mangled Name And Extract Type
if (std::regex_search(mapFileLine, match, jnvMangledNamePattern) && imageBaseAddress)
{
// Extract Parsed Data And Demangle
std::string mangledPropertySignature = match[0];
std::string demangledPropertySignature = jenova::GetDemangledFunctionSignature(mangledPropertySignature, buildResult.compilerModel);
if (demangledPropertySignature.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Demangle Property [%s] [%s]",
mangledPropertySignature.c_str(), demangledPropertySignature.c_str());
return jenova::SerializedData();
}
// Clean Property Signature
std::string cleanedPropertySignature = jenova::CleanFunctionAndPropertySignature(demangledPropertySignature, buildResult.compilerModel);
// Extract Type
std::string propertyType = jenova::ExtractPropertyTypeFromSignature(cleanedPropertySignature, buildResult.compilerModel);
if (propertyType.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Extract Property Type [%s] [%s]",
mangledPropertySignature.c_str(), demangledPropertySignature.c_str());
return jenova::SerializedData();
}
propSerializer["Type"] = propertyType;
jenova::VerboseByID(__LINE__, "Extracted Property Type [%s]", propertyType.c_str());
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Demangled Property Name: [%s], UID: [%s]", demangledPropertySignature.c_str(), scriptUID.c_str());
}
// Store property name and metadata in the serializer
if (serializer["Scripts"].contains(scriptUID))
{
serializer["Scripts"][scriptUID]["properties"][propertyName] = propSerializer;
}
else
{
serializer["Scripts"][scriptUID]["properties"] = { { propertyName, propSerializer } };
}
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Property Name & Offset Extracted > Name: %s, UID: %s, Offset: %llx", propertyName.c_str(), scriptUID.c_str(), actualOffset);
}
}
}
if (buildResult.compilerModel == jenova::CompilerModel::ClangLLVMCompiler)
{
// Regex Patterns
std::regex imageBasePattern(R"(^\s*\d+:\d+\s+__ImageBase\s+([0-9A-Fa-f]{16}))");
std::regex jnvSymbolPattern(R"(^\s*\d+:(\w+)\s+\?(.*?)@JNV_([a-f0-9]+)@@.*\s+([0-9A-Fa-f]{16})\s+\s+.*$)");
std::regex jnvMangledNamePattern(R"(\?\w+@JNV_\w+@@\S+)");
// Process Parsing
std::string mapFileLine; std::smatch match;
while (std::getline(mapfileReader, mapFileLine))
{
// Extract __ImageBase
if (std::regex_search(mapFileLine, match, imageBasePattern))
{
imageBaseAddress = std::stoull(match[1], nullptr, 16);
serializer["ImageBaseAddress"] = imageBaseAddress;
continue; // Skip to the next line after extracting __ImageBase
}
// Parse Jenova Symbols
if (std::regex_search(mapFileLine, match, jnvSymbolPattern) && imageBaseAddress)
{
// Detect Property vs Function
if (match[2].str().find("__prop_") != std::string::npos)
{
// Extract Parsed Data
std::string propertyName = match[2];
std::string scriptUID = match[3];
std::string propertyOffsetStr = match[4];
// Clean Property Name
jenova::ReplaceAllMatchesWithString(propertyName, "__prop_", "");
// Ignore Classed Properties
if (propertyName.find("@") != std::string::npos) continue;
// Calculate Offset
uint64_t propertyOffset = std::stoull(propertyOffsetStr, nullptr, 16);
uint64_t actualOffset = propertyOffset - imageBaseAddress;
// Check for duplicate property names under the same script UID
if (serializer["Scripts"].contains(scriptUID) && serializer["Scripts"][scriptUID].contains(propertyName))
{
jenova::Error("Jenova Interpreter", "Duplicate Property Detected : [%s] Under Script UID: [%s]", propertyName.c_str(), scriptUID.c_str());
return jenova::SerializedData();
}
// Create Property Metadata Serializer
nlohmann::json propSerializer;
propSerializer["Offset"] = actualOffset;
// Parse Properties Mangled Name And Extract Type
if (std::regex_search(mapFileLine, match, jnvMangledNamePattern) && imageBaseAddress)
{
// Extract Parsed Data And Demangle
std::string mangledPropertySignature = match[0];
std::string demangledPropertySignature = jenova::GetDemangledFunctionSignature(mangledPropertySignature, buildResult.compilerModel);
if (demangledPropertySignature.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Demangle Property [%s] [%s]",
mangledPropertySignature.c_str(), demangledPropertySignature.c_str());
return jenova::SerializedData();
}
// Clean Property Signature
std::string cleanedPropertySignature = jenova::CleanFunctionAndPropertySignature(demangledPropertySignature, buildResult.compilerModel);
// Extract Type
std::string propertyType = jenova::ExtractPropertyTypeFromSignature(cleanedPropertySignature, buildResult.compilerModel);
if (propertyType.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Extract Property Type [%s] [%s]",
mangledPropertySignature.c_str(), demangledPropertySignature.c_str());
return jenova::SerializedData();
}
propSerializer["Type"] = propertyType;
jenova::VerboseByID(__LINE__, "Extracted Property Type [%s]", propertyType.c_str());
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Demangled Property Name: [%s], UID: [%s]", demangledPropertySignature.c_str(), scriptUID.c_str());
}
// Store property name and metadata in the serializer
if (serializer["Scripts"].contains(scriptUID))
{
serializer["Scripts"][scriptUID]["properties"][propertyName] = propSerializer;
}
else
{
serializer["Scripts"][scriptUID]["properties"] = { { propertyName, propSerializer } };
}
// Verbose
jenova::VerboseByID(__LINE__, "[Map-Parser] Property Name & Offset Extracted > Name: %s, UID: %s, Offset: %llx", propertyName.c_str(), scriptUID.c_str(), actualOffset);
}
else
{
// Extract Parsed Data
std::string functionName = match[2];
std::string scriptUID = match[3];
std::string functionOffsetStr = match[4];
// Ignore Classed Functions
if (functionName.find("@") != std::string::npos) continue;
// Calculate Offset
uint64_t functionOffset = std::stoull(functionOffsetStr, nullptr, 16);
uint64_t actualOffset = functionOffset - imageBaseAddress;
// Check for duplicate function names under the same script UID
if (serializer["Scripts"].contains(scriptUID) && serializer["Scripts"][scriptUID].contains(functionName))
{
jenova::Error("Jenova Interpreter", "Duplicate Function Detected : [%s] Under Script UID: [%s]", functionName.c_str(), scriptUID.c_str());
return jenova::SerializedData();
}
// Create Function Metadata Serializer
nlohmann::json funcSerializer;
funcSerializer["Offset"] = actualOffset;
// Parse Functions Mangled Name And Extract Types
if (std::regex_search(mapFileLine, match, jnvMangledNamePattern) && imageBaseAddress)
{
// Extract Parsed Data And Demangle
std::string mangledFunctionSignature = match[0];
std::string demangledFunctionSignature = jenova::GetDemangledFunctionSignature(mangledFunctionSignature, buildResult.compilerModel);
if (demangledFunctionSignature.empty())
{
jenova::Error("Jenova Interpreter", "Failed to Parse Map and Generate Metadata, Parser Error : Unable to Demangle Function [%s] [%s]",
mangledFunctionSignature.c_str(), demangledFunctionSignature.c_str());
return jenova::SerializedData();
}