-
-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathHelpers.mm
More file actions
941 lines (808 loc) · 31.7 KB
/
Helpers.mm
File metadata and controls
941 lines (808 loc) · 31.7 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
#include "Helpers.h"
#include <Foundation/Foundation.h>
#include <cxxabi.h>
#include <dispatch/dispatch.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <stdio.h>
#include <sys/stat.h>
#include <codecvt>
#include <fstream>
#include <locale>
#include <sstream>
#include "Caches.h"
#include "NativeScriptException.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
using namespace v8;
namespace {
const int BUFFER_SIZE = 1024 * 1024;
char* Buffer = new char[BUFFER_SIZE];
uint8_t* BinBuffer = new uint8_t[BUFFER_SIZE];
}
std::u16string tns::ToUtf16String(Isolate* isolate, const Local<Value>& value) {
std::string valueStr = tns::ToString(isolate, value);
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// FIXME: std::codecvt_utf8_utf16 is deprecated
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
std::u16string value16 = convert.from_bytes(valueStr);
return value16;
}
std::vector<uint16_t> tns::ToVector(const std::string& value) {
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
// FIXME: std::codecvt_utf8_utf16 is deprecated
std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> convert;
std::u16string value16 = convert.from_bytes(value);
const uint16_t* begin = reinterpret_cast<uint16_t const*>(value16.data());
const uint16_t* end = reinterpret_cast<uint16_t const*>(value16.data() + value16.size());
std::vector<uint16_t> vector(begin, end);
return vector;
}
bool tns::Exists(const char* fullPath) {
struct stat statbuf;
mode_t mode = S_IFDIR | S_IFREG;
if (stat(fullPath, &statbuf) == 0) {
return (statbuf.st_mode & S_IFMT) & mode;
}
return false;
}
Local<v8::String> tns::ReadModule(Isolate* isolate, const std::string& filePath) {
struct stat finfo;
int file = open(filePath.c_str(), O_RDONLY);
if (file < 0) {
throw NativeScriptException(isolate, "Cannot read module " + filePath);
}
fstat(file, &finfo);
long length = finfo.st_size;
char* newBuffer = new char[length + 128];
strcpy(newBuffer,
"(function(module, exports, require, __filename, __dirname) { "); // 61 Characters
read(file, &newBuffer[61], length);
close(file);
length += 61;
// Add the closing "\n})"
newBuffer[length] = 10;
++length;
newBuffer[length] = '}';
++length;
newBuffer[length] = ')';
++length;
newBuffer[length] = 0;
Local<v8::String> str =
v8::String::NewFromUtf8(isolate, newBuffer, NewStringType::kNormal, (int)length)
.ToLocalChecked();
delete[] newBuffer;
return str;
}
const char* tns::ReadText(const std::string& filePath, long& length, bool& isNew) {
FILE* file = fopen(filePath.c_str(), "rb");
if (file == nullptr) {
tns::Assert(false);
}
fseek(file, 0, SEEK_END);
length = ftell(file);
isNew = length > BUFFER_SIZE;
rewind(file);
if (isNew) {
char* newBuffer = new char[length];
fread(newBuffer, 1, length, file);
fclose(file);
return newBuffer;
}
fread(Buffer, 1, length, file);
fclose(file);
return Buffer;
}
std::string tns::ReadText(const std::string& file) {
long length;
bool isNew;
const char* content = tns::ReadText(file, length, isNew);
std::string result(content, length);
if (isNew) {
delete[] content;
}
return result;
}
uint8_t* tns::ReadBinary(const std::string path, long& length, bool& isNew) {
length = 0;
std::ifstream ifs(path);
if (ifs.fail()) {
return nullptr;
}
FILE* file = fopen(path.c_str(), "rb");
if (!file) {
return nullptr;
}
fseek(file, 0, SEEK_END);
length = ftell(file);
rewind(file);
isNew = length > BUFFER_SIZE;
if (isNew) {
uint8_t* data = new uint8_t[length];
fread(data, sizeof(uint8_t), length, file);
fclose(file);
return data;
}
fread(BinBuffer, 1, length, file);
fclose(file);
return BinBuffer;
}
bool tns::WriteBinary(const std::string& path, const void* data, long length) {
FILE* file = fopen(path.c_str(), "wb");
if (!file) {
return false;
}
size_t writtenBytes = fwrite(data, sizeof(uint8_t), length, file);
fclose(file);
return writtenBytes == length;
}
void tns::SetPrivateValue(const Local<Object>& obj, const Local<v8::String>& propName,
const Local<Value>& value) {
Local<Context> context;
bool success = obj->GetCreationContext().ToLocal(&context);
tns::Assert(success);
Isolate* isolate = context->GetIsolate();
Local<Private> privateKey = Private::ForApi(isolate, propName);
if (!obj->SetPrivate(context, privateKey, value).To(&success) || !success) {
tns::Assert(false, isolate);
}
}
Local<Value> tns::GetPrivateValue(const Local<Object>& obj, const Local<v8::String>& propName) {
Local<Context> context;
bool success = obj->GetCreationContext().ToLocal(&context);
tns::Assert(success);
Isolate* isolate = context->GetIsolate();
Local<Private> privateKey = Private::ForApi(isolate, propName);
Maybe<bool> hasPrivate = obj->HasPrivate(context, privateKey);
tns::Assert(!hasPrivate.IsNothing(), isolate);
if (!hasPrivate.FromMaybe(false)) {
return Local<Value>();
}
v8::Locker locker(isolate);
Local<Value> result;
if (!obj->GetPrivate(context, privateKey).ToLocal(&result)) {
tns::Assert(false, isolate);
}
return result;
}
bool tns::DeleteWrapperIfUnused(Isolate* isolate, const Local<Value>& obj, BaseDataWrapper* value) {
if (GetValue(isolate, obj) != value) {
delete value;
return true;
}
return false;
}
void tns::SetValue(Isolate* isolate, const Local<Object>& obj, BaseDataWrapper* value) {
if (obj.IsEmpty() || obj->IsNullOrUndefined()) {
return;
}
Local<External> ext = External::New(isolate, value);
if (obj->InternalFieldCount() > 0) {
obj->SetInternalField(0, ext);
} else {
tns::SetPrivateValue(obj, tns::ToV8String(isolate, "metadata"), ext);
}
}
tns::BaseDataWrapper* tns::GetValue(Isolate* isolate, const Local<Value>& val) {
if (val.IsEmpty() || val->IsNullOrUndefined() || !val->IsObject()) {
return nullptr;
}
Local<Object> obj = val.As<Object>();
if (obj->InternalFieldCount() > 0) {
Local<Value> field = obj->GetInternalField(0);
if (field.IsEmpty() || field->IsNullOrUndefined() || !field->IsExternal()) {
return nullptr;
}
return static_cast<BaseDataWrapper*>(field.As<External>()->Value());
}
Local<Value> metadataProp = tns::GetPrivateValue(obj, tns::ToV8String(isolate, "metadata"));
if (metadataProp.IsEmpty() || metadataProp->IsNullOrUndefined() || !metadataProp->IsExternal()) {
return nullptr;
}
return static_cast<BaseDataWrapper*>(metadataProp.As<External>()->Value());
}
void tns::DeleteValue(Isolate* isolate, const Local<Value>& val) {
if (val.IsEmpty() || val->IsNullOrUndefined() || !val->IsObject()) {
return;
}
Local<Object> obj = val.As<Object>();
if (obj->InternalFieldCount() > 0) {
obj->SetInternalField(0, v8::Undefined(isolate));
return;
}
Local<v8::String> metadataKey = tns::ToV8String(isolate, "metadata");
Local<Value> metadataProp = tns::GetPrivateValue(obj, metadataKey);
if (metadataProp.IsEmpty() || metadataProp->IsNullOrUndefined() || !metadataProp->IsExternal()) {
return;
}
Local<Context> context;
bool success = obj->GetCreationContext().ToLocal(&context);
tns::Assert(success, isolate);
Local<Private> privateKey = Private::ForApi(isolate, metadataKey);
success = obj->DeletePrivate(context, privateKey).FromMaybe(false);
tns::Assert(success, isolate);
}
std::vector<Local<Value>> tns::ArgsToVector(const FunctionCallbackInfo<Value>& info) {
std::vector<Local<Value>> args;
args.reserve(info.Length());
for (int i = 0; i < info.Length(); i++) {
args.push_back(info[i]);
}
return args;
}
bool tns::IsArrayOrArrayLike(Isolate* isolate, const Local<Value>& value) {
if (value->IsArray()) {
return true;
}
if (!value->IsObject()) {
return false;
}
Local<Object> obj = value.As<Object>();
Local<Context> context;
bool success = obj->GetCreationContext().ToLocal(&context);
tns::Assert(success, isolate);
return obj->Has(context, ToV8String(isolate, "length")).FromMaybe(false);
}
void* tns::TryGetBufferFromArrayBuffer(const v8::Local<v8::Value>& value, bool& isArrayBuffer) {
isArrayBuffer = false;
if (value.IsEmpty() || (!value->IsArrayBuffer() && !value->IsArrayBufferView())) {
return nullptr;
}
Local<ArrayBuffer> buffer;
if (value->IsArrayBufferView()) {
isArrayBuffer = true;
buffer = value.As<ArrayBufferView>()->Buffer();
} else if (value->IsArrayBuffer()) {
isArrayBuffer = true;
buffer = value.As<ArrayBuffer>();
}
if (buffer.IsEmpty()) {
return nullptr;
}
void* data = buffer->GetBackingStore()->Data();
return data;
}
struct LockAndCV {
std::mutex m;
std::condition_variable cv;
};
void tns::ExecuteOnRunLoop(CFRunLoopRef queue, void (^func)(void), bool async) {
if(!async) {
bool __block finished = false;
auto v = new LockAndCV;
std::unique_lock<std::mutex> lock(v->m);
CFRunLoopPerformBlock(queue, kCFRunLoopCommonModes, ^(void) {
func();
{
std::unique_lock lk(v->m);
finished = true;
}
v->cv.notify_all();
});
CFRunLoopWakeUp(queue);
while(!finished) {
v->cv.wait(lock);
}
delete v;
} else {
CFRunLoopPerformBlock(queue, kCFRunLoopCommonModes, func);
CFRunLoopWakeUp(queue);
}
}
void tns::ExecuteOnDispatchQueue(dispatch_queue_t queue, std::function<void()> func, bool async) {
if (async) {
dispatch_async(queue, ^(void) {
func();
});
} else {
dispatch_sync(queue, ^(void) {
func();
});
}
}
void tns::ExecuteOnMainThread(std::function<void()> func, bool async) {
if (async) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
func();
});
} else {
dispatch_sync(dispatch_get_main_queue(), ^(void) {
func();
});
}
}
void tns::LogError(Isolate* isolate, TryCatch& tc) {
if (!tc.HasCaught()) {
return;
}
Log(@"Native stack trace:");
LogBacktrace();
Local<Value> stack;
Local<Context> context = isolate->GetCurrentContext();
bool success = tc.StackTrace(context).ToLocal(&stack);
if (!success || stack.IsEmpty()) {
return;
}
Local<v8::String> stackV8Str;
success = stack->ToDetailString(context).ToLocal(&stackV8Str);
if (!success || stackV8Str.IsEmpty()) {
return;
}
std::string stackTraceStr = tns::ToString(isolate, stackV8Str);
stackTraceStr = ReplaceAll(stackTraceStr, RuntimeConfig.BaseDir, "");
Log(@"JavaScript error:");
Log(@"%s", stackTraceStr.c_str());
}
Local<v8::String> tns::JsonStringifyObject(Local<Context> context, Local<Value> value,
bool handleCircularReferences) {
Isolate* isolate = context->GetIsolate();
if (value.IsEmpty()) {
return v8::String::Empty(isolate);
}
if (handleCircularReferences) {
Local<v8::Function> smartJSONStringifyFunction = tns::GetSmartJSONStringifyFunction(isolate);
if (!smartJSONStringifyFunction.IsEmpty()) {
if (value->IsObject()) {
Local<Value> resultValue;
TryCatch tc(isolate);
Local<Value> args[] = {value->ToObject(context).ToLocalChecked()};
bool success = smartJSONStringifyFunction->Call(context, v8::Undefined(isolate), 1, args)
.ToLocal(&resultValue);
if (success && !tc.HasCaught()) {
return resultValue->ToString(context).ToLocalChecked();
}
}
}
}
Local<v8::String> resultString;
TryCatch tc(isolate);
bool success = v8::JSON::Stringify(context, value->ToObject(context).ToLocalChecked())
.ToLocal(&resultString);
if (!success && tc.HasCaught()) {
tns::LogError(isolate, tc);
return Local<v8::String>();
}
return resultString;
}
Local<v8::Function> tns::GetSmartJSONStringifyFunction(Isolate* isolate) {
std::shared_ptr<Caches> caches = Caches::Get(isolate);
if (caches->SmartJSONStringifyFunc != nullptr) {
return caches->SmartJSONStringifyFunc->Get(isolate);
}
std::string smartStringifyFunctionScript =
"(function () {\n"
" function smartStringify(object) {\n"
" const seen = [];\n"
" var replacer = function (key, value) {\n"
" if (value != null && typeof value == \"object\") {\n"
" if (seen.indexOf(value) >= 0) {\n"
" if (key) {\n"
" return \"[Circular]\";\n"
" }\n"
" return;\n"
" }\n"
" seen.push(value);\n"
" }\n"
" return value;\n"
" };\n"
" return JSON.stringify(object, replacer, 2);\n"
" }\n"
" return smartStringify;\n"
"})();";
Local<v8::String> source = tns::ToV8String(isolate, smartStringifyFunctionScript);
Local<Context> context = isolate->GetCurrentContext();
Local<Script> script;
bool success = Script::Compile(context, source).ToLocal(&script);
tns::Assert(success, isolate);
if (script.IsEmpty()) {
return Local<v8::Function>();
}
Local<Value> result;
success = script->Run(context).ToLocal(&result);
tns::Assert(success, isolate);
if (result.IsEmpty() && !result->IsFunction()) {
return Local<v8::Function>();
}
Local<v8::Function> smartStringifyFunction = result.As<v8::Function>();
caches->SmartJSONStringifyFunc =
std::make_unique<Persistent<v8::Function>>(isolate, smartStringifyFunction);
return smartStringifyFunction;
}
std::string tns::ReplaceAll(const std::string source, std::string find, std::string replacement) {
std::string result = source;
size_t pos = result.find(find);
while (pos != std::string::npos) {
result.replace(pos, find.size(), replacement);
pos = result.find(find, pos + replacement.size());
}
return result;
}
void tns::LogBacktrace(int skip) {
void* callstack[128];
const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
char buf[1024];
int nFrames = backtrace(callstack, nMaxFrames);
char** symbols = backtrace_symbols(callstack, nFrames);
for (int i = skip; i < nFrames; i++) {
Dl_info info;
if (dladdr(callstack[i], &info) && info.dli_sname) {
char* demangled = NULL;
int status = -1;
if (info.dli_sname[0] == '_') {
demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
}
snprintf(buf, sizeof(buf), "%-3d %*p %s + %zd\n", i, int(2 + sizeof(void*) * 2), callstack[i],
status == 0 ? demangled : info.dli_sname == 0 ? symbols[i] : info.dli_sname,
(char*)callstack[i] - (char*)info.dli_saddr);
free(demangled);
} else {
snprintf(buf, sizeof(buf), "%-3d %*p %s\n", i, int(2 + sizeof(void*) * 2), callstack[i],
symbols[i]);
}
Log(@"%s", buf);
}
free(symbols);
if (nFrames == nMaxFrames) {
Log(@"[truncated]");
}
}
const std::string tns::GetStackTrace(Isolate* isolate) {
Local<StackTrace> stack =
StackTrace::CurrentStackTrace(isolate, 10, StackTrace::StackTraceOptions::kDetailed);
int framesCount = stack->GetFrameCount();
std::stringstream ss;
for (int i = 0; i < framesCount; i++) {
Local<StackFrame> frame = stack->GetFrame(isolate, i);
ss << BuildStacktraceFrameMessage(isolate, frame) << std::endl;
}
return ss.str();
}
const std::string tns::GetCurrentScriptUrl(Isolate* isolate) {
Local<StackTrace> stack =
StackTrace::CurrentStackTrace(isolate, 1, StackTrace::StackTraceOptions::kDetailed);
int framesCount = stack->GetFrameCount();
if (framesCount > 0) {
Local<StackFrame> frame = stack->GetFrame(isolate, 0);
return tns::BuildStacktraceFrameLocationPart(isolate, frame);
}
return "";
}
std::string tns::RemapStackTraceIfAvailable(Isolate* isolate, const std::string& stackTrace) {
if (stackTrace.empty()) {
return stackTrace;
}
if (isolate == nullptr) {
return stackTrace;
}
v8::Locker locker(isolate);
Isolate::Scope isolateScope(isolate);
HandleScope handleScope(isolate);
Local<Context> context = Caches::Get(isolate)->GetContext();
if (context.IsEmpty()) {
return stackTrace;
}
Context::Scope contextScope(context);
Local<Object> global = context->Global();
Local<Value> remapFnVal;
bool hasRemap =
global->Get(context, tns::ToV8String(isolate, "__ns_remapStack")).ToLocal(&remapFnVal);
if (hasRemap && remapFnVal->IsFunction()) {
Local<v8::Function> remapFn = remapFnVal.As<v8::Function>();
Local<Value> args[] = {tns::ToV8String(isolate, stackTrace)};
Local<Value> remapped;
if (remapFn->Call(context, global, 1, args).ToLocal(&remapped) && remapped->IsString()) {
return tns::ToString(isolate, remapped.As<v8::String>());
}
}
return stackTrace;
}
std::string tns::GetSmartStackTrace(Isolate* isolate, v8::TryCatch* tryCatch,
v8::Local<v8::Value> exception) {
std::string stack;
Local<Context> context = isolate->GetCurrentContext();
// 1) Prefer exception.stack when provided
if (!exception.IsEmpty()) {
if (exception->IsObject()) {
Local<Object> excObj = exception.As<Object>();
Local<Value> stackVal;
if (excObj->Get(context, tns::ToV8String(isolate, "stack")).ToLocal(&stackVal) &&
stackVal->IsString()) {
stack = tns::ToString(isolate, stackVal.As<v8::String>());
}
}
// Fallback to v8::Exception::GetStackTrace on the exception value
if (stack.empty()) {
Local<StackTrace> v8Stack = v8::Exception::GetStackTrace(exception);
if (!v8Stack.IsEmpty()) {
int framesCount = v8Stack->GetFrameCount();
std::stringstream ss;
for (int i = 0; i < framesCount; i++) {
Local<StackFrame> frame = v8Stack->GetFrame(isolate, i);
ss << BuildStacktraceFrameMessage(isolate, frame) << std::endl;
}
stack = ss.str();
}
}
}
// 2) TryCatch-provided stack if available
if (stack.empty() && tryCatch != nullptr) {
Local<Value> stackVal;
if (tryCatch->StackTrace(context).ToLocal(&stackVal) && stackVal->IsString()) {
stack = tns::ToString(isolate, stackVal.As<v8::String>());
} else {
Local<Message> message = tryCatch->Message();
if (!message.IsEmpty()) {
Local<StackTrace> v8Stack = message->GetStackTrace();
if (!v8Stack.IsEmpty()) {
int framesCount = v8Stack->GetFrameCount();
std::stringstream ss;
for (int i = 0; i < framesCount; i++) {
Local<StackFrame> frame = v8Stack->GetFrame(isolate, i);
ss << BuildStacktraceFrameMessage(isolate, frame) << std::endl;
}
stack = ss.str();
}
}
}
}
// 3) Finally, current stack if still empty
if (stack.empty()) {
stack = tns::GetStackTrace(isolate);
}
return stack;
}
const std::string tns::BuildStacktraceFrameLocationPart(Isolate* isolate, Local<StackFrame> frame) {
std::stringstream ss;
Local<v8::String> scriptName = frame->GetScriptNameOrSourceURL();
std::string scriptNameStr = tns::ToString(isolate, scriptName);
scriptNameStr = tns::ReplaceAll(scriptNameStr, RuntimeConfig.BaseDir, "");
if (scriptNameStr.length() < 1) {
ss << "VM";
} else {
ss << scriptNameStr << ":" << frame->GetLineNumber() << ":" << frame->GetColumn();
}
std::string stringResult = ss.str();
return stringResult;
}
const std::string tns::BuildStacktraceFrameMessage(Isolate* isolate, Local<StackFrame> frame) {
std::stringstream ss;
Local<v8::String> functionName = frame->GetFunctionName();
std::string functionNameStr = tns::ToString(isolate, functionName);
if (functionNameStr.empty()) {
functionNameStr = "<anonymous>";
}
if (frame->IsConstructor()) {
ss << "at new " << functionNameStr << " ("
<< tns::BuildStacktraceFrameLocationPart(isolate, frame) << ")";
} else if (frame->IsEval()) {
ss << "eval at " << BuildStacktraceFrameLocationPart(isolate, frame) << std::endl;
} else {
ss << "at " << functionNameStr << " (" << tns::BuildStacktraceFrameLocationPart(isolate, frame)
<< ")";
}
std::string stringResult = ss.str();
return stringResult;
}
bool tns::LiveSync(Isolate* isolate) {
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
std::shared_ptr<Caches> cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
Local<Object> global = context->Global();
Local<Value> value;
bool success = global->Get(context, tns::ToV8String(isolate, "__onLiveSync")).ToLocal(&value);
if (!success || value.IsEmpty() || !value->IsFunction()) {
return false;
}
Local<v8::Function> liveSyncFunc = value.As<v8::Function>();
Local<Value> args[0];
Local<Value> result;
TryCatch tc(isolate);
success = liveSyncFunc->Call(context, v8::Undefined(isolate), 0, args).ToLocal(&result);
if (!success || tc.HasCaught()) {
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
return false;
}
return true;
}
void tns::Assert(bool condition, Isolate* isolate, std::string const& reason) {
if (!RuntimeConfig.IsDebug) {
assert(condition);
return;
}
if (condition) {
return;
}
if (isolate == nullptr) {
Runtime* runtime = Runtime::GetCurrentRuntime();
if (runtime != nullptr) {
isolate = runtime->GetIsolate();
}
}
if (isolate == nullptr) {
Log(@"====== Assertion failed ======");
if (!reason.empty()) {
Log(@"Reason: %s", reason.c_str());
}
Log(@"Native stack trace:");
LogBacktrace();
assert(false);
return;
}
Log(@"====== Assertion failed ======");
Log(@"Native stack trace:");
LogBacktrace();
Log(@"JavaScript stack trace:");
std::string stack = tns::GetStackTrace(isolate);
Log(@"%s", stack.c_str());
assert(false);
}
void tns::StopExecutionAndLogStackTrace(v8::Isolate* isolate) { Assert(false, isolate); }
namespace tns {
Local<v8::FunctionTemplate> NewFunctionTemplate(v8::Isolate* isolate, v8::FunctionCallback callback,
Local<v8::Value> data,
Local<v8::Signature> signature,
v8::ConstructorBehavior behavior,
v8::SideEffectType side_effect_type,
const v8::CFunction* c_function) {
return v8::FunctionTemplate::New(isolate, callback, data, signature, 0, behavior,
side_effect_type, c_function);
}
void SetMethod(Local<v8::Context> context, Local<v8::Object> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Isolate* isolate = context->GetIsolate();
Local<v8::Function> function =
NewFunctionTemplate(isolate, callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect)
->GetFunction(context)
.ToLocalChecked();
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(context, name_string, function).Check();
function->SetName(name_string); // NODE_SET_METHOD() compatibility.
}
void SetMethod(v8::Isolate* isolate, v8::Local<v8::Template> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(name_string, t);
}
void SetFastMethod(Isolate* isolate, Local<Template> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
Local<v8::Value> data) {
Local<v8::FunctionTemplate> t = NewFunctionTemplate(
isolate, slow_callback, data, Local<v8::Signature>(), v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasSideEffect, c_function);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(name_string, t);
}
void SetFastMethod(Local<v8::Context> context, Local<v8::Object> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
Local<v8::Value> data) {
Isolate* isolate = context->GetIsolate();
Local<v8::Function> function =
NewFunctionTemplate(isolate, slow_callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasSideEffect,
c_function)
->GetFunction(context)
.ToLocalChecked();
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(context, name_string, function).Check();
}
void SetFastMethodNoSideEffect(Local<v8::Context> context, Local<v8::Object> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
Local<v8::Value> data) {
Isolate* isolate = context->GetIsolate();
Local<v8::Function> function =
NewFunctionTemplate(isolate, slow_callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect,
c_function)
->GetFunction(context)
.ToLocalChecked();
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(context, name_string, function).Check();
}
void SetFastMethodNoSideEffect(Isolate* isolate, Local<Template> that, const char* name,
v8::FunctionCallback slow_callback, const v8::CFunction* c_function,
Local<v8::Value> data) {
Local<v8::FunctionTemplate> t = NewFunctionTemplate(
isolate, slow_callback, data, Local<v8::Signature>(), v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasNoSideEffect, c_function);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(name_string, t);
}
void SetMethodNoSideEffect(Local<v8::Context> context, Local<v8::Object> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Isolate* isolate = context->GetIsolate();
Local<v8::Function> function =
NewFunctionTemplate(isolate, callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect)
->GetFunction(context)
.ToLocalChecked();
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(context, name_string, function).Check();
function->SetName(name_string); // NODE_SET_METHOD() compatibility.
}
void SetMethodNoSideEffect(Isolate* isolate, Local<v8::Template> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow, v8::SideEffectType::kHasNoSideEffect);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(name_string, t);
}
void SetProtoMethod(v8::Isolate* isolate, Local<v8::FunctionTemplate> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, callback, data, signature, v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasSideEffect);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->PrototypeTemplate()->Set(name_string, t);
t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility.
}
void SetProtoMethodNoSideEffect(v8::Isolate* isolate, Local<v8::FunctionTemplate> that,
const char* name, v8::FunctionCallback callback,
Local<v8::Value> data) {
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, callback, data, signature, v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasNoSideEffect);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->PrototypeTemplate()->Set(name_string, t);
t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility.
}
void SetInstanceMethod(v8::Isolate* isolate, Local<v8::FunctionTemplate> that, const char* name,
v8::FunctionCallback callback, Local<v8::Value> data) {
Local<v8::Signature> signature = v8::Signature::New(isolate, that);
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, callback, data, signature, v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasSideEffect);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string = v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->InstanceTemplate()->Set(name_string, t);
t->SetClassName(name_string);
}
void SetConstructorFunction(Local<v8::Context> context, Local<v8::Object> that, const char* name,
Local<v8::FunctionTemplate> tmpl, SetConstructorFunctionFlag flag) {
Isolate* isolate = context->GetIsolate();
SetConstructorFunction(context, that, tns::OneByteString(isolate, name), tmpl, flag);
}
void SetConstructorFunction(Local<Context> context, Local<Object> that, Local<v8::String> name,
Local<FunctionTemplate> tmpl, SetConstructorFunctionFlag flag) {
if (flag == SetConstructorFunctionFlag::SET_CLASS_NAME) tmpl->SetClassName(name);
that->Set(context, name, tmpl->GetFunction(context).ToLocalChecked()).Check();
}
void SetConstructorFunction(Isolate* isolate, Local<Template> that, const char* name,
Local<FunctionTemplate> tmpl, SetConstructorFunctionFlag flag) {
SetConstructorFunction(isolate, that, OneByteString(isolate, name), tmpl, flag);
}
void SetConstructorFunction(Isolate* isolate, Local<Template> that, Local<v8::String> name,
Local<FunctionTemplate> tmpl, SetConstructorFunctionFlag flag) {
if (flag == SetConstructorFunctionFlag::SET_CLASS_NAME) tmpl->SetClassName(name);
that->Set(name, tmpl);
}
};