-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRuntime.cpp
More file actions
250 lines (201 loc) · 7.54 KB
/
Runtime.cpp
File metadata and controls
250 lines (201 loc) · 7.54 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
#include "native_api_util.h"
#include "runtime/SpinLock.h"
#ifdef ENABLE_JS_RUNTIME
#include "Runtime.h"
#include "RuntimeConfig.h"
#include "js_native_api.h"
#include "js_native_api_types.h"
#include "jsr.h"
#include "jsr_common.h"
#include "runtime/modules/RuntimeModules.h"
#ifdef TARGET_ENGINE_V8
#include "v8-api.h"
#endif // TARGET_ENGINE_V8
#include <CoreFoundation/CFRunLoop.h>
#include "NativeScript.h"
#include "robin_hood.h"
namespace nativescript {
static robin_hood::unordered_map<napi_env, Runtime*> runtimes_;
std::atomic<int> Runtime::nextIsolateId{0};
Runtime* Runtime::GetRuntime(napi_env env) {
auto it = runtimes_.find(env);
if (it != runtimes_.end()) {
return it->second;
}
return nullptr;
}
Runtime::Runtime() {
currentRuntime_ = this;
workerId_ = -1;
// workerCache_ = Caches::Workers;
}
Runtime::~Runtime() {
currentRuntime_ = nullptr;
modules_.DeInit();
if (env_) {
napi_close_handle_scope(env_, globalScope_);
{
NapiScope scope(env_);
js_free_napi_env(env_);
}
js_free_runtime(runtime_);
}
{
SpinLock lock(envsMutex_);
runtimes_.erase(env_);
}
}
napi_value drainMicrotasks(napi_env env, napi_callback_info cbinfo) {
js_execute_pending_jobs(env);
return nullptr;
}
void Runtime::Init(bool isWorker) {
js_set_runtime_flags("");
auto now = std::chrono::steady_clock::now();
startTime_ = std::chrono::duration<double>(now.time_since_epoch()).count();
auto sysNow = std::chrono::system_clock::now();
realtimeOrigin_ = std::chrono::duration_cast<std::chrono::milliseconds>(
sysNow.time_since_epoch())
.count();
js_create_runtime(&runtime_);
js_create_napi_env(&env_, runtime_);
runtimeLoop_ = CFRunLoopGetCurrent();
{
SpinLock lock(envsMutex_);
runtimes_[env_] = this;
}
#ifdef TARGET_ENGINE_V8
v8::Locker locker(env_->isolate);
v8::Isolate::Scope isolate_scope(env_->isolate);
v8::Context::Scope context_scope(env_->context());
#endif // TARGET_ENGINE_V8
napi_open_handle_scope(env_, &globalScope_);
napi_handle_scope scope;
napi_open_handle_scope(env_, &scope);
napi_value global;
napi_get_global(env_, &global);
napi_set_named_property(env_, global, "global", global);
const char* CompatScript = R"(
if (!WeakRef.prototype.get) WeakRef.prototype.get = function() {
return this.deref();
};
if (!globalThis.__collect) {
globalThis.__collect = function() {
gc();
};
}
if (!globalThis.gc) {
globalThis.gc = function() {
console.warn('gc() is not exposed');
};
}
)";
napi_value compatScript, result;
napi_create_string_utf8(env_, CompatScript, NAPI_AUTO_LENGTH, &compatScript);
napi_run_script(env_, compatScript, &result);
#ifdef TARGET_ENGINE_V8
const char *PromiseProxyScript = R"(
// Ensure that Promise callbacks are executed on the
// same thread on which they were created
(() => {
global.Promise = new Proxy(global.Promise, {
construct: function(target, args) {
let origFunc = args[0];
let runloop = CFRunLoopGetCurrent();
let promise = new target(function(resolve, reject) {
function isFulfilled() {
return !resolve;
}
function markFulfilled() {
origFunc = null;
resolve = null;
reject = null;
}
origFunc(value => {
if (isFulfilled()) {
return;
}
const resolveCall = resolve.bind(this, value);
if (runloop === CFRunLoopGetCurrent()) {
markFulfilled();
resolveCall();
} else {
CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, resolveCall);
CFRunLoopWakeUp(runloop);
markFulfilled();
}
}, reason => {
if (isFulfilled()) {
return;
}
const rejectCall = reject.bind(this, reason);
if (runloop === CFRunLoopGetCurrent()) {
markFulfilled();
rejectCall();
} else {
CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, rejectCall);
CFRunLoopWakeUp(runloop);
markFulfilled();
}
});
});
return new Proxy(promise, {
get: function(target, name) {
let orig = target[name];
if (name === "then" || name === "catch" || name === "finally") {
return orig.bind(target);
}
return typeof orig === 'function' ? function(x) {
if (runloop === CFRunLoopGetCurrent()) {
orig.bind(target, x)();
return target;
}
CFRunLoopPerformBlock(runloop, kCFRunLoopDefaultMode, orig.bind(target, x));
CFRunLoopWakeUp(runloop);
return target;
} : orig;
}
});
}
});
})();
)";
napi_value promiseProxyScript;
napi_create_string_utf8(env_, PromiseProxyScript, NAPI_AUTO_LENGTH, &promiseProxyScript);
napi_run_script(env_, promiseProxyScript, &result);
#endif // TARGET_ENGINE_V8
if (isWorker) {
napi_property_descriptor prop = napi_util::desc("self", global);
napi_define_properties(env_, global, 1, &prop);
}
napi_property_descriptor prop = napi_util::desc(
"__drainMicrotaskQueue", drainMicrotasks, nullptr);
napi_define_properties(env_, global, 1, &prop);
modules_.Init(env_, global);
const char* metadata_path = std::getenv("NS_METADATA_PATH");
nativescript_init(env_, metadata_path, RuntimeConfig.MetadataPtr);
napi_close_handle_scope(env_, scope);
}
const int Runtime::WorkerId() { return this->workerId_; }
void Runtime::SetWorkerId(int workerId) { this->workerId_ = workerId; }
void Runtime::RunScript(std::string& scriptSrc, std::string file) {
NapiScope scope(env_);
napi_value script, result;
napi_create_string_utf8(env_, scriptSrc.c_str(), scriptSrc.length(), &script);
js_execute_script(env_, script, file.c_str(), &result);
}
napi_value Runtime::RunModule(std::string spec) {
NapiScope scope(env_);
return modules_.module.Require(env_, spec, RuntimeConfig.BaseDir);
}
void Runtime::RunMainModule() { napi_value result = RunModule("./"); }
void Runtime::RunLoop() { CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true); }
bool Runtime::IsAlive(napi_env env) {
SpinLock lock(envsMutex_);
auto it = runtimes_.find(env);
return it != runtimes_.end();
}
thread_local Runtime* Runtime::currentRuntime_ = nullptr;
SpinMutex Runtime::envsMutex_;
} // namespace nativescript
#endif // ENABLE_JS_RUNTIME