-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjsr.cpp
More file actions
346 lines (287 loc) · 10.8 KB
/
jsr.cpp
File metadata and controls
346 lines (287 loc) · 10.8 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
#include "jsr.h"
#include <dlfcn.h>
#include <libgen.h>
#include <sys/stat.h>
#include <utime.h>
#include <ctime>
#include <fstream>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#include "libplatform/libplatform.h"
#include "v8-fast-api-calls.h"
using namespace v8;
using namespace tns;
#if defined(__APPLE__) && TARGET_OS_IPHONE
static_assert(v8::internal::PointerCompressionIsEnabled(),
"iOS V8 embedder must be built with pointer compression enabled");
static_assert(v8::internal::SmiValuesAre31Bits(),
"iOS V8 embedder must use 31-bit smis on 64-bit arch");
#endif
tns::SimpleAllocator g_allocator;
static void divide(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsInt32());
CHECK(args[1]->IsInt32());
auto a = args[0].As<v8::Int32>();
auto b = args[1].As<v8::Int32>();
if (b->Value() == 0) {
return;
}
double result = a->Value() / b->Value();
args.GetReturnValue().Set(result);
}
static double FastDivide(const int32_t this_arg, const int32_t a,
const int32_t b, v8::FastApiCallbackOptions& options) {
// DEBUG_WRITE_FORCE("%s", "FAST");
if (b == 0) {
#if V8_MAJOR_VERSION < 14
options.fallback = true;
#endif
return 0;
} else {
return a / b;
}
}
CFunction fast_divide_(CFunction::Make(FastDivide));
Local<v8::FunctionTemplate> NewFunctionTemplate(
v8::Isolate* isolate, v8::FunctionCallback callback, Local<v8::Value> data,
Local<v8::Signature> signature, v8::ConstructorBehavior behavior,
v8::SideEffectType side_effect_type, const v8::CFunction* c_function) {
return v8::FunctionTemplate::New(isolate, callback, data, signature, 0,
behavior, side_effect_type, c_function);
}
void SetFastMethod(Isolate* isolate, Local<Template> that, const char* name,
v8::FunctionCallback slow_callback,
const v8::CFunction* c_function, Local<v8::Value> data) {
Local<v8::FunctionTemplate> t =
NewFunctionTemplate(isolate, slow_callback, data, Local<v8::Signature>(),
v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasSideEffect, c_function);
// kInternalized strings are created in the old space.
const v8::NewStringType type = v8::NewStringType::kInternalized;
Local<v8::String> name_string =
v8::String::NewFromUtf8(isolate, name, type).ToLocalChecked();
that->Set(name_string, t);
}
JSR::JSR() : isolate(nullptr) {
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &g_allocator;
if (!JSR::s_mainThreadInitialized) {
JSR::platform = v8::platform::NewDefaultPlatform().release();
v8::V8::SetFlagsFromString("--expose_gc");
v8::V8::InitializePlatform(JSR::platform);
v8::V8::Initialize();
JSR::s_mainThreadInitialized = true;
}
isolate = v8::Isolate::New(create_params);
}
v8::Platform* JSR::platform = nullptr;
bool JSR::s_mainThreadInitialized = false;
std::unordered_map<napi_env, JSR*> JSR::env_to_jsr_cache;
napi_status js_create_runtime(napi_runtime* runtime) {
if (!runtime) return napi_invalid_arg;
*runtime = (napi_runtime) new JSR();
return napi_ok;
}
napi_status js_set_runtime_flags(const char* flags) {
V8::V8::SetFlagsFromString(flags);
return napi_ok;
}
napi_status js_lock_env(napi_env env) {
auto itFound = JSR::env_to_jsr_cache.find(env);
if (itFound == JSR::env_to_jsr_cache.end()) {
return napi_invalid_arg;
}
itFound->second->lock();
return napi_ok;
}
napi_status js_unlock_env(napi_env env) {
auto itFound = JSR::env_to_jsr_cache.find(env);
if (itFound == JSR::env_to_jsr_cache.end()) {
return napi_invalid_arg;
}
itFound->second->unlock();
return napi_ok;
}
napi_status js_create_napi_env(napi_env* env, napi_runtime runtime) {
if (env == nullptr) return napi_invalid_arg;
JSR* jsr = (JSR*)runtime;
v8::Locker locker(jsr->isolate);
v8::Isolate::Scope isolate_scope(jsr->isolate);
v8::HandleScope handle_scope(jsr->isolate);
v8::Local<v8::Context> context = v8::Context::New(jsr->isolate);
v8::Context::Scope context_scope(context);
*env = new napi_env__(jsr->isolate, context, NAPI_VERSION_EXPERIMENTAL);
JSR::env_to_jsr_cache.insert(std::make_pair(*env, jsr));
v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
jsr->isolate, [](const v8::FunctionCallbackInfo<v8::Value>& args) {
});
// Set the function on the global object
v8::Local<v8::Function> func =
func_template->GetFunction(context).ToLocalChecked();
context->Global()
->Set(context,
v8::String::NewFromUtf8(jsr->isolate, "directFunction")
.ToLocalChecked(),
func)
.FromJust();
v8::Local<v8::ObjectTemplate> global_template =
v8::ObjectTemplate::New(jsr->isolate);
SetFastMethod(jsr->isolate, global_template, "directFunction", divide,
&fast_divide_, v8::Local<Value>());
// Create an instance of the ObjectTemplate
v8::Local<v8::Object> instance =
global_template->NewInstance(context).ToLocalChecked();
context->Global()
->Set(
context,
v8::String::NewFromUtf8(jsr->isolate, "fastObject").ToLocalChecked(),
instance)
.FromJust();
return napi_ok;
}
napi_status js_free_napi_env(napi_env env) {
if (env == nullptr) return napi_invalid_arg;
JSR::env_to_jsr_cache.erase(env);
js_run_env_cleanup_hooks(env);
env->DeleteMe();
return napi_ok;
}
napi_status js_free_runtime(napi_runtime runtime) {
if (runtime == nullptr) return napi_invalid_arg;
JSR* jsr = (JSR*)runtime;
if (jsr == nullptr || jsr->isolate == nullptr) return napi_invalid_arg;
// Ensure there are no outstanding current-thread isolate entries while we
// still hold a valid lock object. The isolate must be disposed only after
// the locker has been destroyed.
{
v8::Locker locker(jsr->isolate);
while (v8::Isolate::GetCurrent() == jsr->isolate) {
jsr->isolate->Exit();
}
}
jsr->isolate->Dispose();
jsr->isolate = nullptr;
delete jsr;
return napi_ok;
}
napi_status js_execute_script(napi_env env, napi_value script, const char* file,
napi_value* result) {
return napi_run_script_source(env, script, file, result);
}
napi_status js_execute_pending_jobs(napi_env env) {
env->isolate->RequestGarbageCollectionForTesting(
v8::Isolate::kFullGarbageCollection);
v8::platform::PumpMessageLoop(JSR::platform, env->isolate);
env->isolate->PerformMicrotaskCheckpoint();
env->isolate->ClearKeptObjects();
env->isolate->PerformMicrotaskCheckpoint();
return napi_ok;
}
napi_status js_get_engine_ptr(napi_env env, int64_t* engine_ptr) {
*engine_ptr = reinterpret_cast<int64_t>(env->isolate);
return napi_ok;
}
napi_status js_adjust_external_memory(napi_env env, int64_t changeInBytes,
int64_t* externalMemory) {
*externalMemory =
env->isolate->AdjustAmountOfExternalAllocatedMemory(changeInBytes);
return napi_ok;
}
napi_status js_cache_script(napi_env env, const char* source,
const char* file) {
v8::Local<v8::String> sourceString =
v8::String::NewFromUtf8(env->isolate, source).ToLocalChecked();
v8::Local<v8::String> fileString =
v8::String::NewFromUtf8(env->isolate, file).ToLocalChecked();
#if V8_MAJOR_VERSION >= 14
v8::ScriptOrigin origin(fileString);
#else
v8::ScriptOrigin origin(env->isolate, fileString);
#endif
v8::Local<v8::Script> script =
v8::Script::Compile(env->context(), sourceString, &origin)
.ToLocalChecked();
Local<UnboundScript> unboundScript = script->GetUnboundScript();
ScriptCompiler::CachedData* cachedData =
ScriptCompiler::CreateCodeCache(unboundScript);
int length = cachedData->length;
auto cachePath = std::string(file) + ".cache";
// File::WriteBinary(cachePath, cachedData->data, length);
std::ofstream cacheFile(cachePath, std::ios::binary);
cacheFile.write(reinterpret_cast<const char*>(cachedData->data), length);
cacheFile.close();
delete cachedData;
// make sure cache and js file have the same modification date
struct stat result;
struct utimbuf new_times;
new_times.actime = time(nullptr);
new_times.modtime = time(nullptr);
if (stat(file, &result) == 0) {
auto jsLastModifiedTime = result.st_mtime;
new_times.modtime = jsLastModifiedTime;
}
utime(cachePath.c_str(), &new_times);
return napi_ok;
}
napi_status js_run_cached_script(napi_env env, const char* file,
napi_value script, void* cache,
napi_value* result) {
auto cachePath = std::string(file) + ".cache";
struct stat s_result;
if (stat(cachePath.c_str(), &s_result) == 0) {
auto cacheLastModifiedTime = s_result.st_mtime;
if (stat(file, &s_result) == 0) {
auto jsLastModifiedTime = s_result.st_mtime;
if (jsLastModifiedTime != cacheLastModifiedTime) {
// files have different dates, ignore the cache file (this is enforced
// by the SaveScriptCache function)
return napi_cannot_run_js;
}
}
}
int length = 0;
// auto data = File::ReadBinary(cachePath, length);
// if (!data) {
// return napi_cannot_run_js;
// }
std::ifstream cacheFile(cachePath, std::ios::binary);
if (!cacheFile.is_open()) {
return napi_cannot_run_js;
}
cacheFile.seekg(0, std::ios::end);
length = cacheFile.tellg();
cacheFile.seekg(0, std::ios::beg);
char* data = new char[length];
cacheFile.read(data, length);
cacheFile.close();
auto* cacheData =
new ScriptCompiler::CachedData(reinterpret_cast<uint8_t*>(data), length,
ScriptCompiler::CachedData::BufferOwned);
std::string filePath = std::string("file://") + file;
auto fullRequiredModulePathWithSchema =
v8::String::NewFromUtf8(env->isolate, filePath.c_str());
#if V8_MAJOR_VERSION >= 14
ScriptOrigin origin(fullRequiredModulePathWithSchema.ToLocalChecked());
#else
ScriptOrigin origin(env->isolate,
fullRequiredModulePathWithSchema.ToLocalChecked());
#endif
v8::Local<v8::String> scriptText;
memcpy(static_cast<void*>(&scriptText), &script, sizeof(script));
TryCatch tc(env->isolate);
ScriptCompiler::Source source(scriptText, origin, cacheData);
ScriptCompiler::CompileOptions option = ScriptCompiler::kConsumeCodeCache;
auto maybeScript = ScriptCompiler::Compile(env->context(), &source, option);
if (maybeScript.IsEmpty() || tc.HasCaught()) {
return napi_cannot_run_js;
}
Local<Script> cached_script = maybeScript.ToLocalChecked();
v8::Local<Value> ret = cached_script->Run(env->context()).ToLocalChecked();
*result = reinterpret_cast<napi_value>(*ret);
return napi_ok;
}
napi_status js_get_runtime_version(napi_env env, napi_value* version) {
napi_create_string_utf8(env, "V8", NAPI_AUTO_LENGTH, version);
return napi_ok;
}