-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathNativeScriptException.mm
More file actions
1621 lines (1441 loc) · 64.5 KB
/
Copy pathNativeScriptException.mm
File metadata and controls
1621 lines (1441 loc) · 64.5 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 "NativeScriptException.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import <UIKit/UIKit.h>
#if __has_include(<UniformTypeIdentifiers/UniformTypeIdentifiers.h>)
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#endif
#include <TargetConditionals.h>
#import <objc/message.h>
#import <objc/runtime.h>
#include <algorithm>
#include <limits>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include "ArgConverter.h"
#include "Caches.h"
#include "DataWrapper.h"
#include "ErrorEvents.h"
#include "Helpers.h"
#include "NSExceptionSupport.h"
#include "Runtime.h"
#include "RuntimeConfig.h"
using namespace v8;
namespace {
static UITextView* gErrorStackTextView = nil;
static NSString* gLatestStackText = nil;
struct PendingErrorDisplay {
uint64_t ticket = 0;
bool contextCaptured = false;
bool modalPresented = false;
bool fallbackScheduled = false;
v8::Isolate* isolate = nullptr;
std::string title;
std::string message;
std::string rawStack;
std::string canonicalStack;
std::string consolePayload;
};
static std::mutex gErrorDisplayMutex;
static PendingErrorDisplay gPendingErrorDisplay;
static uint64_t gNextErrorTicket = 1;
// Per-isolate uncaughtErrorPolicy "throw" handoff slot. The NSException lifetime
// is managed by ARC (__strong) — fine in this .mm. Heap-allocated and never
// destroyed: ~Runtime reaches this registry via OnIsolateTeardown, and a global
// Runtime can be destructed during __cxa_finalize at process exit — after this
// TU's file-scope statics would have been destroyed. Locking a destroyed
// std::mutex throws std::system_error out of the noexcept destructor chain and
// terminates the process, so the registry must outlive all static destructors.
static std::mutex& PolicyThrowMutex() {
static std::mutex* mutex = new std::mutex();
return *mutex;
}
static std::unordered_map<v8::Isolate*, NSException * __strong>& PendingPolicyThrows() {
static auto* map = new std::unordered_map<v8::Isolate*, NSException * __strong>();
return *map;
}
} // namespace
namespace tns {
extern bool isErrorDisplayShowing;
static void UpdateDisplayedStackText(const std::string& stackText);
static void RenderErrorModalUI(v8::Isolate* isolate, const std::string& title,
const std::string& message, const std::string& stackText);
static void ShowErrorModalSynchronously(const std::string& title, const std::string& message,
const std::string& stackTrace);
static void ScheduleFallbackPresentation(uint64_t ticket);
static void PresentFallbackIfNeeded(uint64_t ticket);
static std::string ResolveDisplayStack(const PendingErrorDisplay& state);
static void ConsiderStackCandidate(PendingErrorDisplay& state, v8::Isolate* isolate,
const std::string& candidateStack);
NativeScriptException::NativeScriptException(const std::string& message) {
this->javascriptException_ = nullptr;
this->message_ = message;
this->name_ = "NativeScriptException";
}
NativeScriptException::NativeScriptException(Isolate* isolate, TryCatch& tc,
const std::string& message) {
Local<Value> error = tc.Exception();
this->javascriptException_ = new Persistent<Value>(isolate, tc.Exception());
this->message_ = GetErrorMessage(isolate, error, message);
this->stackTrace_ = tns::GetSmartStackTrace(isolate, &tc, error);
this->fullMessage_ = GetFullMessage(isolate, tc, this->message_);
this->name_ = "NativeScriptException";
tc.Reset();
}
NativeScriptException::NativeScriptException(Isolate* isolate, const std::string& message,
const std::string& name) {
this->name_ = name;
Local<Value> error = Exception::Error(tns::ToV8String(isolate, message));
auto context = Caches::Get(isolate)->GetContext();
error.As<Object>()
->Set(context, ToV8String(isolate, "name"), ToV8String(isolate, this->name_))
.FromMaybe(false);
this->javascriptException_ = new Persistent<Value>(isolate, error);
this->message_ = GetErrorMessage(isolate, error, message);
this->stackTrace_ = GetErrorStackTrace(isolate, Exception::GetStackTrace(error));
this->fullMessage_ =
GetFullMessage(isolate, Exception::CreateMessage(isolate, error), this->message_);
}
NativeScriptException::NativeScriptException(Isolate* isolate, Local<Value> jsError,
const std::string& message) {
this->javascriptException_ = new Persistent<Value>(isolate, jsError);
this->message_ = message;
this->name_ = "NativeScriptException";
}
NativeScriptException::~NativeScriptException() { delete this->javascriptException_; }
void NativeScriptException::OnUncaughtError(Local<v8::Message> message, Local<Value> error) {
@try {
Isolate* isolate = v8::Isolate::GetCurrent();
ReportToJsHandlersAndLog(isolate, error, message);
} @catch (NSException* exception) {
Log(@"OnUncaughtError: Caught exception during error handling: %@", exception);
@throw exception;
}
}
// Defined below; needed by the escape-brand short-circuits in the reporters.
static void ScheduleDeferredThrow(v8::Isolate* isolate, NSException* e);
// An explicit interop.escapeException is a crash/forward request, never an
// error report: it must not dispatch events (preventDefault cannot veto it —
// matching Android, where the brand is checked before any dispatch), must not
// call the legacy hooks and must not log. Returns true when `value` carried the
// brand and the native throw was scheduled.
static bool ScheduleEscapedExceptionIfBranded(Isolate* isolate, Local<Value> value) {
Local<Context> context = isolate->GetCurrentContext();
NSException* branded = ArgConverter::ExtractEscapedException(context, value);
if (branded == nil) {
return false;
}
ScheduleDeferredThrow(isolate, branded);
return true;
}
void NativeScriptException::ReportToJsHandlersAndLog(Isolate* isolate, Local<Value> error,
Local<v8::Message> message,
const std::string& stackOverride,
const std::string& logPrefix) {
if (ScheduleEscapedExceptionIfBranded(isolate, error)) {
return;
}
// First: give `error` event listeners a chance. If one prevents the default,
// the report is fully handled — no shim, no fatal log.
std::string messageString;
if (!message.IsEmpty()) {
messageString = tns::ToString(isolate, message->Get());
} else {
messageString = tns::ToString(isolate, error);
}
// Derive the combined stack ONCE, with the full fallback chain ReportFatalTail
// uses (stackOverride → GetSmartStackTrace → v8::Message stack → the error's
// own stack), so the `error` event listeners and the fatal tail observe the
// same string.
std::string stackForEvent = stackOverride;
if (stackForEvent.empty()) {
stackForEvent = tns::GetSmartStackTrace(isolate, nullptr, error);
}
if (stackForEvent.empty()) {
if (!message.IsEmpty()) {
stackForEvent = GetErrorStackTrace(isolate, message->GetStackTrace());
} else {
// Rejections/reportError carry no v8::Message; fall back to the error's
// own stack.
stackForEvent = GetErrorStackTrace(isolate, Exception::GetStackTrace(error));
}
}
// Android sets a combined `stackTrace` property on the error object BEFORE
// dispatching the `error` event, so listeners can read `e.error.stackTrace`
// (not only `e.error.stack`). Mirror that here (object errors only; guarded /
// non-fatal on failure — same pattern ReportFatalTail uses). ReportFatalTail
// sets it again with the same value (idempotent) for callers that reach it
// directly (the nativeReportFatal handshake).
if (error->IsObject()) {
Local<Context> context = isolate->GetCurrentContext();
bool stackTraceSet = error.As<Object>()
->Set(context, tns::ToV8String(isolate, "stackTrace"),
tns::ToV8String(isolate, stackForEvent))
.FromMaybe(false);
if (!stackTraceSet) {
Log(@"Warning: Failed to set stackTrace property on error object");
}
}
if (ErrorEvents::DispatchError(isolate, error, messageString, stackForEvent)) {
return;
}
// Pass the already-derived stack down so ReportFatalTail does not re-derive it.
ReportFatalTail(isolate, error, message, stackForEvent, logPrefix);
}
void NativeScriptException::ReportUnhandledRejection(Isolate* isolate, Local<Promise> promise,
Local<Value> reason,
const std::string& stackOverride) {
if (ScheduleEscapedExceptionIfBranded(isolate, reason)) {
return;
}
if (ErrorEvents::DispatchUnhandledRejection(isolate, promise, reason)) {
return;
}
ReportFatalTail(isolate, reason, Local<v8::Message>(), stackOverride,
"Unhandled promise rejection:");
}
// Schedules an uncaught @throw on the runtime loop with a clean, V8-scope-free
// stack. Throwing synchronously from here is unsafe: ReportFatalTail runs inside
// V8 callbacks (message listener) or under the drain observer's V8 scopes. The
// deferred block runs on a frame with no V8 scopes, so the uncaught NSException
// terminates the app with a real crash report. Best-effort: silently returns if
// the runtime/loop is gone (e.g. during teardown).
static void ScheduleDeferredThrow(Isolate* isolate, NSException* e) {
Runtime* rt = Runtime::GetRuntime(isolate);
if (rt == nullptr) {
return;
}
auto loop = rt->GetEventLoop();
if (loop == nullptr) {
return;
}
// bare entry: runs with no V8 scopes and outside the loop's exception
// guard, so the NSException unwinds into the runloop frame
loop->PostInternalBare([e]() { @throw e; });
}
void NativeScriptException::DepositPendingPolicyThrow(Isolate* isolate, id exception) {
std::lock_guard<std::mutex> lock(PolicyThrowMutex());
PendingPolicyThrows()[isolate] = (NSException*)exception; // overwrites any prior entry
}
id NativeScriptException::ClaimPendingPolicyThrow(Isolate* isolate) {
std::lock_guard<std::mutex> lock(PolicyThrowMutex());
auto it = PendingPolicyThrows().find(isolate);
if (it == PendingPolicyThrows().end()) {
return nil;
}
NSException* e = it->second;
PendingPolicyThrows().erase(it);
return e;
}
id NativeScriptException::ClaimPendingPolicyThrowIfEqual(Isolate* isolate, id expected) {
std::lock_guard<std::mutex> lock(PolicyThrowMutex());
auto it = PendingPolicyThrows().find(isolate);
if (it == PendingPolicyThrows().end() || it->second != expected) {
return nil;
}
NSException* e = it->second;
PendingPolicyThrows().erase(it);
return e;
}
void NativeScriptException::OnIsolateTeardown(Isolate* isolate) {
std::lock_guard<std::mutex> lock(PolicyThrowMutex());
PendingPolicyThrows().erase(isolate);
}
void NativeScriptException::ReportFatalTail(Isolate* isolate, Local<Value> error,
Local<v8::Message> message,
const std::string& stackOverride,
const std::string& logPrefix) {
Local<Context> context = isolate->GetCurrentContext();
Local<Object> global = context->Global();
// A branded escapeException reaching the fatal tail (e.g. a listener did
// `throw interop.escapeException(x)`; the bootstrap routes listener throws to
// nativeReportFatal) is an explicit crash/forward request: skip shim + log and
// schedule the deferred @throw of the extracted NSException, regardless of the
// crash flag.
{
NSException* branded = ArgConverter::ExtractEscapedException(context, error);
if (branded != nil) {
ScheduleDeferredThrow(isolate, branded);
return;
}
}
Local<Value> handler;
// Deprecated: still honored in full (selects the __onDiscardedError callback
// and skips the fatal log), but new code should handle errors with an
// error/unhandledrejection listener calling preventDefault(), or set
// uncaughtErrorPolicy.
id value = Runtime::GetAppConfigValue("discardUncaughtJsExceptions");
bool isDiscarded = value ? [value boolValue] : false;
if (isDiscarded) {
static std::once_flag warnedDeprecated;
std::call_once(warnedDeprecated, []() {
Log(@"NativeScript: \"discardUncaughtJsExceptions\" is deprecated. Handle errors with a "
@"globalThis \"error\"/\"unhandledrejection\" listener calling preventDefault(), or "
@"configure \"uncaughtErrorPolicy\".");
});
}
std::string cbName = isDiscarded ? "__onDiscardedError" : "__onUncaughtError";
bool success = global->Get(context, tns::ToV8String(isolate, cbName)).ToLocal(&handler);
std::string stackTrace = stackOverride;
if (stackTrace.empty()) {
stackTrace = tns::GetSmartStackTrace(isolate, nullptr, error);
}
if (stackTrace.empty()) {
if (!message.IsEmpty()) {
stackTrace = GetErrorStackTrace(isolate, message->GetStackTrace());
} else {
// Rejections carry no v8::Message; fall back to the reason's own stack.
stackTrace = GetErrorStackTrace(isolate, Exception::GetStackTrace(error));
}
}
// Derive the human-readable message string, either from the v8::Message (sync
// exceptions) or from the reason value itself (rejections, no v8::Message).
auto messageOrReasonString = [&]() -> std::string {
if (!message.IsEmpty()) {
Local<v8::String> messageV8String = message->Get();
return tns::ToString(isolate, messageV8String);
}
return tns::ToString(isolate, error);
};
std::string fullMessage;
if (error->IsObject()) {
auto errObject = error.As<Object>();
auto fullMessageString = tns::ToV8String(isolate, "fullMessage");
if (errObject->HasOwnProperty(context, fullMessageString).ToChecked()) {
// check if we have a "fullMessage" on the error, and log that instead - since it includes
// more info about the exception.
v8::Local<v8::Value> fullMessage_;
if (errObject->Get(context, fullMessageString).ToLocal(&fullMessage_)) {
fullMessage = tns::ToString(isolate, fullMessage_);
} else {
// Fallback to regular message if fullMessage access fails
fullMessage = messageOrReasonString();
}
} else {
fullMessage = messageOrReasonString() + "\n at \n" + stackTrace;
}
} else {
fullMessage = messageOrReasonString() + "\n at \n" + stackTrace;
}
if (success && handler->IsFunction()) {
if (error->IsObject()) {
// Try to set stackTrace property, but don't crash if it fails
bool stackTraceSet = error.As<Object>()
->Set(context, tns::ToV8String(isolate, "stackTrace"),
tns::ToV8String(isolate, stackTrace))
.FromMaybe(false);
if (!stackTraceSet) {
Log(@"Warning: Failed to set stackTrace property on error object");
}
}
Local<v8::Function> errorHandlerFunc = handler.As<v8::Function>();
Local<Object> thiz = Object::New(isolate);
Local<Value> args[] = {error};
Local<Value> result;
TryCatch tc(isolate);
success = errorHandlerFunc->Call(context, thiz, 1, args).ToLocal(&result);
if (tc.HasCaught()) {
tns::LogError(isolate, tc);
}
// Don't crash if error handler call failed - just log it
if (!success) {
Log(@"Warning: Error handler function call failed");
}
}
if (!isDiscarded) {
Log(@"***** Fatal JavaScript exception *****\n");
if (!logPrefix.empty()) {
Log(@"%s", logPrefix.c_str());
}
Log(@"%s", fullMessage.c_str());
if (!stackTrace.empty()) {
Log(@"%s", stackTrace.c_str());
}
} else {
if (!logPrefix.empty()) {
Log(@"%s", logPrefix.c_str());
}
Log(@"NativeScript discarding uncaught JS exception!");
}
// uncaughtErrorPolicy — the cross-platform uncaught-error contract:
// "report" (default): report and keep the app running;
// "throw": after reporting, rethrow the unprevented error
// natively. If a JS→native boundary originated the error
// it is rethrown synchronously there (catchable by a
// native @try/@catch around that call, matching Android);
// otherwise (loop-originated: timers, microtasks,
// rejections) it is thrown from a clean, scope-free frame
// on the runtime loop. Either way it is a throw, not a
// crash guarantee — the app terminates only if nothing
// catches it.
// The deprecated discardUncaughtJsExceptions flag suppresses the throw (an
// explicit "keep the app alive").
if (!isDiscarded) {
id policyValue = Runtime::GetAppConfigValue("uncaughtErrorPolicy");
std::string policy = [policyValue isKindOfClass:[NSString class]]
? std::string([(NSString*)policyValue UTF8String])
: "report";
if (policy == "throw") {
NSString* reasonText = tns::ToNSString(fullMessage);
NSDictionary* userInfo =
stackTrace.empty() ? nil : @{TNSJavaScriptStackTraceKey : tns::ToNSString(stackTrace)};
NSException* fatal = [NSException exceptionWithName:@"NativeScriptFatalJSException"
reason:reasonText
userInfo:userInfo];
// Mirror the stack onto the associated object so the category accessor is
// uniform for crash-SDK hooks.
if (!stackTrace.empty()) {
tns::SetJSStackOnException(fatal, tns::ToNSString(stackTrace));
}
// Claim-slot handoff: deposit the exception and schedule a FALLBACK
// clean-frame throw. A JS→native boundary that originated this error
// claims the slot while still under its V8 scopes and @throws `fatal`
// synchronously after scope teardown, so a native @try/@catch around the
// boundary can catch it (Android parity). Loop-originated errors (timers,
// microtasks, rejections) are never claimed at a boundary, so the fallback
// throws them from a clean, scope-free frame exactly as before.
//
// The fallback claims by pointer IDENTITY (ClaimPendingPolicyThrowIfEqual):
// reporting is serialized under the isolate lock, but if a newer error is
// deposited and then claimed (by its boundary or its own fallback) before
// this block runs, the identity check fails and this now-stale block is a
// no-op — it can never throw a different (newer) error than the one it was
// scheduled for.
DepositPendingPolicyThrow(isolate, fatal);
Runtime* rt = Runtime::GetRuntime(isolate);
auto loop = rt != nullptr ? rt->GetEventLoop() : nullptr;
if (loop != nullptr) {
// bare entry: clean, V8-scope-free frame, outside the loop's
// exception guard
loop->PostInternalBare([isolate, fatal]() {
id e = ClaimPendingPolicyThrowIfEqual(isolate, fatal);
if (e != nil) {
@throw e;
}
});
}
} else if (policy != "report") {
static std::once_flag warnedPolicy;
std::call_once(warnedPolicy, [&policy]() {
Log(@"NativeScript: unknown uncaughtErrorPolicy \"%s\" — falling back to \"report\".",
policy.c_str());
});
}
}
}
void NativeScriptException::OnPromiseRejected(v8::PromiseRejectMessage message) {
Local<Promise> promise = message.GetPromise();
Isolate* isolate = v8::Isolate::GetCurrent();
auto cache = Caches::Get(isolate);
if (cache == nullptr || cache->PromiseRejections == nullptr) {
return;
}
switch (message.GetEvent()) {
case v8::kPromiseRejectWithNoHandler:
cache->PromiseRejections->OnReject(promise, message.GetValue());
break;
case v8::kPromiseHandlerAddedAfterReject:
cache->PromiseRejections->OnHandlerAdded(promise);
break;
case v8::kPromiseResolveAfterResolved:
case v8::kPromiseRejectAfterResolved:
// Not relevant to unhandled-rejection tracking.
break;
}
}
void PromiseRejectionTracker::OnReject(Local<Promise> promise, Local<Value> reason) {
for (auto& entry : pending_) {
if (entry.promise.Get(isolate_)->SameValue(promise)) {
// Already tracked; refresh the reason for the latest rejection value.
entry.reason.Reset(isolate_, reason);
return;
}
}
PendingRejection entry;
entry.promise.Reset(isolate_, promise);
entry.reason.Reset(isolate_, reason);
entry.reported = false;
pending_.push_back(std::move(entry));
SyncPendingCount();
}
void PromiseRejectionTracker::PruneReportedOutstanding() {
reportedOutstanding_.erase(
std::remove_if(reportedOutstanding_.begin(), reportedOutstanding_.end(),
[](const ReportedRejection& r) { return r.promise.IsEmpty(); }),
reportedOutstanding_.end());
}
void PromiseRejectionTracker::OnHandlerAdded(Local<Promise> promise) {
// A handler attached before the rejection was drained cancels the report.
for (auto it = pending_.begin(); it != pending_.end(); ++it) {
if (it->promise.Get(isolate_)->SameValue(promise)) {
pending_.erase(it);
SyncPendingCount();
return;
}
}
// Otherwise, if the rejection was already reported and the promise is still
// outstanding, queue a `rejectionhandled` event. OnHandlerAdded runs during a
// microtask checkpoint, but spec fires rejectionhandled as a task, so we defer
// to the next drain turn instead of dispatching synchronously.
for (auto it = reportedOutstanding_.begin(); it != reportedOutstanding_.end(); ++it) {
if (it->promise.IsEmpty()) {
continue;
}
if (it->promise.Get(isolate_)->SameValue(promise)) {
ReportedRejection queued;
// Re-anchor the promise strongly (the outstanding handle is weak) and
// carry the original reason so the event reports it per spec.
queued.promise.Reset(isolate_, promise);
queued.reason = std::move(it->reason);
reportedOutstanding_.erase(it);
pendingRejectionHandled_.push_back(std::move(queued));
SyncPendingCount();
PruneReportedOutstanding();
return;
}
}
PruneReportedOutstanding();
}
// Gives a worker's global `onerror` a chance to handle a rejected reason,
// mirroring WorkerWrapper::CallOnErrorHandlers. Returns true when the handler
// signalled it consumed the error (truthy return).
static bool GiveWorkerOnErrorAChance(Isolate* isolate, Local<Context> context,
Local<Value> reason) {
Local<Object> global = context->Global();
Local<Value> onErrorVal;
if (!global->Get(context, tns::ToV8String(isolate, "onerror")).ToLocal(&onErrorVal)) {
return false;
}
if (onErrorVal.IsEmpty() || !onErrorVal->IsFunction()) {
return false;
}
Local<v8::Function> onErrorFunc = onErrorVal.As<v8::Function>();
Local<Value> args[1] = {reason};
Local<Value> result;
TryCatch tc(isolate);
bool success = onErrorFunc->Call(context, v8::Undefined(isolate), 1, args).ToLocal(&result);
return success && !result.IsEmpty() && result->BooleanValue(isolate);
}
void PromiseRejectionTracker::Drain(Local<Context> context) {
if (draining_) {
return;
}
draining_ = true;
// Fire queued rejectionhandled events first (they were deferred from a
// microtask checkpoint to run as a task on this drain turn), carrying the
// retained original rejection reason.
std::vector<ReportedRejection> handledSnapshot;
handledSnapshot.swap(pendingRejectionHandled_);
std::vector<PendingRejection> snapshot;
snapshot.swap(pending_);
SyncPendingCount();
auto cache = Caches::Get(isolate_);
bool isWorker = cache->isWorker;
for (auto& queued : handledSnapshot) {
if (queued.promise.IsEmpty()) {
continue;
}
@try {
Local<Promise> promise = queued.promise.Get(isolate_);
Local<Value> reason = queued.reason.IsEmpty() ? v8::Undefined(isolate_).As<Value>()
: queued.reason.Get(isolate_);
ErrorEvents::DispatchRejectionHandled(isolate_, promise, reason);
} @catch (NSException* exception) {
Log(@"PromiseRejectionTracker: exception while firing rejectionhandled: %@", exception);
}
}
for (auto& entry : snapshot) {
if (entry.reported) {
continue;
}
entry.reported = true;
// The observer calling us holds live V8 scopes, so an NSException from the
// reporting path must not unwind past this frame — catch and log instead.
@try {
Local<Promise> promise = entry.promise.Get(isolate_);
Local<Value> reason = entry.reason.Get(isolate_);
std::string stack = tns::GetSmartStackTrace(isolate_, nullptr, reason);
if (stack.empty()) {
stack =
NativeScriptException::GetErrorStackTrace(isolate_, Exception::GetStackTrace(reason));
}
// Android parity (Fix A): populate `reason.stackTrace` BEFORE dispatching
// the unhandledrejection event so listeners can read `e.reason.stackTrace`
// (object reasons only; guarded / non-fatal). Covers both the worker and
// main dispatch branches below.
if (reason->IsObject() && !stack.empty()) {
bool ok = reason.As<Object>()
->Set(context, tns::ToV8String(isolate_, "stackTrace"),
tns::ToV8String(isolate_, stack))
.FromMaybe(false);
if (!ok) {
Log(@"Warning: Failed to set stackTrace property on rejection reason");
}
}
if (isWorker) {
// An escapeException-branded reason converts straight to the native
// throw (never dispatched, never vetoable) — same rule as the main
// isolate's ReportUnhandledRejection.
if (ScheduleEscapedExceptionIfBranded(isolate_, reason)) {
continue;
}
// Dispatch the rejection event on the worker's own global first;
// preventDefault() there fully handles it. Only when unprevented fall
// through to the existing worker channel (worker-global onerror →
// forward to the main isolate's worker.onerror).
if (!ErrorEvents::DispatchUnhandledRejection(isolate_, promise, reason)) {
if (!GiveWorkerOnErrorAChance(isolate_, context, reason)) {
Runtime* runtime = Runtime::GetRuntime(isolate_);
if (runtime != nullptr) {
int workerId = runtime->WorkerId();
bool found = false;
auto state = Caches::Workers->Get(workerId, found);
if (found && state != nullptr) {
auto* worker = static_cast<WorkerWrapper*>(state->UserData());
if (worker != nullptr) {
std::string reasonMessage = tns::ToString(isolate_, reason);
worker->PassUncaughtRejectionToMain(reasonMessage, "Worker script", stack, 1);
}
}
}
}
}
} else {
NativeScriptException::ReportUnhandledRejection(isolate_, promise, reason, stack);
}
// The rejection has now been reported (unhandledrejection fired, prevented
// or not). Keep the promise as a phantom-weak outstanding entry so a
// handler attached later fires rejectionhandled; a GC'd promise drops out
// on its own.
ReportedRejection outstanding;
outstanding.promise = std::move(entry.promise);
outstanding.reason = std::move(entry.reason);
reportedOutstanding_.push_back(std::move(outstanding));
reportedOutstanding_.back().promise.SetWeak();
} @catch (NSException* exception) {
Log(@"PromiseRejectionTracker: exception while reporting rejection: %@", exception);
}
}
PruneReportedOutstanding();
draining_ = false;
}
void NativeScriptException::ReThrowToV8(Isolate* isolate) {
@try {
// The Isolate::Scope here is necessary because the Exception::Error method internally relies on
// the Isolate::GetCurrent method which might return null if we do not use the proper scope
Isolate::Scope scope(isolate);
Local<Context> context = isolate->GetCurrentContext();
Local<Value> errObj;
if (this->javascriptException_ != nullptr) {
errObj = this->javascriptException_->Get(isolate);
if (errObj->IsObject()) {
if (!this->fullMessage_.empty()) {
bool success = errObj.As<Object>()
->Set(context, tns::ToV8String(isolate, "fullMessage"),
tns::ToV8String(isolate, this->fullMessage_))
.FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set fullMessage property on error object");
}
} else if (!this->message_.empty()) {
bool success = errObj.As<Object>()
->Set(context, tns::ToV8String(isolate, "fullMessage"),
tns::ToV8String(isolate, this->message_))
.FromMaybe(false);
if (!success) {
Log(@"Warning: Failed to set fullMessage property on error object");
}
}
}
} else if (!this->fullMessage_.empty()) {
errObj = Exception::Error(tns::ToV8String(isolate, this->fullMessage_));
} else if (!this->message_.empty()) {
errObj = Exception::Error(tns::ToV8String(isolate, this->message_));
} else {
errObj = Exception::Error(
tns::ToV8String(isolate, "No javascript exception or message provided."));
}
isolate->ThrowException(errObj);
} @catch (NSException* exception) {
Log(@"ReThrowToV8: Caught exception during error handling: %@", exception);
@throw exception;
}
}
std::string NativeScriptException::GetErrorMessage(Isolate* isolate, Local<Value>& error,
const std::string& prependMessage) {
std::shared_ptr<Caches> cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
// get whole error message from previous stack
std::stringstream ss;
if (prependMessage != "") {
ss << prependMessage << std::endl;
}
std::string errMessage;
bool hasFullErrorMessage = false;
auto v8FullMessage = tns::ToV8String(isolate, "fullMessage");
if (error->IsObject() && error.As<Object>()->Has(context, v8FullMessage).ToChecked()) {
hasFullErrorMessage = true;
Local<Value> errMsgVal;
bool success = error.As<Object>()->Get(context, v8FullMessage).ToLocal(&errMsgVal);
if (success && !errMsgVal.IsEmpty()) {
errMessage = tns::ToString(isolate, errMsgVal.As<v8::String>());
} else {
errMessage = "";
if (!success) {
Log(@"Warning: Failed to get fullMessage property from error object");
}
}
ss << errMessage;
}
MaybeLocal<v8::String> str = error->ToDetailString(context);
if (!str.IsEmpty()) {
v8::String::Utf8Value utfError(isolate, str.FromMaybe(Local<v8::String>()));
if (hasFullErrorMessage) {
ss << std::endl;
}
ss << *utfError;
}
return ss.str();
}
std::string NativeScriptException::GetErrorStackTrace(Isolate* isolate,
const Local<StackTrace>& stackTrace) {
if (stackTrace.IsEmpty()) {
return "";
}
std::stringstream ss;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
int frameCount = stackTrace->GetFrameCount();
for (int i = 0; i < frameCount; i++) {
Local<StackFrame> frame = stackTrace->GetFrame(isolate, i);
std::string funcName = tns::ToString(isolate, frame->GetFunctionName());
std::string srcName = tns::ToString(isolate, frame->GetScriptName());
int lineNumber = frame->GetLineNumber();
int column = frame->GetColumn();
ss << "\t" << (i > 0 ? "at " : "") << funcName.c_str() << "(" << srcName.c_str() << ":"
<< lineNumber << ":" << column << ")" << std::endl;
}
return ss.str();
}
std::string NativeScriptException::GetFullMessage(Isolate* isolate, const TryCatch& tc,
const std::string& jsExceptionMessage) {
std::string loggedMessage = GetFullMessage(isolate, tc.Message(), jsExceptionMessage);
if (!tc.CanContinue()) {
std::stringstream errM;
errM << std::endl
<< "An uncaught error has occurred and V8's TryCatch block CAN'T be continued. ";
loggedMessage = errM.str() + loggedMessage;
}
return loggedMessage;
}
std::string NativeScriptException::GetFullMessage(Isolate* isolate, Local<v8::Message> message,
const std::string& jsExceptionMessage) {
Local<Context> context = isolate->GetEnteredOrMicrotaskContext();
std::stringstream ss;
ss << jsExceptionMessage;
// get script name
Local<Value> scriptResName = message->GetScriptResourceName();
// get stack trace
std::string stackTraceMessage = GetErrorStackTrace(isolate, message->GetStackTrace());
if (!scriptResName.IsEmpty() && scriptResName->IsString()) {
ss << std::endl << "File: (" << tns::ToString(isolate, scriptResName.As<v8::String>());
} else {
ss << std::endl << "File: (<unknown>";
}
ss << ":" << message->GetLineNumber(context).ToChecked() << ":" << message->GetStartColumn()
<< ")" << std::endl
<< std::endl;
ss << "StackTrace: " << std::endl << stackTraceMessage << std::endl;
std::string loggedMessage = ss.str();
// TODO: Log the error
// tns::LogError(isolate, tc);
return loggedMessage;
}
void NativeScriptException::ShowErrorModal(Isolate* isolate, const std::string& title,
const std::string& message,
const std::string& stackTrace) {
if (!RuntimeConfig.IsDebug) {
return;
}
if (!Runtime::showErrorDisplay()) {
return;
}
uint64_t ticketToSchedule = 0;
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
// If the console already presented this error (console-first scenario), just enrich the
// context.
if (gPendingErrorDisplay.ticket != 0 && !gPendingErrorDisplay.contextCaptured &&
gPendingErrorDisplay.modalPresented) {
gPendingErrorDisplay.contextCaptured = true;
gPendingErrorDisplay.isolate = isolate;
gPendingErrorDisplay.title = title;
gPendingErrorDisplay.message = message;
gPendingErrorDisplay.rawStack = stackTrace;
ConsiderStackCandidate(gPendingErrorDisplay, isolate, stackTrace);
return;
}
gPendingErrorDisplay.ticket = gNextErrorTicket++;
gPendingErrorDisplay.contextCaptured = true;
gPendingErrorDisplay.modalPresented = false;
gPendingErrorDisplay.fallbackScheduled = true;
gPendingErrorDisplay.isolate = isolate;
gPendingErrorDisplay.title = title;
gPendingErrorDisplay.message = message;
gPendingErrorDisplay.rawStack = stackTrace;
gPendingErrorDisplay.consolePayload.clear();
gPendingErrorDisplay.canonicalStack.clear();
ConsiderStackCandidate(gPendingErrorDisplay, isolate, stackTrace);
ticketToSchedule = gPendingErrorDisplay.ticket;
}
if (ticketToSchedule != 0) {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
ScheduleFallbackPresentation(ticketToSchedule);
});
}
}
void NativeScriptException::SubmitConsoleErrorPayload(Isolate* isolate,
const std::string& payload) {
if (!RuntimeConfig.IsDebug) {
return;
}
if (!Runtime::showErrorDisplay()) {
return;
}
PendingErrorDisplay stateSnapshot;
bool presentNow = false;
bool updateExisting = false;
auto promoteConsolePayload = [&](const std::string& text, v8::Isolate* payloadIsolate) {
gPendingErrorDisplay.consolePayload = text;
if (payloadIsolate != nullptr) {
gPendingErrorDisplay.isolate = payloadIsolate;
}
gPendingErrorDisplay.canonicalStack = text;
};
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
auto buildDefaultContext = [&](void) {
gPendingErrorDisplay.title = "JavaScript Error";
std::string firstLine = payload;
size_t newlinePos = payload.find('\n');
if (newlinePos != std::string::npos) {
firstLine = payload.substr(0, newlinePos);
}
gPendingErrorDisplay.message = firstLine;
gPendingErrorDisplay.rawStack = payload;
promoteConsolePayload(payload, isolate);
};
if (gPendingErrorDisplay.ticket == 0) {
gPendingErrorDisplay.ticket = gNextErrorTicket++;
gPendingErrorDisplay.canonicalStack.clear();
}
if (!gPendingErrorDisplay.contextCaptured && !gPendingErrorDisplay.modalPresented) {
// Console-first scenario for a brand new error
gPendingErrorDisplay.modalPresented = true;
gPendingErrorDisplay.isolate = isolate;
buildDefaultContext();
stateSnapshot = gPendingErrorDisplay;
presentNow = true;
} else if (!gPendingErrorDisplay.modalPresented) {
// Context captured (or pending) but UI not yet shown – prefer the console payload
if (!gPendingErrorDisplay.contextCaptured) {
buildDefaultContext();
}
if (isolate != nullptr) {
gPendingErrorDisplay.isolate = isolate;
}
promoteConsolePayload(payload, isolate);
gPendingErrorDisplay.modalPresented = true;
stateSnapshot = gPendingErrorDisplay;
presentNow = true;
} else {
// Modal already visible (fallback or previous payload) – just update the text content
promoteConsolePayload(payload, isolate);
updateExisting = true;
}
}
if (presentNow) {
std::string displayStack =
stateSnapshot.canonicalStack.empty()
? (stateSnapshot.consolePayload.empty() ? ResolveDisplayStack(stateSnapshot)
: stateSnapshot.consolePayload)
: stateSnapshot.canonicalStack;
RenderErrorModalUI(stateSnapshot.isolate, stateSnapshot.title, stateSnapshot.message,
displayStack);
} else if (updateExisting) {
std::string displayStack = gPendingErrorDisplay.canonicalStack.empty()
? (gPendingErrorDisplay.consolePayload.empty()
? ResolveDisplayStack(gPendingErrorDisplay)
: gPendingErrorDisplay.consolePayload)
: gPendingErrorDisplay.canonicalStack;
UpdateDisplayedStackText(displayStack);
}
}
static void ScheduleFallbackPresentation(uint64_t ticket) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)),
dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
PresentFallbackIfNeeded(ticket);
});
}
static void PresentFallbackIfNeeded(uint64_t ticket) {
PendingErrorDisplay snapshot;
bool shouldPresent = false;
{
std::lock_guard<std::mutex> lock(gErrorDisplayMutex);
if (gPendingErrorDisplay.ticket == ticket && !gPendingErrorDisplay.modalPresented) {
gPendingErrorDisplay.modalPresented = true;
snapshot = gPendingErrorDisplay;
shouldPresent = true;
}
}
if (!shouldPresent) {
return;
}
std::string finalStack = ResolveDisplayStack(snapshot);
RenderErrorModalUI(snapshot.isolate, snapshot.title, snapshot.message, finalStack);
}