This repository was archived by the owner on Dec 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogpV8.cpp
More file actions
1489 lines (1135 loc) · 47.4 KB
/
Copy pathprogpV8.cpp
File metadata and controls
1489 lines (1135 loc) · 47.4 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
/*
* (C) Copyright 2024 Johan Michel PIQUET, France (https://johanpiquet.fr/).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "progpV8.h"
#include "libplatform/libplatform.h"
#include "v8.h"
#include <memory>
#include <iostream>
#include <utility>
#include <thread>
#include <cstdlib>
#include <string>
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/config.hpp>
namespace beast = boost::beast;
namespace http = beast::http;
namespace websocket = beast::websocket;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
std::unique_ptr<v8::Platform> gV8Platform;
v8::ArrayBuffer::Allocator *gArrayBufferAllocator;
f_progp_v8_functions_provider gV8FunctionProvider = nullptr;
f_progp_v8_dynamicFunctions_provider gV8DynamicFunctionProvider = nullptr;
f_progp_v8_function_allowedFunctionChecker gV8AllowedFunctionChecker = nullptr;
ProgpContext gProgpDbgCtx;
//region Engine
void onProcessRejectedPromise(v8::PromiseRejectMessage reject_message) {
auto v8Iso = reject_message.GetPromise()->GetIsolate();
auto v8Ctx = v8Iso->GetCurrentContext();
ProgpContext progpCtx = (ProgpContext) v8Ctx->GetEmbedderData(0).As<v8::External>()->Value();
auto messageValue = reject_message.GetValue();
if (!messageValue.IsEmpty()) {
v8::Local<v8::Message> errorMessage = v8::Exception::CreateMessage(v8Iso, messageValue);
onJavascriptError(progpCtx, v8Ctx, errorMessage);
}
}
extern "C"
void progp_DisposeContext(ProgpContext progpCtx) {
delete(progpCtx->event);
if (progpCtx->v8Iso == v8::Isolate::GetCurrent()) {
progpCtx->v8Iso->Exit();
}
progpCtx->v8Iso->Dispose();
delete(progpCtx);
}
extern "C"
ProgpContext progp_CreateNewContext(uintptr_t data) {
auto progpCtx = new s_progp_context();
progpCtx->data = data;
// Always having a event allow generalizing some mechanisms.
// It's why we always bind an event to a ProgpContext.
//
progpCtx->event = new s_progp_event();
progpCtx->event->id = 0;
progpCtx->event->refCount = 0;
progpCtx->event->previousEvent = nullptr;
progpCtx->event->contextData = data;
// Create the v8-isolate.
{
v8::Isolate::CreateParams params;
params.array_buffer_allocator = gArrayBufferAllocator;
progpCtx->v8Iso = v8::Isolate::New(params);
// Allows having the stacktrace for the errors.
progpCtx->v8Iso->SetCaptureStackTraceForUncaughtExceptions(true);
// Allows knowing when a promise is rejected and not caught.
progpCtx->v8Iso->SetPromiseRejectCallback(onProcessRejectedPromise);
// Allow freeing memory when running out.
progpCtx->v8Iso->LowMemoryNotification();
}
// Create the v8-context.
{
V8ISO_ACCESS(progpCtx);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(v8Iso);
auto v8Ctx = v8::Context::New(v8Iso, nullptr, global);
progpCtx->v8Ctx.Reset(v8Iso, v8Ctx);
v8Ctx->SetEmbedderData(0, v8::External::New(v8Iso, progpCtx));
}
return progpCtx;
}
extern "C"
void progp_InitializeContext(ProgpContext progpCtx) {
progp_DeclareGlobalFunctions(progpCtx);
if (gProgpDbgCtx== nullptr) {
gProgpDbgCtx = progpCtx;
}
}
extern "C"
void progp_StartupEngine() {
gV8Platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(gV8Platform.get());
v8::V8::Initialize();
gArrayBufferAllocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator();
#ifndef PROGP_STANDALONE
cgoInitialize();
#endif
}
extern "C"
const char* progp_GetV8EngineVersion() {
return v8::V8::GetVersion();
}
//endregion
//region Executing scripts
f_progp_onNoMoreTasksForContext g_onNoMoreTask = nullptr;
f_progp_eventFinished g_onEventFinished = nullptr;
extern "C"
void progp_IncreaseContextRef(ProgpContext progpCtx) {
//std::lock_guard autoUnlock(gContextRefCountMutex);
// Here we are thread safe since caller use
// a funnel doing that only one thread can speak to the VM.
progpCtx->refCount++;
if (progpCtx->event!= nullptr) {
progpCtx->event->refCount++;
}
}
extern "C"
void progp_DecreaseContextRef(ProgpContext progpCtx) {
if (progpCtx->event!= nullptr) {
progpCtx->event->refCount--;
if (progpCtx->event->refCount==0) {
auto evt = progpCtx->event;
progpCtx->event = evt->previousEvent;
if (g_onEventFinished!=nullptr) g_onEventFinished(evt->id);
delete(evt);
}
}
progpCtx->refCount--;
if (progpCtx->refCount==0) {
if (g_onNoMoreTask != nullptr) g_onNoMoreTask(progpCtx);
}
}
extern "C"
bool progp_ExecuteScript(ProgpContext progpCtx, const char* scriptContent, const char* scriptOrigin, uintptr_t eventId) {
progpCtx->event->id = eventId;
progp_IncreaseContextRef(progpCtx);
V8CTX_ACCESS();
v8::ScriptOrigin v8ScriptOrigin(v8Iso, v8::String::NewFromUtf8(v8Iso, scriptOrigin).ToLocalChecked());
v8::Local<v8::String> v8ScriptSourceAsText = v8::String::NewFromUtf8(v8Iso, scriptContent).ToLocalChecked();
v8::TryCatch tryCatch(v8Iso);
v8::Local<v8::Script> script;
if (!v8::Script::Compile(v8Ctx, v8ScriptSourceAsText, &v8ScriptOrigin).ToLocal(&script)) {
auto error = tryCatch.Message();
onJavascriptError(progpCtx, v8Ctx, error);
progp_DecreaseContextRef(progpCtx);
return false;
}
v8::Local<v8::Value> result;
//
if (!script->Run(v8Ctx).ToLocal(&result)) {
auto error = tryCatch.Message();
onJavascriptError(progpCtx, v8Ctx, error);
progp_DecreaseContextRef(progpCtx);
return false;
}
progp_DecreaseContextRef(progpCtx);
return true;
}
//endregion
//region Managing errors
f_progp_javascriptErrorListener gJavascriptErrorListener = nullptr;
void disposeErrorMessage(s_progp_v8_errorMessage *msg) {
if (msg->error!= nullptr) free(msg->error);
if (msg->sourceMapUrl!= nullptr) free(msg->sourceMapUrl);
if (msg->resourceName!= nullptr) free(msg->resourceName);
if (msg->stackTraceFrameArray!= nullptr) {
int frameCount = msg->stackTraceFrameCount;
auto array = msg->stackTraceFrameArray;
msg->stackTraceFrameArray = nullptr;
for (int i=0;i<frameCount;i++) {
auto frame = &array[i];
if (frame->function!= nullptr) free(frame->function);
if (frame->source!= nullptr) free(frame->source);
}
}
delete(msg);
}
static s_progp_v8_errorMessage* createErrorMessage(ProgpContext progpCtx, const v8::Local<v8::Context> &v8Ctx, v8::Local<v8::Message>& message) {
auto res = new s_progp_v8_errorMessage();
res->error = strdup(V8VALUE_TO_CSTRING(message->Get()));
res->errorLevel = message->ErrorLevel();
res->startColumn = message->GetStartColumn();
res->endColumn = message->GetEndColumn();
res->startPosition = message->GetStartPosition();
res->endPosition = message->GetEndPosition();
auto v8ScriptOrigin = message->GetScriptOrigin();
if (!v8ScriptOrigin.SourceMapUrl().IsEmpty()) {
res->sourceMapUrl = strdup(V8VALUE_TO_CSTRING(v8ScriptOrigin.SourceMapUrl()->ToString(v8Ctx).ToLocalChecked()));
}
if (!v8ScriptOrigin.ResourceName().IsEmpty()) {
res->resourceName = strdup(V8VALUE_TO_CSTRING(v8ScriptOrigin.ResourceName()->ToString(v8Ctx).ToLocalChecked()));
}
auto v8StackTrace = message->GetStackTrace();
if (!v8StackTrace.IsEmpty()) {
auto stackTraceFrameCount = v8StackTrace->GetFrameCount();
auto frames = (s_progp_v8_stackTraceFrame*)malloc(sizeof(s_progp_v8_stackTraceFrame) * stackTraceFrameCount);
res->stackTraceFrameArray = frames;
res->stackTraceFrameCount = stackTraceFrameCount;
res->stackTraceFrameSize = sizeof(s_progp_v8_stackTraceFrame);
for (auto frameOffset = 0 ; frameOffset<stackTraceFrameCount ; frameOffset++) {
auto v8StackFrame = v8StackTrace->GetFrame(progpCtx->v8Iso, frameOffset);
auto frame = &frames[frameOffset];
frame->line = v8StackFrame->GetLineNumber();
frame->column = v8StackFrame->GetColumn();
auto v8Function = v8StackFrame->GetFunctionName();
if (!v8Function.IsEmpty()) frame->function = strdup(V8VALUE_TO_CSTRING(v8Function->ToString(v8Ctx).ToLocalChecked()));
auto v8Source = v8StackFrame->GetScriptNameOrSourceURL();
if (!v8Source.IsEmpty()) frame->source = strdup(V8VALUE_TO_CSTRING(v8Source->ToString(v8Ctx).ToLocalChecked()));
}
}
return res;
}
void onJavascriptError(ProgpContext progpCtx, const v8::Local<v8::Context> &v8Ctx, v8::Local<v8::Message>& message) {
//PROGP_DEBUG("Calling onJavascriptError from " << caller);
if (gJavascriptErrorListener != nullptr) {
auto msg = createErrorMessage(progpCtx, v8Ctx, message);
gJavascriptErrorListener(progpCtx, msg);
disposeErrorMessage(msg);
}
}
void progp_PrintErrorMessage(s_progp_v8_errorMessage* msg) {
PROGP_PRINT(msg->error);
for (int i=0;i<msg->stackTraceFrameCount;i++) {
auto frame = msg->stackTraceFrameArray[i];
if (frame.function!= nullptr) {
PROGP_PRINT(frame.source << ":" << frame.line << ":" << frame.column << " - " << frame.function);
}
}
}
//endregion
//region Functions: declaring news functions
void progp_AddFunctionToObject(ProgpContext progpCtx, const char* groupName, const v8::Local<v8::Object> &v8Object, const char* functionName, f_progp_v8_function functionRef) {
// Detect if the function is allowed.
//
if (gV8AllowedFunctionChecker!= nullptr) {
std::string securityGroup;
if (!gV8AllowedFunctionChecker((char*)securityGroup.c_str(), (char*)groupName, (char*)functionName)) return;
}
V8CTX_ACCESS();
auto v8FunctionTemplate = v8::FunctionTemplate::New(v8Iso, functionRef);
v8::Local<v8::String> v8PropName = v8::String::NewFromUtf8(v8Iso, functionName,
v8::NewStringType::kNormal).ToLocalChecked();
auto v8Function = v8FunctionTemplate->GetFunction(v8Ctx).ToLocalChecked();
v8Object->Set(v8Ctx, v8PropName, v8Function).IsJust();
v8FunctionTemplate.Clear();
}
const v8::Local<v8::Object>* gCurrentFunctionGroup;
void progp_CreateFunctionGroup(ProgpContext progpCtx, const std::string& group, const v8::Local<v8::Object> &v8Object) {
progp_CreateFunctionGroup_Internal(progpCtx, group, v8Object);
if (gV8FunctionProvider!= nullptr) {
gV8FunctionProvider(progpCtx, group, v8Object);
}
if (gV8DynamicFunctionProvider!= nullptr) {
gCurrentFunctionGroup = &v8Object;
// Will call progp_DeclareDynamicFunction.
gV8DynamicFunctionProvider(progpCtx, (char*)group.c_str());
gCurrentFunctionGroup = nullptr;
}
}
extern "C"
void progp_DeclareDynamicFunction(ProgpContext progpCtx, const char* functionName) {
if (gCurrentFunctionGroup== nullptr) {
return;
}
V8CTX_ACCESS();
auto vFctName = CSTRING_TO_V8VALUE(functionName);
auto v8FunctionTemplate = v8::FunctionTemplate::New(v8Iso, progp_handleDraftFunction, vFctName);
v8::Local<v8::String> v8PropName = v8::String::NewFromUtf8(v8Iso, functionName,
v8::NewStringType::kNormal).ToLocalChecked();
auto v8Function = v8FunctionTemplate->GetFunction(v8Ctx).ToLocalChecked();
(*gCurrentFunctionGroup)->Set(v8Ctx, v8PropName, v8Function).IsJust();
v8FunctionTemplate.Clear();
}
void progp_DeclareGlobalFunctions(ProgpContext progpCtx) {
V8CTX_ACCESS();
progp_CreateFunctionGroup(progpCtx, "global", v8Ctx->Global());
}
//endregion
//region Functions: ref to javascript function
s_progp_v8_function* progpFunctions_NewPointer(ProgpContext progpCtx, const v8::Local<v8::Function> &v8Function) {
auto res = new s_progp_v8_function();
res->progpCtx = progpCtx;
res->ref.Reset(progpCtx->v8Iso, v8Function);
return res;
}
//endregion
//region Functions: call from external / callbacks
void useNewEvent(ProgpContext progpCtx, uintptr_t resourceContainerId) {
auto newEvent = new s_progp_event();
newEvent->id = resourceContainerId;
newEvent->refCount = 0;
newEvent->previousEvent = nullptr;
newEvent->contextData = progpCtx->data;
newEvent->previousEvent = progpCtx->event;
progpCtx->event = newEvent;
// Require, without that the ref counter is 0
// and will never go from 1 to 0.
//
progp_IncreaseContextRef(progpCtx);
}
extern "C"
void progp_CallFunctionWithStringP2(FCT_CALLBACK_PARAMS, const char* str, size_t strLen) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[2];
argArray[0] = v8::Undefined(v8Iso);
argArray[1] = v8::String::NewFromUtf8(v8Iso, str, v8::NewStringType::kNormal, (int)strLen).ToLocalChecked();
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 2, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithArrayBufferP2(FCT_CALLBACK_PARAMS, const void* buffer, size_t bufferSize) {
FCT_CALLBACK_BEFORE
auto v8BackingStore = std::shared_ptr(v8::ArrayBuffer::NewBackingStore(v8Iso, bufferSize));
memcpy(v8BackingStore->Data(), buffer, bufferSize);
// Required for buffer allocation.
v8Ctx->Enter();
v8::Local<v8::Value> argArray[2];
argArray[0] = v8::Undefined(v8Iso);
argArray[1] = v8::ArrayBuffer::New(v8Iso, v8BackingStore);
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 2, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithErrorP1(FCT_CALLBACK_PARAMS, const char* str, size_t strLen) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[1];
argArray[0] = v8::String::NewFromUtf8(v8Iso, str, v8::NewStringType::kNormal, (int)strLen).ToLocalChecked();
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 1, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithDoubleP1(FCT_CALLBACK_PARAMS, double value) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[1];
argArray[0] = DOUBLE_TO_V8VALUE(value);
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 1, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithDoubleP2(FCT_CALLBACK_PARAMS, double value) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[2];
argArray[0] = v8::Undefined(v8Iso);
argArray[1] = DOUBLE_TO_V8VALUE(value);
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 2, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithBoolP2(FCT_CALLBACK_PARAMS, bool value) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[2];
argArray[0] = v8::Undefined(v8Iso);
argArray[1] = BOOL_TO_V8VALUE(value);
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 2, argArray).IsEmpty();
FCT_CALLBACK_AFTER
}
extern "C"
void progp_CallFunctionWithUndefined(FCT_CALLBACK_PARAMS) {
FCT_CALLBACK_BEFORE
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), 0, nullptr).IsEmpty();
FCT_CALLBACK_AFTER
}
//endregion
//region Calling function from Golang / dynamic
extern "C"
s_progp_dynamicFunctionCall* progp_DynamicFunctionCaller_New(int argCount) {
auto dfc = new(s_progp_dynamicFunctionCall);
dfc->argCount = argCount;
dfc->callArgs = (s_progp_anyValue**)calloc(argCount, sizeof(s_progp_anyValue));
return dfc;
}
extern "C"
void progp_DynamicFunctionCaller_AddParam(s_progp_dynamicFunctionCall* dfc, s_progp_anyValue* anyValue, int offset) {
dfc->callArgs[offset] = anyValue;
}
extern "C"
void progp_DynamicFunctionCaller_Call(s_progp_dynamicFunctionCall* dfc, FCT_CALLBACK_PARAMS) {
FCT_CALLBACK_BEFORE
v8::Local<v8::Value> argArray[dfc->argCount];
for (int i=0;i<dfc->argCount;i++) {
s_progp_anyValue anyValue = *(dfc->callArgs[i]);
argArray[i] = progp_AnyValueToV8Value(progpCtx, v8Ctx, anyValue);
// Note: callArgs lifetime is controller by the Go caller so we don't deleter the anyValues here.
}
auto isEmpty = functionRef->ref.Get(v8Iso)->Call(v8Ctx, v8Ctx->Global(), dfc->argCount, argArray).IsEmpty();
delete(dfc->callArgs);
delete(dfc);
// Note: FCT_CALLBACK_AFTER destroy the function ref so we don't destroy it.
FCT_CALLBACK_AFTER
}
//endregion
//region Others
void* progp_CopyGoBuffer(void* buffer, int size) {
auto newBuffer = malloc(size);
memcpy(newBuffer, buffer, size);
return newBuffer;
}
const char* progpV8Value_GetTypeName(v8::Local<v8::Value> &value) {
if (value->IsUndefined()) return "Undefined";
if (value->IsNull()) return "Null";
if (value->IsString()) return "String";
if (value->IsStringObject()) return "StringObject";
if (value->IsFloat64Array()) return "Float64Array";
if (value->IsFloat32Array()) return "Float32Array";
if (value->IsMapIterator()) return "MapIterator";
if (value->IsMap()) return "Map";
if (value->IsDate()) return "Date";
if (value->IsBooleanObject()) return "BooleanObject";
if (value->IsBoolean()) return "Boolean";
if (value->IsBigIntObject()) return "BigIntObject";
if (value->IsBigInt64Array()) return "BigInt64Array";
if (value->IsAsyncFunction()) return "AsyncFunction";
if (value->IsArrayBufferView()) return "ArrayBufferView";
if (value->IsArgumentsObject()) return "ArgumentsObject";
if (value->IsUint8Array()) return "Uint8Array";
if (value->IsExternal()) return "External";
if (value->IsFunction()) return "Function";
if (value->IsArray()) return "Array";
if (value->IsArrayBuffer()) return "ArrayBuffer";
if (value->IsBigInt()) return "BigInt";
if (value->IsInt32()) return "Int32";
if (value->IsNumber()) return "Number";
return "???";
}
extern "C"
int progp_GetSizeOfAnyValueStruct() {
return sizeof(s_progp_anyValue);
}
//endregion
//region V8 Debugger
//region Don't expose, for v8 debugger use
unsigned int randomChar() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 255);
return dis(gen);
}
std::string buildGuid(int len) {
std::stringstream ss;
for (auto i = 0; i < len; i++) {
const auto rc = randomChar();
std::stringstream hexStream;
hexStream << std::hex << rc;
auto hex = hexStream.str();
ss << (hex.length() < 2 ? '0' + hex : hex);
}
return ss.str();
}
static std::string replaceAll(std::string str, const std::string& from, const std::string& to) {
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
return str;
}
static inline std::string convertToString(v8::Isolate *isolate, const v8_inspector::StringView stringView) {
int length = static_cast<int>(stringView.length());
v8::Local<v8::String> message = (
stringView.is8Bit()
? v8::String::NewFromOneByte(isolate, reinterpret_cast<const uint8_t *>(stringView.characters8()),
v8::NewStringType::kNormal, length)
: v8::String::NewFromTwoByte(isolate, reinterpret_cast<const uint16_t *>(stringView.characters16()),
v8::NewStringType::kNormal, length)
).ToLocalChecked();
v8::String::Utf8Value result(isolate, message);
return *result;
}
static inline v8_inspector::StringView convertToStringView(const std::string &str) {
auto *stringView = reinterpret_cast<const uint8_t *>(str.c_str());
return {stringView, str.length()};
}
static inline v8::Local<v8::Object> parseJson(const v8::Local<v8::Context> &context, const std::string &json) {
auto iso = context->GetIsolate();
v8::MaybeLocal<v8::Value> v = v8::JSON::Parse(
context, v8::String::NewFromUtf8(iso, &json[0],
v8::NewStringType::kNormal).ToLocalChecked());
if (v.IsEmpty()) return {};
return v.ToLocalChecked()->ToObject(context).ToLocalChecked();
}
static inline std::string getPropertyFromJson(v8::Isolate *isolate,
const v8::Local<v8::Object> &jsonObject,
const std::string &propertyName) {
v8::Local<v8::Value> property = jsonObject->Get(isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, propertyName.c_str(),
v8::NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();
v8::String::Utf8Value utf8Value(isolate, property);
return *utf8Value;
}
inline void pauseMs(int durationInMs) {
std::this_thread::sleep_for(std::chrono::milliseconds(durationInMs));
}
//endregion
const int Size_1Ko = 1024;
const int Size_1Mo = Size_1Ko * 1024;
// The max size of the packets sends to the debugger.
// Must be huge since the debugger sends huge packets and doesn't support chunking...
//
const int gDebuggerIoBufferSize = Size_1Mo * 60;
ProgpDbgInternals_IoNetwork *g_debuggerInt_ioNetwork;
f_progp_noParamNoReturn g_onDebuggerExitedCallback = nullptr;
extern "C"
void progp_WaitDebuggerReady() {
if (g_debuggerInt_ioNetwork == nullptr) {
g_debuggerInt_ioNetwork = new ProgpDbgInternals_IoNetwork(buildGuid(64), "file://progpv8");
}
ProgpDbgInternals_IoNetwork::printOpenChromeInspectorMessage();
for (;;) {
if (g_debuggerInt_ioNetwork->isDebuggerReady()) {
break;
}
pauseMs(100);
}
}
void progpDbgInternals_OnDebuggerReady() {
PROGP_PRINT("Debugger: Chrome Inspector is ready");
}
void progpDbgInternals_DeclareDebuggerExited() {
if (g_onDebuggerExitedCallback!= nullptr) g_onDebuggerExitedCallback();
else DEBUGGER_ERROR("Debugger client has been closed.")
}
//region Class --> ProgpDbgInternals_IoNetwork
ProgpDbgInternals_IoNetwork::ProgpDbgInternals_IoNetwork(std::string guid, std::string filePath)
{
_port = 9229;
_guid = std::move(guid);
_filePath = std::move(filePath);
std::thread([this] { return this->startListeningNetwork(); }).detach();
}
http::message_generator ProgpDbgInternals_IoNetwork::onSimpleHttpRequest(http::request<http::string_body> &req)
{
auto const bad_request =
[&req](beast::string_view why)
{
http::response<http::string_body> res{http::status::bad_request, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = std::string(why);
res.prepare_payload();
return res;
};
auto const send_response = [&req](beast::string_view msg) {
http::response<http::string_body> res{http::status::ok, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = std::string(msg);
res.prepare_payload();
return res;
};
// Make sure we can handle the method
//
if( req.method() != http::verb::get &&
req.method() != http::verb::head)
return bad_request("Unknown HTTP-method");
auto target = req.target();
// Request path must be absolute and not contain "..".
if(target.empty() || target[0] != '/' || req.target().find("..") != beast::string_view::npos) return bad_request("Illegal request-target");
if (target=="/json/version") {
return send_response(R"({"Browser":"progpjs/1.0.0","Protocol-Version":"1.3","V8-Version":"11.4.183.1"})");
}
// Note: target was "/json" and is now "/json/list?for_tab".
//
if (target.starts_with("/json")) {
std::string s = R"([{"description":"progpjs","devtoolsFrontendUrl":"devtools://devtools/bundled/js_app.html?ws=127.0.0.1:%PORT%/ws/%GUID%&experiments=true&v8only=true","faviconUrl":"https://progpjs.com/favicon.ico","id":"%GUID%","title":"progpjs - main [pid: %PID%]","type":"node","url":"%FILEPATH%","webSocketDebuggerUrl":"ws://127.0.0.1:%PORT%/ws/%GUID%"}])";
s = replaceAll(s, std::string("%GUID%"), _guid);
s = replaceAll(s, std::string("%PID%"), std::to_string(5555));
s = replaceAll(s, std::string("%PORT%"), std::to_string(_port));
s = replaceAll(s, std::string("%FILEPATH%"), _filePath);
return send_response(s);
}
#if PROGP_PRINT_DEBUGGER_MESSAGE
PROGP_DEBUG("Unknown debugger request: " << target.data());
#endif
return bad_request("Unknown request");
}
void ProgpDbgInternals_IoNetwork::sendMessageToChromeInspector(const std::string &message) {
if (_isDebuggerSessionStopped) return;
PROGP_PRINT_DEBUGGER_MSG("E2I >>>>> " << message)
try {
boost::beast::multi_buffer b;
boost::beast::ostream(b) << message;
_ws->text(_ws->got_text());
auto data = b.data();
if (message.size()>gDebuggerIoBufferSize) PROGP_PRINT("Warning, message to debugger exceed the max size. See: gDebuggerIoBufferSize");
_ws->write(data);
} catch (beast::system_error const &se) {
if (se.code() != websocket::error::closed) {
DEBUGGER_ERROR(se.code().message())
}
} catch (std::exception const &e) {
DEBUGGER_ERROR(e.what())
}
}
bool ProgpDbgInternals_IoNetwork::isDebuggerReady() const {
return _isDebuggerReady;
}
void ProgpDbgInternals_IoNetwork::printOpenChromeInspectorMessage() {
PROGP_PRINT("");
PROGP_PRINT("=== ProgpJS Debugger started =========================================");
PROGP_PRINT("= Open the following link in your Chrome/Chromium browser: =");
PROGP_PRINT("= chrome://inspect/#devices =");
PROGP_PRINT("======================================================================");
}
void ProgpDbgInternals_IoNetwork::loopAddIncomingMessagesToDebuggerQueue() {
_isDebuggerSessionStopped = false;
while (true) {
try {
if (_isDebuggerSessionStopped) break;
auto message = readNextWebSocketMessage();
if (_isDebuggerSessionStopped) break;
if (!message.empty() && (_inspector!= nullptr)) _inspector->addMessageFromChromeInspector(message);
}
catch (const std::exception &e) {
declareDebuggerSessionStopped();
}
}
}
void ProgpDbgInternals_IoNetwork::declareDebuggerSessionStopped() {
if (!_isNowAWebSocket) return;
if (_isDebuggerSessionStopped) return;
_isDebuggerSessionStopped = true;
if (_inspector!= nullptr) _inspector->onNetworkDisconnected();
}
void ProgpDbgInternals_IoNetwork::startListeningNetwork() {
auto const address = net::ip::make_address("127.0.0.1");
boost::beast::flat_buffer buffer;
_isDebuggerSessionStopped = true;
try {
net::io_context ioc{1};
tcp::acceptor acceptor{ioc, {address, static_cast<unsigned short>(_port)}};
while (true) {
_isDebuggerReady = false;
_isNowAWebSocket = false;
// The connexion socket.
// Will be initialized by the acceptor.
//
// There is one socket per message, since each client connects
// to a different internal port (the same external port, but a different internal port).
//
// It's why the socket is closed after each http-message that is received.
//
tcp::socket socket{ioc};
try {
// Initialize the socket and
// wait until a client connects to this socket.
// Block waiting the client.
//
acceptor.accept(socket);
// Read the request send by the client (here Chrome Inspector).
// Here buffer is only used to store the temporary data.
//
http::request<http::string_body> req;
http::read(socket, buffer, req);
// The target is what is after "http://localhost/???".
// It's the "???" part.
//
auto reqTarget = req.target();
// Here the difficulty is that two things are mixed:
// - Simple HTTP calls.
// - And webSocket calls.
//
// Its starts by simples http call where Chrome Inspector asks us the list of the sessions.
// Once the user clicks on a session through a hypertext link (or if Chrome Inspector auto-connect),
// then the connexion turns into a web-socket connexion.
//
// We have known that it's beginning the web-socket dialogue a target beginning by "/ws/"+;
//
if (reqTarget.starts_with("/ws/")) {
// >>> Began a web-socket dialogue.
_isNowAWebSocket = true;
_ws = new websocket::stream<tcp::socket>(std::move(socket));
// Required. Without that track, the messages are too long.
// The default is 4kb. Here grow to 8Mb. Which means scripts size can exceed 8Mb.
_ws->write_buffer_bytes(gDebuggerIoBufferSize);
_ws->accept(req);
// Create a client which will consume the messages from the Chrome Inspector.
onChromeInspectorConnected();
// An infinite loop waiting for messages and adding them to the inspector client message queue.
this->loopAddIncomingMessagesToDebuggerQueue();
// Close the connexion.
if (_ws!= nullptr) {
beast::error_code ec;
ec = _ws->next_layer().shutdown(tcp::socket::shutdown_both, ec);
delete (_ws);
_ws = nullptr;
if (ec) {
// 57 - Socket is not connected
if (ec.value()!=57) {
DEBUGGER_ERROR("Code " << ec.value() << " - " << ec.what())
}
}
}
} else {
// >>> A standard HTTP call.
// Process the message and give a response.
auto msg = onSimpleHttpRequest(req);
// Send this response.
//
beast::error_code ec;
beast::write(socket, std::move(msg), ec);
//
if (ec) {
DEBUGGER_ERROR("Code " << ec.value() << " - " << ec.what())
}
// Close the connexion with the client.
// Here it's always one shoot.
//
ec = socket.shutdown(tcp::socket::shutdown_send, ec);
//
if (ec) {
// 57 - Socket is not connected
if (ec.value()!=57) {
DEBUGGER_ERROR("Code " << ec.value() << " - " << ec.what())
}
}
}
}
catch (beast::system_error const &se) {
if (se.code() != websocket::error::closed) {
DEBUGGER_ERROR("Code " << se.code().value() << " - " << se.code().message())
declareDebuggerSessionStopped();
}
}
catch (const std::exception &e) {
DEBUGGER_ERROR(e.what())
declareDebuggerSessionStopped();
}
}
}
catch (beast::system_error const &se) {
if (se.code().message()=="Permission denied") {
DEBUGGER_ERROR("The port " << _port << " is already used, can't launch debugger.")
} else {
DEBUGGER_ERROR(se.code().message() << " - " << se.what())
}
declareDebuggerSessionStopped();
}
catch (const std::exception &e) {
DEBUGGER_ERROR(e.what())
declareDebuggerSessionStopped();
}
}
void ProgpDbgInternals_IoNetwork::onChromeInspectorConnected() {
if (_inspector== nullptr) {
_inspector = new ProgpDbgInternals_V8InspectorClientImpl(gV8Platform.get(), this);
}
_inspector->onChromeInspectorConnected();
}
void ProgpDbgInternals_IoNetwork::declareDebuggerReady() {