Repository navigation
Expand file tree
/
Copy pathHelpers.mm
More file actions
1141 lines (997 loc) · 38.3 KB
/
Copy pathHelpers.mm
File metadata and controls
1141 lines (997 loc) · 38.3 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
#include "Helpers.h"
#include <Foundation/Foundation.h>
#include <cxxabi.h>
#include <dispatch/dispatch.h>
#include <dlfcn.h>
#include <execinfo.h>
#include <objc/runtime.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <atomic>
#include <cerrno>
#include <mutex>
#include <sstream>
#include <vector>
#include "Caches.h"
#include "ErrorEvents.h"
#include "NativeScriptException.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
using namespace v8;
std::u16string tns::ToUtf16String(Isolate* isolate, const Local<Value>& value) {
// Read the V8 string's native UTF-16 buffer directly instead of round-tripping
// through UTF-8, which corrupts lone surrogates (replaced with U+FFFD) and is
// slower. This also drops the deprecated std::codecvt_utf8_utf16.
if (value.IsEmpty()) {
return std::u16string();
}
if (value->IsStringObject()) {
Local<v8::String> obj = value.As<StringObject>()->ValueOf();
return tns::ToUtf16String(isolate, obj);
}
Local<v8::String> str;
if (!value->ToString(isolate->GetCurrentContext()).ToLocal(&str)) {
return std::u16string();
}
v8::String::ValueView result(isolate, str);
if (result.is_one_byte()) {
// A one-byte V8 string is Latin-1, so widening each byte is the conversion.
const uint8_t* data = result.data8();
return std::u16string(data, data + result.length());
}
return std::u16string((const char16_t*)result.data16(), result.length());
}
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;
}
// The file readers below run on the main thread and on every worker's thread
// at once (workers load shared modules and their code caches while starting),
// so each call reads into storage of its own; no scratch buffer is shared.
std::string tns::ReadText(const std::string& filePath) {
FILE* file = fopen(filePath.c_str(), "rb");
if (file == nullptr) {
tns::Assert(false);
}
fseek(file, 0, SEEK_END);
long length = ftell(file);
rewind(file);
std::string result;
if (length > 0) {
result.resize(length);
size_t readBytes = fread(result.data(), 1, length, file);
result.resize(readBytes);
}
fclose(file);
return result;
}
uint8_t* tns::ReadBinary(const std::string& path, long& length) {
length = 0;
FILE* file = fopen(path.c_str(), "rb");
if (!file) {
return nullptr;
}
fseek(file, 0, SEEK_END);
long fileLength = ftell(file);
rewind(file);
if (fileLength <= 0) {
fclose(file);
return nullptr;
}
uint8_t* data = new uint8_t[fileLength];
size_t readBytes = fread(data, sizeof(uint8_t), fileLength, file);
fclose(file);
if (readBytes != static_cast<size_t>(fileLength)) {
delete[] data;
return nullptr;
}
length = fileLength;
return data;
}
bool tns::WriteBinary(const std::string& path, const void* data, long length,
time_t modificationTime) {
// Written to a private temp file in the same directory, then renamed over the
// target: rename is atomic on the local file system, so a concurrent reader
// of `path` never observes a truncated or half-written file, and two writers
// racing on the same path leave whichever complete file landed last.
std::string tmpTemplate = path + ".XXXXXX";
std::vector<char> tmpPath(tmpTemplate.begin(), tmpTemplate.end());
tmpPath.push_back('\0');
int fd = mkstemp(tmpPath.data());
if (fd < 0) {
return false;
}
bool ok = true;
const uint8_t* cursor = static_cast<const uint8_t*>(data);
long remaining = length;
while (remaining > 0) {
ssize_t written = write(fd, cursor, remaining);
if (written < 0) {
if (errno == EINTR) {
continue;
}
ok = false;
break;
}
cursor += written;
remaining -= written;
}
if (ok && modificationTime >= 0) {
struct timespec times[2];
times[0].tv_sec = time(nullptr);
times[0].tv_nsec = 0;
times[1].tv_sec = modificationTime;
times[1].tv_nsec = 0;
ok = futimens(fd, times) == 0;
}
close(fd);
if (ok && rename(tmpPath.data(), path.c_str()) != 0) {
ok = false;
}
if (!ok) {
unlink(tmpPath.data());
}
return ok;
}
void tns::SetPrivateValue(const Local<Object>& obj, const Local<v8::String>& propName,
const Local<Value>& value) {
Local<Context> context;
bool success = obj->GetCreationContext(v8::Isolate::GetCurrent()).ToLocal(&context);
tns::Assert(success);
Isolate* isolate = v8::Isolate::GetCurrent();
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(v8::Isolate::GetCurrent()).ToLocal(&context);
tns::Assert(success);
Isolate* isolate = v8::Isolate::GetCurrent();
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, v8::kExternalPointerTypeTagDefault);
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).As<v8::Value>();
if (field.IsEmpty() || field->IsNullOrUndefined() || !field->IsExternal()) {
return nullptr;
}
return static_cast<BaseDataWrapper*>(
field.As<External>()->Value(v8::kExternalPointerTypeTagDefault));
}
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(v8::kExternalPointerTypeTagDefault));
}
namespace {
std::atomic<int> releasedObjectPolicy_{static_cast<int>(tns::ReleasedObjectPolicy::kReport)};
struct ReleasedAccessReport {
v8::Isolate* isolate;
v8::Global<v8::Value> error;
std::string operation;
};
// Runs on the isolate's microtask queue: dispatching from the touch site
// itself would run arbitrary app JS in the middle of an interop marshal.
void DispatchReleasedAccessMicrotask(void* data) {
std::unique_ptr<ReleasedAccessReport> report(static_cast<ReleasedAccessReport*>(data));
v8::Isolate* isolate = report->isolate;
v8::HandleScope scope(isolate);
tns::ErrorEvents::DispatchReleasedNativeAccess(isolate, report->error.Get(isolate),
report->operation);
}
} // namespace
tns::ReleasedObjectPolicy tns::GetReleasedObjectPolicy() {
return static_cast<ReleasedObjectPolicy>(releasedObjectPolicy_.load(std::memory_order_relaxed));
}
void tns::SetReleasedObjectPolicy(ReleasedObjectPolicy policy) {
releasedObjectPolicy_.store(static_cast<int>(policy), std::memory_order_relaxed);
}
namespace {
// Index-aligned with tns::LogCategory; the only place a category name lives.
constexpr const char* kLogCategoryNames[] = {"esm", "fetch", "registry"};
constexpr size_t kLogCategoryCount = static_cast<size_t>(tns::LogCategory::kCount);
static_assert(sizeof(kLogCategoryNames) / sizeof(kLogCategoryNames[0]) == kLogCategoryCount,
"every LogCategory needs exactly one name");
#if TNS_HAVE_OS_LOG
// One os_log_t per category, created once: Console.app and `log stream` can
// then filter by subsystem/category without parsing message text.
os_log_t LogHandleFor(tns::LogCategory category) {
static os_log_t handles[kLogCategoryCount];
static std::once_flag handlesInit;
std::call_once(handlesInit, []() {
for (size_t i = 0; i < kLogCategoryCount; ++i) {
handles[i] = os_log_create("org.nativescript.runtime", kLogCategoryNames[i]);
}
});
return handles[static_cast<size_t>(category)];
}
#endif
void WriteDebugLine(tns::LogCategory category, const char* message) {
const char* name = tns::LogCategoryName(category);
#if TNS_HAVE_OS_LOG
os_log(LogHandleFor(category), "[%{public}s] %{public}s", name, message);
#else
Log("[%s] %s", name, message);
#endif
}
std::string TrimAsciiSpace(const std::string& value) {
size_t begin = value.find_first_not_of(" \t");
if (begin == std::string::npos) {
return std::string();
}
size_t end = value.find_last_not_of(" \t");
return value.substr(begin, end - begin + 1);
}
} // namespace
const char* tns::LogCategoryName(LogCategory category) {
size_t index = static_cast<size_t>(category);
return index < kLogCategoryCount ? kLogCategoryNames[index] : "unknown";
}
std::string tns::AllLogCategoryNames() {
std::string names;
for (size_t i = 0; i < kLogCategoryCount; ++i) {
if (!names.empty()) {
names += ",";
}
names += kLogCategoryNames[i];
}
return names;
}
uint32_t tns::ParseLogCategories(const std::string& list, bool* hadUnknown) {
if (hadUnknown != nullptr) {
*hadUnknown = false;
}
uint32_t mask = 0;
size_t start = 0;
while (start <= list.size()) {
size_t comma = list.find(',', start);
size_t length = comma == std::string::npos ? std::string::npos : comma - start;
std::string name = TrimAsciiSpace(list.substr(start, length));
if (!name.empty()) {
bool matched = false;
for (size_t i = 0; i < kLogCategoryCount; ++i) {
if (name == kLogCategoryNames[i]) {
mask |= 1u << i;
matched = true;
break;
}
}
if (!matched && hadUnknown != nullptr) {
*hadUnknown = true;
}
}
if (comma == std::string::npos) {
break;
}
start = comma + 1;
}
return mask;
}
std::string tns::EnabledLogCategoryNames() {
uint32_t mask = g_enabledLogCategories.load(std::memory_order_relaxed);
std::string names;
for (size_t i = 0; i < kLogCategoryCount; ++i) {
if ((mask & (1u << i)) == 0) {
continue;
}
if (!names.empty()) {
names += ",";
}
names += kLogCategoryNames[i];
}
return names;
}
void tns::SetEnabledLogCategories(uint32_t mask) {
g_enabledLogCategories.store(mask, std::memory_order_relaxed);
}
void tns::InitializeLogCategoriesFromEnvironment() {
const char* value = getenv("NS_DEBUG");
if (value == nullptr || *value == '\0') {
return;
}
bool hadUnknown = false;
SetEnabledLogCategories(ParseLogCategories(value, &hadUnknown));
if (hadUnknown) {
Log("NS_DEBUG: ignoring unknown categories in '%s'; valid categories are %s", value,
AllLogCategoryNames().c_str());
}
}
void tns::EmitDebugLog(LogCategory category, const char* format, ...) {
va_list ap;
va_start(ap, format);
char stackBuffer[1024];
va_list apCopy;
va_copy(apCopy, ap);
int needed = vsnprintf(stackBuffer, sizeof(stackBuffer), format, apCopy);
va_end(apCopy);
if (needed < 0) {
va_end(ap);
return;
}
if (static_cast<size_t>(needed) < sizeof(stackBuffer)) {
WriteDebugLine(category, stackBuffer);
} else {
std::vector<char> heapBuffer(static_cast<size_t>(needed) + 1);
vsnprintf(heapBuffer.data(), heapBuffer.size(), format, ap);
WriteDebugLine(category, heapBuffer.data());
}
va_end(ap);
}
tns::BaseDataWrapper* tns::GetValueOrReport(Isolate* isolate, const Local<Value>& val,
const char* operation) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, val);
if (wrapper != nullptr) {
return wrapper;
}
std::string message =
std::string("The native object has been released or is not a valid native object (") +
operation + ")";
if (GetReleasedObjectPolicy() == ReleasedObjectPolicy::kThrow) {
isolate->ThrowException(v8::Exception::ReferenceError(tns::ToV8String(isolate, message)));
return nullptr;
}
Local<Context> context = isolate->GetCurrentContext();
if (val->IsObject()) {
// One report per husk object: a released buffer touched in a tight loop
// must not flood the event queue.
Local<Private> reported =
Private::ForApi(isolate, tns::ToV8String(isolate, "ns:releasedAccessReported"));
Local<Object> obj = val.As<Object>();
if (obj->HasPrivate(context, reported).FromMaybe(false)) {
return nullptr;
}
obj->SetPrivate(context, reported, v8::True(isolate)).FromMaybe(false);
}
// The error is created here so its stack names the touch site.
Local<Value> error = v8::Exception::ReferenceError(tns::ToV8String(isolate, message));
auto* report =
new ReleasedAccessReport{isolate, v8::Global<v8::Value>(isolate, error), operation};
isolate->EnqueueMicrotask(DispatchReleasedAccessMicrotask, report);
return nullptr;
}
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(v8::Isolate::GetCurrent()).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(v8::Isolate::GetCurrent()).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() && !value->IsSharedArrayBuffer())) {
return nullptr;
}
std::shared_ptr<BackingStore> backingStore;
size_t byteOffset = 0;
if (value->IsArrayBufferView()) {
isArrayBuffer = true;
auto view = value.As<ArrayBufferView>();
byteOffset = view->ByteOffset();
auto buffer = view->Buffer();
if (!buffer.IsEmpty()) {
backingStore = buffer->GetBackingStore();
}
} else if (value->IsArrayBuffer()) {
isArrayBuffer = true;
backingStore = value.As<ArrayBuffer>()->GetBackingStore();
} else if (value->IsSharedArrayBuffer()) {
isArrayBuffer = true;
backingStore = value.As<SharedArrayBuffer>()->GetBackingStore();
}
if (!backingStore) {
return nullptr;
}
uint8_t* data = static_cast<uint8_t*>(backingStore->Data());
if (data == nullptr) {
return nullptr;
}
return data + byteOffset;
}
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());
}
std::string tns::GetNativeWrapperHint(Isolate* isolate, const Local<Value>& value) {
BaseDataWrapper* wrapper = tns::GetValue(isolate, value);
if (wrapper == nullptr) {
return std::string();
}
switch (wrapper->Type()) {
case WrapperType::ObjCObject: {
id data = static_cast<ObjCDataWrapper*>(wrapper)->Data();
return data != nil ? std::string(object_getClassName(data)) : "ObjCObject";
}
case WrapperType::ObjCClass: {
Class klass = static_cast<ObjCClassWrapper*>(wrapper)->Klass();
return klass != nil ? "class " + std::string(class_getName(klass)) : "ObjCClass";
}
case WrapperType::ObjCProtocol: {
Protocol* proto = static_cast<ObjCProtocolWrapper*>(wrapper)->Proto();
return proto != nil ? "protocol " + std::string(protocol_getName(proto)) : "ObjCProtocol";
}
case WrapperType::Pointer:
return "Pointer";
case WrapperType::Block:
return "Block";
case WrapperType::Function:
return "NativeFunction";
default:
// Remaining wrapper kinds (structs, references, enums, ...) format fine
// through the ordinary object path.
return std::string();
}
}
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 = v8::Isolate::GetCurrent();
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.
}