Repository navigation
Expand file tree
/
Copy pathRuntime.mm
More file actions
802 lines (704 loc) · 31.4 KB
/
Copy pathRuntime.mm
File metadata and controls
802 lines (704 loc) · 31.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
#include "Runtime.h"
#include <chrono>
#include <string>
#include "ArgConverter.h"
#include "BuiltinLoader.h"
#include "Caches.h"
#include "Console.h"
#include "Constants.h"
#include "ErrorEvents.h"
#include "Events.h"
#include "Helpers.h"
#include "InlineFunctions.h"
#include "Interop.h"
#include "IsolateTracked.h"
#include "LazyGlobals.h"
#include "NativeScriptException.h"
#include "NativeScriptPlatform.h"
#include "ObjectManager.h"
#include "Performance.h"
#include "PromiseProxy.h"
#include "RuntimeConfig.h"
#include "SimpleAllocator.h"
#include "SpinLock.h"
#include "StructuredClone.h"
#include "TSHelpers.h"
#include "WeakRef.h"
#include "Worker.h"
#include "IsolateWrapper.h"
#include <mutex>
#include <unordered_map>
#include <vector>
#include "HttpLoader.h"
#include "ModuleBinding.hpp"
#include "ModuleInternalCallbacks.h"
#include "napi/NapiEnv.h"
#include "URLImpl.h"
#include "URLPatternImpl.h"
#include "URLSearchParamsImpl.h"
#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
using namespace v8;
using namespace std;
// Import meta callback to support import.meta.url
//
// `g_moduleRegistry` keys are normalized by `CanonicalizeRegistryKey`
// (in ModuleInternalCallbacks.mm) to one of:
//
// 1. HTTP / HTTPS URL — `http://host:port/path` or `https://...`.
// The URL IS the module identity;
// `import.meta.url` should be the URL verbatim.
//
// 2. Custom scheme — `node:fs`, `blob:...`.
// Synthetic / built-in modules that aren't backed by the local
// filesystem. Their identity is the scheme + body itself;
// `import.meta.url` keeps that string unchanged.
//
// 3. Absolute filesystem path — `/Users/.../app/src/foo.js`. The
// production / non-HMR dev shape. Strip the runtime base dir to
// recover the canonical "/app/<rel>" shape JS consumers see, then
// prepend `file://` so the result is a well-formed URL.
//
static void InitializeImportMetaObject(Local<Context> context, Local<Module> module,
Local<Object> meta) {
Isolate* isolate = v8::Isolate::GetCurrent();
std::string modulePath = tns::LookupModuleKeyForModule(isolate, module);
auto hasUrlScheme = [](const std::string& s) -> bool {
if (s.empty()) return false;
size_t colonPos = s.find(':');
if (colonPos == 0 || colonPos == std::string::npos) return false;
size_t slashPos = s.find('/');
if (slashPos != std::string::npos && slashPos < colonPos) return false;
for (size_t i = 0; i < colonPos; i++) {
char c = s[i];
const bool ok = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') ||
c == '+' || c == '-' || c == '.';
if (!ok) return false;
}
return true;
};
// Compute import.meta.url.
std::string moduleUrl;
if (modulePath.empty()) {
moduleUrl = "file:///app/";
} else if (hasUrlScheme(modulePath)) {
moduleUrl = modulePath;
} else {
std::string base = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, "");
moduleUrl = "file://" + base;
}
Local<String> url =
String::NewFromUtf8(isolate, moduleUrl.c_str(), NewStringType::kNormal).ToLocalChecked();
// Set import.meta.url property
meta->CreateDataProperty(
context, String::NewFromUtf8(isolate, "url", NewStringType::kNormal).ToLocalChecked(),
url)
.Check();
// Compute import.meta.dirname.
//
// Spec (Node.js): `import.meta.dirname` is the OS-path of the
// directory containing the module — equivalent to `path.dirname(
// fileURLToPath(import.meta.url))`. It only makes sense for modules
// backed by the local filesystem.
//
// For URL-backed modules (HTTP, blob, etc.) there is no
// filesystem directory. We return the URL with the final segment
// stripped — a best-effort answer that's stable across cycles and
// useful for log lines / source maps. Consumers that genuinely need
// a filesystem path should already be guarding on `meta.url`'s
// scheme before using `meta.dirname`.
std::string dirname;
if (modulePath.empty()) {
dirname = "/app";
} else if (hasUrlScheme(modulePath)) {
size_t schemeEnd = modulePath.find("://");
size_t pathStart =
(schemeEnd == std::string::npos) ? std::string::npos : modulePath.find('/', schemeEnd + 3);
size_t lastSlash = modulePath.find_last_of('/');
if (pathStart != std::string::npos && lastSlash != std::string::npos && lastSlash > pathStart) {
dirname = modulePath.substr(0, lastSlash);
} else {
// No path beyond the host (`http://host`) or scheme without `//`
// (`node:fs`, `blob:abc`). Keep the identity intact.
dirname = modulePath;
}
} else {
// Derived from the same base-stripped path `import.meta.url` reports, so
// the documented equivalence holds: dirname is
// `path.dirname(fileURLToPath(import.meta.url))`. Taking it from the raw
// path instead reported a container-absolute directory for a module whose
// url said `file:///app/…`.
const std::string appRelative = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, "");
size_t lastSlash = appRelative.find_last_of("/\\");
if (lastSlash != std::string::npos && lastSlash > 0) {
dirname = appRelative.substr(0, lastSlash);
} else {
dirname = "/app"; // fallback
}
}
Local<String> dirnameStr =
String::NewFromUtf8(isolate, dirname.c_str(), NewStringType::kNormal).ToLocalChecked();
// Set import.meta.dirname property
meta->CreateDataProperty(
context, String::NewFromUtf8(isolate, "dirname", NewStringType::kNormal).ToLocalChecked(),
dirnameStr)
.Check();
}
namespace tns {
std::atomic<int> Runtime::nextIsolateId{0};
SimpleAllocator allocator_;
NSDictionary* AppPackageJson = nil;
static std::unordered_map<std::string, id> AppConfigCache; // generic cache for app config values
static std::mutex AppConfigCacheMutex;
// Global flag to track if error display is currently showing
bool isErrorDisplayShowing = false;
// TODO: consider listening to timezone changes and automatically reseting the DateTime. Probably
// makes more sense to move it to its own file
// void UpdateTimezoneNotificationCallback(CFNotificationCenterRef center,
// void *observer,
// CFStringRef name,
// const void *object,
// CFDictionaryRef userInfo) {
// Runtime* r = (Runtime*)observer;
// auto isolate = r->GetIsolate();
//
// CFRunLoopPerformBlock(r->RuntimeLoop(), kCFRunLoopDefaultMode, ^() {
// TODO: lock isolate here?
// isolate->DateTimeConfigurationChangeNotification(Isolate::TimeZoneDetection::kRedetect);
// });
//}
// add this to register (most likely on setting up isolate
// CFNotificationCenterAddObserver(CFNotificationCenterGetLocalCenter(), this,
// &UpdateTimezoneNotificationCallback, kCFTimeZoneSystemTimeZoneDidChangeNotification, nullptr,
// CFNotificationSuspensionBehaviorDeliverImmediately);
// add this to remove the observer
// CFNotificationCenterRemoveObserver(CFNotificationCenterGetLocalCenter(), this,
// kCFTimeZoneSystemTimeZoneDidChangeNotification, NULL);
void DisposeIsolateWhenPossible(Isolate* isolate) {
// Disposal is deferred only while the isolate is still entered, which happens
// when the runtime is deleted by code running inside its own isolate: an
// embedder calling shutdownRuntime from a JS callback. exit() never deletes a
// runtime, so a process that is dying leaves its isolates to the OS.
if (isolate->IsInUse()) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_MSEC)),
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
DisposeIsolateWhenPossible(isolate);
});
} else {
isolate->Dispose();
}
}
void Runtime::Initialize() {
// Before anything worth tracing runs, so NS_DEBUG covers boot itself.
tns::InitializeLogCategoriesFromEnvironment();
MetaFile::setInstance(RuntimeConfig.MetadataPtr);
}
Runtime::Runtime() {
currentRuntime_ = this;
workerId_ = -1;
workerCache_ = Caches::Workers;
}
Runtime::~Runtime() {
// Tear the rejection observer down before any isolate teardown: it references
// the isolate and reads Caches, both of which are invalidated below.
if (rejectionObserver_ != nullptr) {
CFRunLoopObserverInvalidate(rejectionObserver_);
CFRelease(rejectionObserver_);
rejectionObserver_ = nullptr;
}
// Drop any pending uncaughtErrorPolicy "throw" deposit for this isolate so a
// stale entry can't outlive the isolate it keys on.
NativeScriptException::OnIsolateTeardown(isolate_);
auto currentIsolate = this->isolate_;
{
// make sure we remove the isolate from the list of active isolates first
// this will make sure isAlive(isolate) will return false and prevent locking of the v8 isolate
// after it terminates execution
SpinLock lock(isolatesMutex_);
Runtime::isolates_.erase(
std::remove(Runtime::isolates_.begin(), Runtime::isolates_.end(), this->isolate_),
Runtime::isolates_.end());
Caches::Get(isolate_)->InvalidateIsolate();
}
this->isolate_->TerminateExecution();
// TODO: fix race condition on workers where a queue can leak (maybe calling Terminate before
// Initialize?)
Caches::Workers->ForEach([currentIsolate](int& key, std::shared_ptr<Caches::WorkerState>& value) {
auto childWorkerWrapper = static_cast<WorkerWrapper*>(value->UserData());
if (childWorkerWrapper->GetMainIsolate() == currentIsolate) {
childWorkerWrapper->Terminate();
}
return false;
});
{
v8::Locker lock(isolate_);
// Flag this isolate's in-flight async graph loads dead and Reset their
// context Globals — while the isolate is still alive, under the Locker
// above — so fetch completions still queued on background NSURLSession
// queues become no-ops. This MUST precede the event-loop Shutdown: a
// post the loop drops is destroyed on the POSTING (background) thread,
// and quiescing first guarantees such a task holds only already-Reset
// Globals by then. The rest of the loader state (registry / waiters)
// lives in a Caches state slot and is destroyed with the isolate's
// Caches below. Worker isolates quiesce the same way.
tns::QuiesceModuleLoadsForIsolate(isolate_);
// Stop the event loop before any handle disposal: queued entries touch
// caches and persistents that go away below, and posts from other threads
// must start dropping now.
if (eventLoop_ != nullptr) {
eventLoop_->Shutdown();
}
// Before DisposeAllRegistered: the env's reference lists hold v8::Globals,
// so its teardown needs the isolate alive and locked.
NapiEnv::Destroy(static_cast<NapiEnv*>(this->napiEnv_));
this->napiEnv_ = nullptr;
ObjectManager::DisposeAllRegistered(isolate_);
IsolateTracked::SweepAll(isolate_);
if (IsRuntimeWorker()) {
std::shared_ptr<Caches::WorkerState> workerState = Caches::Workers->Get(this->workerId_);
WorkerWrapper* currentWorker =
workerState == nullptr ? nullptr : static_cast<WorkerWrapper*>(workerState->UserData());
Caches::Workers->Remove(this->workerId_);
// if the parent isolate is dead then deleting the wrapper is our responsibility
if (currentWorker != nullptr && currentWorker->IsWeak()) {
delete currentWorker;
}
}
Caches::Remove(this->isolate_);
this->isolate_->SetData(Constants::RUNTIME_SLOT, nullptr);
}
DisposeIsolateWhenPossible(this->isolate_);
// Matched erase: only removes the registry entry while it still maps to
// this runtime's loop, so a worker isolate that reuses this pointer after
// the (possibly deferred) Dispose can't be evicted by us.
if (eventLoop_ != nullptr) {
NativeScriptPlatform::Instance()->IsolateDisposed(currentIsolate, eventLoop_);
}
currentRuntime_ = nullptr;
}
Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
return static_cast<Runtime*>(isolate->GetData(Constants::RUNTIME_SLOT));
}
Isolate* Runtime::CreateIsolate(const IsolateLimits& limits) {
if (!v8Initialized_) {
// Runtime::platform_ = RuntimeConfig.IsDebug
// ? v8_inspector::V8InspectorPlatform::CreateDefaultPlatform()
// : platform::NewDefaultPlatform();
// Flags must be set before V8::Initialize(), which freezes them; changing a
// flag afterwards aborts the process. Don't pass --jitless either:
// v8_enable_lite_mode already implies it and makes the flag read-only,
// which is likewise fatal to set.
std::string flags = RuntimeConfig.IsDebug ? "--expose_gc" : "--expose_gc --no-lazy";
V8::SetFlagsFromString(flags.c_str(), flags.size());
// wrap the default platform so foreground tasks ride each runtime
// thread's CFRunLoop instead of sitting in never-pumped libplatform queues
Runtime::platform_ = new NativeScriptPlatform(platform::NewDefaultPlatform());
V8::InitializePlatform(Runtime::platform_);
V8::Initialize();
v8Initialized_ = true;
}
timeOriginMonotonic_ = platform_->MonotonicallyIncreasingTime();
timeOriginRealtimeMs_ = platform_->CurrentClockTimeMillis();
// auto version = v8::V8::GetVersion();
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &allocator_;
if (limits.maxOldGenerationSizeBytes.has_value()) {
create_params.constraints.set_max_old_generation_size_in_bytes(
*limits.maxOldGenerationSizeBytes);
}
if (limits.maxYoungGenerationSizeBytes.has_value()) {
create_params.constraints.set_max_young_generation_size_in_bytes(
*limits.maxYoungGenerationSizeBytes);
}
#ifdef V8_HAS_JS_DISPATCH_TABLE_RESERVATION_PARAM
if (limits.jsDispatchTableReservationBytes.has_value()) {
create_params.js_dispatch_table_reservation_size = *limits.jsDispatchTableReservationBytes;
}
#endif
Isolate* isolate = Isolate::New(create_params);
runtimeLoop_ = CFRunLoopGetCurrent();
// v8 already asked for this isolate's task runner during Isolate::New, so
// the registry may hold an unbound loop - or a stopped one, when a worker
// isolate reuses a disposed isolate's address. Refresh, then attach to this
// thread; foreground tasks buffered so far start flowing from here on.
// (In the reused-address case, tasks v8 posted DURING Isolate::New landed
// in the stale stopped loop and were dropped - refreshing any earlier is
// impossible (the address isn't known) and refreshing on runner lookup
// would defeat the matched-erase teardown protection.)
eventLoop_ = NativeScriptPlatform::Instance()->RefreshEventLoop(isolate);
eventLoop_->BindToCurrentThread();
isolate->SetData(Constants::RUNTIME_SLOT, this);
{
SpinLock lock(isolatesMutex_);
Runtime::isolates_.emplace_back(isolate);
}
return isolate;
}
void Runtime::Init(Isolate* isolate, bool isWorker) {
std::shared_ptr<Caches> cache =
Caches::Init(isolate, nextIsolateId.fetch_add(1, std::memory_order_relaxed));
cache->isWorker = isWorker;
cache->ObjectCtorInitializer = MetadataBuilder::GetOrCreateConstructorFunctionTemplate;
cache->StructCtorInitializer = MetadataBuilder::GetOrCreateStructCtorFunction;
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<FunctionTemplate> globalTemplateFunction = FunctionTemplate::New(isolate);
globalTemplateFunction->SetClassName(tns::ToV8String(isolate, "NativeScriptGlobalObject"));
tns::binding::CreateInternalBindingTemplates(isolate, globalTemplateFunction);
Local<ObjectTemplate> globalTemplate = ObjectTemplate::New(isolate, globalTemplateFunction);
DefineNativeScriptVersion(isolate, globalTemplate);
// Worker::Init(isolate, globalTemplate, isWorker);
DefineTimeMethod(isolate, globalTemplate);
DefineDrainMicrotaskMethod(isolate, globalTemplate);
DefineQueueMacrotaskMethod(isolate, globalTemplate);
// queueMicrotask(callback) per spec
{
Local<FunctionTemplate> qmtTemplate =
FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value>& info) {
auto* isolate = info.GetIsolate();
if (info.Length() < 1 || !info[0]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(
tns::ToV8String(isolate, "queueMicrotask: callback must be a function")));
return;
}
v8::Local<v8::Function> cb = info[0].As<v8::Function>();
isolate->EnqueueMicrotask(cb);
});
globalTemplate->Set(tns::ToV8String(isolate, "queueMicrotask"), qmtTemplate);
}
ObjectManager::Init(isolate, globalTemplate);
LazyGlobals::Init(isolate, globalTemplate);
MetadataBuilder::RegisterConstantsOnGlobalObject(isolate, globalTemplate, isWorker);
isolate->SetCaptureStackTraceForUncaughtExceptions(true, 100, StackTrace::kOverview);
// Enable dynamic import() support (handle API rename across V8 versions)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
isolate->SetHostImportModuleDynamicallyCallback(tns::ImportModuleDynamicallyCallback);
#pragma clang diagnostic pop
// Set up import.meta callback
isolate->SetHostInitializeImportMetaObjectCallback(InitializeImportMetaObject);
isolate->AddMessageListener(NativeScriptException::OnUncaughtError);
isolate->SetPromiseRejectCallback(NativeScriptException::OnPromiseRejected);
Local<Context> context = Context::New(isolate, nullptr, globalTemplate);
context->Enter();
// Drain tracked unhandled promise rejections once per runloop turn, just
// before the loop sleeps. The info pointer is the isolate; the callback
// re-validates liveness because the isolate may be torn down between turns.
CFRunLoopObserverContext observerContext = {0, isolate, nullptr, nullptr, nullptr};
rejectionObserver_ =
CFRunLoopObserverCreate(kCFAllocatorDefault, kCFRunLoopBeforeWaiting, /*repeats*/ true,
/*order*/ 0, Runtime::DrainRejectionsObserver, &observerContext);
CFRunLoopAddObserver(runtimeLoop_, rejectionObserver_, kCFRunLoopCommonModes);
DefineGlobalObject(context, isWorker);
DefineCollectFunction(context);
PromiseProxy::Init(context);
Events::Init(context);
ErrorEvents::Init(context);
StructuredClone::Init(context);
Performance::Init(context);
Console::Init(context);
WeakRef::Init(context);
// The dev primitives (configureLoader, invalidateModules, …) live in the
// `ns:module` builtin module, materialized lazily per realm on first
// resolution (see `BuildNsModuleBinding` in ModuleInternalCallbacks.mm for
// the member list) — nothing to install here.
// URL blob support (internal/blob-url.js); failures are tolerated —
// compile-and-run-if-possible.
v8::Local<v8::Value> blobMethodsResult;
bool blobMethodsOk =
BuiltinLoader::RunBuiltin(context, BuiltinId::kBlobUrl).ToLocal(&blobMethodsResult);
(void)blobMethodsOk;
this->moduleInternal_ = std::make_unique<ModuleInternal>(context);
ArgConverter::Init(context, MetadataBuilder::StructPropertyGetterCallback,
MetadataBuilder::StructPropertySetterCallback);
Interop::RegisterInteropTypes(context);
ClassBuilder::RegisterBaseTypeScriptExtendsFunction(
context); // Register the __extends function to the global object
ClassBuilder::RegisterNativeTypeScriptExtendsFunction(
context); // Override the __extends function for native objects
TSHelpers::Init(context);
InlineFunctions::Init(context);
cache->SetContext(context);
this->napiEnv_ = NapiEnv::Create(context);
this->isolate_ = isolate;
}
void Runtime::RunMainScript() {
Isolate* isolate = this->GetIsolate();
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
try {
this->moduleInternal_->RunModule(isolate, "./");
} catch (NativeScriptException& ex) {
// A failed entry module is fatal in every build — an app whose main
// module did not run has no defined state to continue in. Log the cause
// before unwinding so it survives even if the terminate handler doesn't
// print exception details.
Log(@"Fatal: the main module failed to run: %s", ex.getMessage().c_str());
throw;
}
}
void Runtime::RunModule(const std::string moduleName) {
Isolate* isolate = this->GetIsolate();
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
this->moduleInternal_->RunModule(isolate, moduleName);
}
EntryEvaluationState Runtime::PollMainEntryEvaluation(std::string* rejectionReason) {
Isolate* isolate = this->GetIsolate();
if (isolate == nullptr || this->moduleInternal_ == nullptr) {
return EntryEvaluationState::kNone;
}
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = Caches::Get(isolate)->GetContext();
if (context.IsEmpty()) {
return EntryEvaluationState::kNone;
}
Context::Scope context_scope(context);
// RunMainScript launches "./"; the promise lives under the resolved path.
const std::string entryPath = ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath);
return ModuleInternal::PollEntryEvaluation(isolate, entryPath, rejectionReason);
}
void Runtime::EvictMainEntry() {
Isolate* isolate = this->GetIsolate();
if (isolate == nullptr || this->moduleInternal_ == nullptr) {
return;
}
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = Caches::Get(isolate)->GetContext();
if (context.IsEmpty()) {
return;
}
Context::Scope context_scope(context);
RemoveModuleFromRegistry(isolate, ResolveMainEntryFromPackageJson(RuntimeConfig.ApplicationPath));
}
bool Runtime::IsExecutionTerminating() {
Isolate* isolate = this->GetIsolate();
if (isolate == nullptr) {
return false;
}
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
return isolate->IsExecutionTerminating();
}
void Runtime::RunScript(const std::string script) {
Isolate* isolate = this->GetIsolate();
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
this->moduleInternal_->RunScript(isolate, script);
}
Isolate* Runtime::GetIsolate() { return this->isolate_; }
const int Runtime::WorkerId() { return this->workerId_; }
void Runtime::SetWorkerId(int workerId) { this->workerId_ = workerId; }
id Runtime::GetAppConfigValue(std::string key) {
if (AppPackageJson == nil) {
NSString* packageJsonPath =
[[NSString stringWithUTF8String:RuntimeConfig.ApplicationPath.c_str()]
stringByAppendingPathComponent:@"package.json"];
NSData* data = [NSData dataWithContentsOfFile:packageJsonPath];
if (data) {
NSError* error = nil;
NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
AppPackageJson = [[NSDictionary alloc] initWithDictionary:dict];
}
}
// Generic cache for all keys to avoid repeated NSString conversion and NSDictionary hashing
{
std::lock_guard<std::mutex> lock(AppConfigCacheMutex);
auto it = AppConfigCache.find(key);
if (it != AppConfigCache.end()) {
return it->second;
}
}
id result = nil;
if (AppPackageJson != nil) {
NSString* nsKey = [NSString stringWithUTF8String:key.c_str()];
result = AppPackageJson[nsKey];
}
// Store in cache (can cache nil as NSNull to differentiate presence if desired; for now, cache
// as-is)
{
std::lock_guard<std::mutex> lock(AppConfigCacheMutex);
AppConfigCache[key] = result;
}
return result;
}
bool Runtime::showErrorDisplay() {
id value = GetAppConfigValue("showErrorDisplay");
return value ? [value boolValue] : false;
}
void Runtime::DefineGlobalObject(Local<Context> context, bool isWorker) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Object> global = context->Global();
const PropertyAttribute readOnlyFlags =
static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
if (!global
->DefineOwnProperty(context, ToV8String(v8::Isolate::GetCurrent(), "global"), global,
readOnlyFlags)
.FromMaybe(false)) {
tns::Assert(false, isolate);
}
if (isWorker && !global
->DefineOwnProperty(context, ToV8String(v8::Isolate::GetCurrent(), "self"),
global, readOnlyFlags)
.FromMaybe(false)) {
tns::Assert(false, isolate);
}
if (isWorker) {
// Register proper interop types for worker context
// Worker bundles need full interop functionality, not just simple stubs
tns::Interop::RegisterInteropTypes(context);
}
}
void Runtime::DefineCollectFunction(Local<Context> context) {
Isolate* isolate = v8::Isolate::GetCurrent();
Local<Object> global = context->Global();
Local<Value> value;
bool success = global->Get(context, tns::ToV8String(isolate, "gc")).ToLocal(&value);
tns::Assert(success, isolate);
if (value.IsEmpty() || !value->IsFunction()) {
return;
}
Local<v8::Function> gcFunc = value.As<v8::Function>();
const PropertyAttribute readOnlyFlags =
static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
success =
global
->DefineOwnProperty(context, tns::ToV8String(isolate, "__collect"), gcFunc, readOnlyFlags)
.FromMaybe(false);
tns::Assert(success, isolate);
}
double Runtime::PerformanceNowMillis() {
return (platform_->MonotonicallyIncreasingTime() - timeOriginMonotonic_) * 1000.0;
}
void Runtime::DefineNativeScriptVersion(Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
const PropertyAttribute readOnlyFlags =
static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
globalTemplate->Set(ToV8String(isolate, "__runtimeVersion"),
ToV8String(isolate, STRINGIZE_VALUE_OF(NATIVESCRIPT_VERSION)), readOnlyFlags);
}
void Runtime::DefineTimeMethod(v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> globalTemplate) {
Local<FunctionTemplate> timeFunctionTemplate =
FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value>& info) {
auto nano = std::chrono::time_point_cast<std::chrono::nanoseconds>(
std::chrono::steady_clock::now());
double duration = nano.time_since_epoch().count() / 1000000.0;
info.GetReturnValue().Set(duration);
});
globalTemplate->Set(ToV8String(isolate, "__time"), timeFunctionTemplate);
}
void Runtime::DefineDrainMicrotaskMethod(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> globalTemplate) {
Local<FunctionTemplate> drainMicrotaskTemplate =
FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value>& info) {
info.GetIsolate()->PerformMicrotaskCheckpoint();
});
globalTemplate->Set(ToV8String(isolate, "__drainMicrotaskQueue"), drainMicrotaskTemplate);
}
// TODO: remove the __ns__ prefix once the event loop's ordered lane backs
// public macrotask APIs (performance observers etc.)
void Runtime::DefineQueueMacrotaskMethod(v8::Isolate* isolate,
v8::Local<v8::ObjectTemplate> globalTemplate) {
Local<FunctionTemplate> queueMacrotaskTemplate =
FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value>& info) {
auto* isolate = info.GetIsolate();
if (info.Length() < 1 || !info[0]->IsFunction()) {
isolate->ThrowException(Exception::TypeError(
tns::ToV8String(isolate, "__ns__queueMacrotask: callback must be a function")));
return;
}
Runtime* runtime = Runtime::GetRuntime(isolate);
if (runtime == nullptr || runtime->GetEventLoop() == nullptr) {
return;
}
auto callback =
std::make_shared<Persistent<v8::Function>>(isolate, info[0].As<v8::Function>());
// the ordered lane is one due-ordered domain with JS timers, so the
// callback runs as a macrotask in strict FIFO order with them
runtime->GetEventLoop()->PostOrdered([isolate, callback]() {
auto cache = Caches::Get(isolate);
Local<Context> context = cache->GetContext();
Context::Scope context_scope(context);
Local<v8::Function> cb = callback->Get(isolate);
callback->Reset();
// no TryCatch: like timer callbacks, uncaught errors surface
// through the isolate's message listener
(void)cb->Call(context, context->Global(), 0, nullptr);
});
});
globalTemplate->Set(ToV8String(isolate, "__ns__queueMacrotask"), queueMacrotaskTemplate);
}
void Runtime::DefineDateTimeConfigurationChangeNotificationMethod(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> globalTemplate) {
Local<FunctionTemplate> drainMicrotaskTemplate =
FunctionTemplate::New(isolate, [](const FunctionCallbackInfo<Value>& info) {
info.GetIsolate()->DateTimeConfigurationChangeNotification(
Isolate::TimeZoneDetection::kRedetect);
});
globalTemplate->Set(ToV8String(isolate, "__dateTimeConfigurationChangeNotification"),
drainMicrotaskTemplate);
}
void Runtime::DrainRejectionsObserver(CFRunLoopObserverRef observer, CFRunLoopActivity activity,
void* info) {
Isolate* isolate = static_cast<Isolate*>(info);
if (!Runtime::IsAlive(isolate)) {
return;
}
auto cache = Caches::Get(isolate);
// HasPending is an atomic read: OnReject can run on any thread holding the
// v8::Locker, so pending_ itself must only be touched under the lock below.
if (!cache->IsValid() || cache->PromiseRejections == nullptr ||
!cache->PromiseRejections->HasPending()) {
return;
}
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
Local<Context> context = cache->GetContext();
Context::Scope context_scope(context);
cache->PromiseRejections->Drain(context);
}
bool Runtime::IsAlive(const Isolate* isolate) {
// speedup lookup by avoiding locking if thread locals match
// note: this can be a problem when the Runtime is deleted in a different thread that it was
// created which could happen under some specific embedding scenarios
if ((Isolate::TryGetCurrent() == isolate ||
(currentRuntime_ != nullptr && currentRuntime_->GetIsolate() == isolate)) &&
Caches::Get((Isolate*)isolate)->IsValid()) {
return true;
}
SpinLock lock(isolatesMutex_);
return std::find(Runtime::isolates_.begin(), Runtime::isolates_.end(), isolate) !=
Runtime::isolates_.end();
}
napi_env Runtime::GetNapiEnvIfAlive(const Runtime* runtime) {
if (runtime == nullptr) {
return nullptr;
}
SpinLock lock(isolatesMutex_);
for (Isolate* isolate : Runtime::isolates_) {
Runtime* candidate = GetRuntime(isolate);
// The home-loop comparison closes the allocator-reuse (ABA) hole: a stale
// thread-local can only exist on the dead runtime's home thread, and a
// recycled same-address Runtime homed on this thread would have
// overwritten that thread-local — so an address match with a foreign home
// loop can only be a recycled pointer.
if (candidate == runtime && candidate->RuntimeLoop() == CFRunLoopGetCurrent()) {
return candidate->GetNapiEnv();
}
}
return nullptr;
}
Platform* Runtime::platform_ = nullptr;
std::vector<Isolate*> Runtime::isolates_;
bool Runtime::v8Initialized_ = false;
thread_local Runtime* Runtime::currentRuntime_ = nullptr;
SpinMutex Runtime::isolatesMutex_;
} // namespace tns