-
-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathRuntime.mm
More file actions
326 lines (266 loc) · 12.6 KB
/
Copy pathRuntime.mm
File metadata and controls
326 lines (266 loc) · 12.6 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
#include <string>
#include <chrono>
#include "Runtime.h"
#include "Caches.h"
#include "Console.h"
#include "ArgConverter.h"
#include "Interop.h"
#include "NativeScriptException.h"
#include "InlineFunctions.h"
#include "SimpleAllocator.h"
#include "ObjectManager.h"
#include "RuntimeConfig.h"
#include "PromiseProxy.h"
#include "Helpers.h"
#include "TSHelpers.h"
#include "WeakRef.h"
#include "Worker.h"
#include "Constants.h"
#include "SpinLock.h"
// #include "SetTimeout.h"
#include "IsolateWrapper.h"
#include "DisposerPHV.h"
#include "cppgc/default-platform.h"
#include "cppgc/heap.h"
#define STRINGIZE(x) #x
#define STRINGIZE_VALUE_OF(x) STRINGIZE(x)
using namespace v8;
using namespace std;
namespace tns {
std::atomic<int> Runtime::nextIsolateId{0};
SimpleAllocator allocator_;
NSDictionary* AppPackageJson = nil;
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());
}
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_);
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();
Runtime::platform_ = std::make_shared<cppgc::DefaultPlatform>();
V8::InitializePlatform(Runtime::GetPlatform());
cppgc::InitializeProcess(Runtime::platform_->GetPageAllocator());
std::string flags = RuntimeConfig.IsDebug
? "--expose_gc --jitless --no-freeze_flags_after_init"
: "--expose_gc --jitless --no-lazy --freeze_flags_after_init=false";
V8::SetFlagsFromString(flags.c_str(), flags.size());
V8::Initialize();
v8Initialized_ = true;
}
// auto version = v8::V8::GetVersion();
Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &allocator_;
std::unique_ptr<v8::CppHeap> cpp_heap = v8::CppHeap::Create(Runtime::GetPlatform(), {
/* std::vector<std::unique_ptr<cppgc::CustomSpaceBase>> custom_spaces */
{},
/* WrapperDescriptor wrapper_descriptor */
kGarbageCollectedWrapperDescriptor,
});
Isolate* isolate = Isolate::New(create_params);
isolate->AttachCppHeap(cpp_heap.release());
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->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"));
Local<ObjectTemplate> globalTemplate = ObjectTemplate::New(isolate, globalTemplateFunction);
DefineNativeScriptVersion(isolate, globalTemplate);
Worker::Init(isolate, globalTemplate, isWorker);
DefinePerformanceObject(isolate, globalTemplate);
DefineTimeMethod(isolate, globalTemplate);
DefineDrainMicrotaskMethod(isolate, globalTemplate);
ObjectManager::Init(isolate, globalTemplate);
// SetTimeout::Init(isolate, globalTemplate);
MetadataBuilder::RegisterConstantsOnGlobalObject(isolate, globalTemplate, isWorker);
isolate->SetCaptureStackTraceForUncaughtExceptions(true, 100, StackTrace::kOverview);
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);
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);
this->moduleInternal_->RunModule(isolate, "./");
}
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);
}
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];
}
}
id result = AppPackageJson[[NSString stringWithUTF8String:key.c_str()]];
return result;
}
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);
}
}
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);
Local<v8::String> performancePropertyName = ToV8String(isolate, "performance");
globalTemplate->Set(performancePropertyName, performanceTemplate);
}
void Runtime::PerformanceNowCallback(const FunctionCallbackInfo<Value>& args) {
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::milliseconds timestampMs = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
double result = timestampMs.count();
args.GetReturnValue().Set(result);
}
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);
}
bool Runtime::IsAlive(const Isolate* isolate) {
SpinLock lock(isolatesMutex_);
return std::find(Runtime::isolates_.begin(), Runtime::isolates_.end(), isolate) != Runtime::isolates_.end();
}
std::shared_ptr<cppgc::DefaultPlatform> Runtime::platform_;
std::vector<Isolate*> Runtime::isolates_;
bool Runtime::v8Initialized_ = false;
thread_local Runtime* Runtime::currentRuntime_ = nullptr;
SpinMutex Runtime::isolatesMutex_;
}