forked from NativeScript/ios
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntime.mm
More file actions
645 lines (549 loc) · 23.1 KB
/
Runtime.mm
File metadata and controls
645 lines (549 loc) · 23.1 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
#include "Runtime.h"
#include <chrono>
#include <string>
#include "ArgConverter.h"
#include "Caches.h"
#include "Console.h"
#include "Constants.h"
#include "Helpers.h"
#include "InlineFunctions.h"
#include "Interop.h"
#include "NativeScriptException.h"
#include "ObjectManager.h"
#include "PromiseProxy.h"
#include "RuntimeConfig.h"
#include "SimpleAllocator.h"
#include "SpinLock.h"
#include "TSHelpers.h"
#include "WeakRef.h"
#include "Worker.h"
// #include "SetTimeout.h"
#include "DisposerPHV.h"
#include "IsolateWrapper.h"
#include <mutex>
#include <unordered_map>
#include "DevFlags.h"
#include "HMRSupport.h"
#include "ModuleBinding.hpp"
#include "ModuleInternalCallbacks.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
static void InitializeImportMetaObject(Local<Context> context, Local<Module> module,
Local<Object> meta) {
Isolate* isolate = context->GetIsolate();
// Look up the module path in the global module registry (with safety checks)
std::string modulePath;
try {
for (auto& kv : tns::g_moduleRegistry) {
// Check if Global handle is empty before accessing
if (kv.second.IsEmpty()) {
continue;
}
Local<Module> registered = kv.second.Get(isolate);
if (!registered.IsEmpty() && registered == module) {
modulePath = kv.first;
break;
}
}
} catch (...) {
// NSLog(@"[import.meta] Exception during module registry lookup, using fallback");
modulePath = ""; // Will use fallback path
}
// Debug logging
// NSLog(@"[import.meta] Module lookup: found path = %s",
// modulePath.empty() ? "(empty)" : modulePath.c_str());
// NSLog(@"[import.meta] Registry size: %zu", tns::g_moduleRegistry.size());
// Convert file path to file:// URL
std::string moduleUrl;
if (!modulePath.empty()) {
// Remove base directory and create file:// URL
std::string base = tns::ReplaceAll(modulePath, RuntimeConfig.BaseDir, "");
moduleUrl = "file://" + base;
} else {
// Fallback URL if module not found in registry
moduleUrl = "file:///app/";
}
// NSLog(@"[import.meta] Final URL: %s", moduleUrl.c_str());
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();
// Add import.meta.dirname support (extract directory from path)
std::string dirname;
if (!modulePath.empty()) {
size_t lastSlash = modulePath.find_last_of("/\\");
if (lastSlash != std::string::npos) {
dirname = modulePath.substr(0, lastSlash);
} else {
dirname = "/app"; // fallback
}
} 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();
if (RuntimeConfig.IsDebug) {
// Attach minimal import.meta.hot only in dev
try {
tns::InitializeImportMetaHot(isolate, context, meta, modulePath);
} catch (...) {
// If anything fails, keep meta without hot to avoid crashing
}
}
}
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 when JavaScript errors occur during execution
bool jsErrorOccurred = false;
// 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) {
// most of the time, this will never delay disposal
// occasionally this can happen when the runtime is destroyed by actions of its own isolate
// as an example: isolate calls exit(0), which in turn destroys the Runtime unique_ptr
// another scenario is when embedding nativescript, if the embedder deletes the runtime as a
// result of a callback from JS in the case of exit(0), the app will die before actually disposing
// the isolate, which isn't a problem
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() { MetaFile::setInstance(RuntimeConfig.MetadataPtr); }
Runtime::Runtime() {
currentRuntime_ = this;
workerId_ = -1;
workerCache_ = Caches::Workers;
}
Runtime::~Runtime() {
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_);
// Clear module registry before disposing other handles
// This prevents crashes during g_moduleRegistry cleanup
extern std::unordered_map<std::string, v8::Global<v8::Module>> g_moduleRegistry;
for (auto& kv : g_moduleRegistry) {
kv.second.Reset();
}
g_moduleRegistry.clear();
DisposerPHV phv(isolate_);
isolate_->VisitHandlesWithClassIds(&phv);
if (IsRuntimeWorker()) {
auto currentWorker =
static_cast<WorkerWrapper*>(Caches::Workers->Get(this->workerId_)->UserData());
Caches::Workers->Remove(this->workerId_);
// if the parent isolate is dead then deleting the wrapper is our responsibility
if (currentWorker->IsWeak()) {
delete currentWorker;
}
}
Caches::Remove(this->isolate_);
this->isolate_->SetData(Constants::RUNTIME_SLOT, nullptr);
}
DisposeIsolateWhenPossible(this->isolate_);
currentRuntime_ = nullptr;
}
Runtime* Runtime::GetRuntime(v8::Isolate* isolate) {
return static_cast<Runtime*>(isolate->GetData(Constants::RUNTIME_SLOT));
}
Isolate* Runtime::CreateIsolate() {
if (!v8Initialized_) {
// Runtime::platform_ = RuntimeConfig.IsDebug
// ? v8_inspector::V8InspectorPlatform::CreateDefaultPlatform()
// : platform::NewDefaultPlatform();
Runtime::platform_ = platform::NewDefaultPlatform();
V8::InitializePlatform(Runtime::platform_.get());
V8::Initialize();
std::string flags =
RuntimeConfig.IsDebug ? "--expose_gc --jitless" : "--expose_gc --jitless --no-lazy";
V8::SetFlagsFromString(flags.c_str(), flags.size());
v8Initialized_ = true;
}
startTime = platform_->MonotonicallyIncreasingTime();
realtimeOrigin = platform_->CurrentClockTimeMillis();
// auto version = v8::V8::GetVersion();
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &allocator_;
Isolate* isolate = Isolate::New(create_params);
runtimeLoop_ = CFRunLoopGetCurrent();
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);
DefinePerformanceObject(isolate, globalTemplate);
DefineTimeMethod(isolate, globalTemplate);
DefineDrainMicrotaskMethod(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);
// SetTimeout::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);
Local<Context> context = Context::New(isolate, nullptr, globalTemplate);
context->Enter();
DefineGlobalObject(context, isWorker);
DefineCollectFunction(context);
PromiseProxy::Init(context);
Console::Init(context);
WeakRef::Init(context);
auto blob_methods = R"js(
const BLOB_STORE = new Map();
URL.createObjectURL = function (object, options = null) {
try {
if (object instanceof Blob || object instanceof File) {
const id = NSUUID.UUID().UUIDString.toLowerCase();
const ret = `blob:nativescript/${id}`;
BLOB_STORE.set(ret, {
blob: object,
type: object?.type,
ext: options?.ext,
});
return ret;
}
} catch (error) {
return null;
}
return null;
};
URL.revokeObjectURL = function (url) {
BLOB_STORE.delete(url);
};
const InternalAccessor = class {};
InternalAccessor.getData = function (url) {
return BLOB_STORE.get(url);
};
URL.InternalAccessor = InternalAccessor;
Object.defineProperty(URL.prototype, 'searchParams', {
get() {
if (this._searchParams == null) {
this._searchParams = new URLSearchParams(this.search);
Object.defineProperty(this._searchParams, '_url', {
enumerable: false,
writable: false,
value: this,
});
this._searchParams._append = this._searchParams.append;
this._searchParams.append = function (name, value) {
this._append(name, value);
this._url.search = this.toString();
};
this._searchParams._delete = this._searchParams.delete;
this._searchParams.delete = function (name) {
this._delete(name);
this._url.search = this.toString();
};
this._searchParams._set = this._searchParams.set;
this._searchParams.set = function (name, value) {
this._set(name, value);
this._url.search = this.toString();
};
this._searchParams._sort = this._searchParams.sort;
this._searchParams.sort = function () {
this._sort();
this._url.search = this.toString();
};
}
return this._searchParams;
},
});
)js";
v8::Local<v8::Script> script;
auto done = v8::Script::Compile(context, ToV8String(isolate, blob_methods)).ToLocal(&script);
v8::Local<v8::Value> outVal;
if (done) {
done = script->Run(context).ToLocal(&outVal);
}
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->isolate_ = isolate;
}
void Runtime::RunMainScript() {
Isolate* isolate = this->GetIsolate();
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
auto cache = Caches::Get(isolate);
auto context = cache->GetContext();
Context::Scope context_scope(context);
this->moduleInternal_->RunModule(isolate, "./");
}
void Runtime::RunModule(const std::string moduleName) {
Isolate* isolate = this->GetIsolate();
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
auto cache = Caches::Get(isolate);
auto context = cache->GetContext();
Context::Scope context_scope(context);
this->moduleInternal_->RunModule(isolate, moduleName);
}
void Runtime::RunScript(const std::string script) {
Isolate* isolate = this->GetIsolate();
v8::Locker locker(isolate);
Isolate::Scope isolate_scope(isolate);
HandleScope handle_scope(isolate);
auto cache = Caches::Get(isolate);
auto context = cache->GetContext();
Context::Scope context_scope(context);
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 = context->GetIsolate();
Local<Object> global = context->Global();
const PropertyAttribute readOnlyFlags =
static_cast<PropertyAttribute>(PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly);
if (!global
->DefineOwnProperty(context, ToV8String(context->GetIsolate(), "global"), global,
readOnlyFlags)
.FromMaybe(false)) {
tns::Assert(false, isolate);
}
if (isWorker && !global
->DefineOwnProperty(context, ToV8String(context->GetIsolate(), "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 = context->GetIsolate();
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);
}
void Runtime::DefinePerformanceObject(Isolate* isolate, Local<ObjectTemplate> globalTemplate) {
Local<ObjectTemplate> performanceTemplate = ObjectTemplate::New(isolate);
Local<FunctionTemplate> nowFuncTemplate = FunctionTemplate::New(isolate, PerformanceNowCallback);
performanceTemplate->Set(tns::ToV8String(isolate, "now"), nowFuncTemplate);
performanceTemplate->Set(tns::ToV8String(isolate, "timeOrigin"),
v8::Number::New(isolate, realtimeOrigin));
Local<v8::String> performancePropertyName = ToV8String(isolate, "performance");
globalTemplate->Set(performancePropertyName, performanceTemplate);
}
void Runtime::PerformanceNowCallback(const FunctionCallbackInfo<Value>& args) {
auto runtime = Runtime::GetRuntime(args.GetIsolate());
args.GetReturnValue().Set(
(runtime->platform_->MonotonicallyIncreasingTime() - runtime->startTime) * 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);
}
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);
}
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();
}
std::shared_ptr<Platform> Runtime::platform_;
std::vector<Isolate*> Runtime::isolates_;
bool Runtime::v8Initialized_ = false;
thread_local Runtime* Runtime::currentRuntime_ = nullptr;
SpinMutex Runtime::isolatesMutex_;
} // namespace tns