Repository navigation
Expand file tree
/
Copy pathjsr.cpp
More file actions
583 lines (502 loc) · 20.2 KB
/
Copy pathjsr.cpp
File metadata and controls
583 lines (502 loc) · 20.2 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
#include "jsr.h"
#include <dlfcn.h>
#include <libgen.h>
#include <sys/stat.h>
#include <utime.h>
#include <cstdio>
#include <ctime>
#include <fstream>
#include "libplatform/libplatform.h"
#include "v8-fast-api-calls.h"
#include "v8-module-loader.h"
#ifdef __ANDROID__
#include "NativeScriptAssert.h"
#include "native_api_util.h"
#else
// DEBUG_WRITE is the Android runtime's logging macro (NativeScriptAssert.h).
// The code-cache paths below are shared, so stub it out rather than fork them.
#define DEBUG_WRITE(...) ((void)0)
#endif
using namespace v8;
using namespace tns;
tns::SimpleAllocator g_allocator;
#ifndef __ANDROID__
// Benchmark scaffolding for V8's fast API calls, installed as `fastObject` on
// the global. Apple-only: nothing on Android registers it.
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) {
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);
}
#endif // !__ANDROID__
JSR::JSR() : isolate(nullptr) {
v8::Isolate::CreateParams create_params;
create_params.array_buffer_allocator = &g_allocator;
std::call_once(JSR::initialization_once, [] {
JSR::platform = v8::platform::NewDefaultPlatform();
v8::V8::SetFlagsFromString("--expose_gc");
v8::V8::InitializePlatform(JSR::platform.get());
v8::V8::Initialize();
});
isolate = v8::Isolate::New(create_params);
}
std::unique_ptr<v8::Platform> JSR::platform = nullptr;
std::once_flag JSR::initialization_once;
std::mutex JSR::env_cache_mutex;
std::unordered_map<napi_env, JSR*> JSR::env_to_jsr_cache;
JSR* JSR::ForEnv(napi_env env) {
std::lock_guard<std::mutex> lock(env_cache_mutex);
auto it = env_to_jsr_cache.find(env);
return it == env_to_jsr_cache.end() ? nullptr : it->second;
}
void JSR::RegisterEnv(napi_env env, JSR* runtime) {
std::lock_guard<std::mutex> lock(env_cache_mutex);
env_to_jsr_cache[env] = runtime;
}
void JSR::UnregisterEnv(napi_env env) {
std::lock_guard<std::mutex> lock(env_cache_mutex);
env_to_jsr_cache.erase(env);
}
napi_status js_create_runtime(jsr_ns_runtime* runtime) {
if (!runtime) return napi_invalid_arg;
*runtime = (jsr_ns_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) {
JSR* runtime = JSR::ForEnv(env);
if (runtime == nullptr) {
return napi_invalid_arg;
}
runtime->lock();
return napi_ok;
}
napi_status js_unlock_env(napi_env env) {
JSR* runtime = JSR::ForEnv(env);
if (runtime == nullptr) {
return napi_invalid_arg;
}
runtime->unlock();
return napi_ok;
}
napi_status js_create_napi_env(napi_env* env, jsr_ns_runtime runtime) {
if (env == nullptr) return napi_invalid_arg;
JSR* jsr = (JSR*)runtime;
#ifdef __ANDROID__
// The Android runtime owns thread/isolate entry itself and holds no Locker
// here, so the isolate must be entered and exited explicitly around setup.
jsr->isolate->Enter();
try {
v8::HandleScope handle_scope(jsr->isolate);
v8::Local<v8::Context> context = v8::Context::New(jsr->isolate);
*env = new napi_env__(jsr->isolate, context, NAPI_VERSION_EXPERIMENTAL);
JSR::RegisterEnv(*env, jsr);
Local<Object> global = context->Global();
global->Set(context,
String::NewFromUtf8(jsr->isolate, "__promiseUnhandledEvent")
.ToLocalChecked(),
Integer::New(jsr->isolate,
PromiseRejectEvent::kPromiseRejectWithNoHandler));
global->Set(
context,
String::NewFromUtf8(jsr->isolate, "__promiseHandledEvent")
.ToLocalChecked(),
Integer::New(jsr->isolate,
PromiseRejectEvent::kPromiseHandlerAddedAfterReject));
jsr->isolate->SetPromiseRejectCallback([](PromiseRejectMessage message) {
Local<Promise> promise = message.GetPromise();
Isolate* isolate = Isolate::GetCurrent();
Local<Value> value = message.GetValue();
Local<Integer> event = Integer::New(isolate, message.GetEvent());
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
Local<Object> global = context->Global();
Local<Value> callback =
global
->Get(context, String::NewFromUtf8(
isolate, "onUnhandledPromiseRejectionTracker")
.ToLocalChecked())
.ToLocalChecked();
if (value.IsEmpty()) value = Undefined(isolate);
Local<Value> args[] = {event, promise, value};
callback.As<Function>()->Call(context, global, 3, args);
});
jsr->isolate->Exit();
} catch (...) {
jsr->isolate->Exit();
return napi_generic_failure;
}
#else
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::RegisterEnv(*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();
#endif
return napi_ok;
}
napi_status js_free_napi_env(napi_env env) {
if (env == nullptr) return napi_invalid_arg;
JSR::UnregisterEnv(env);
#ifndef __ANDROID__
// Defined alongside the Apple threadsafe-function layer; Android has no
// equivalent entry point.
js_run_env_cleanup_hooks(env);
#endif
env->DeleteMe();
return napi_ok;
}
napi_status js_free_runtime(jsr_ns_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);
// The ES module cache holds thread-local Globals per isolate. Release them
// now; left to thread exit, they would be reset against a disposed isolate.
v8impl::CleanupESModuleSystem(jsr->isolate);
while (v8::Isolate::GetCurrent() == jsr->isolate) {
jsr->isolate->Exit();
}
}
jsr->isolate->Dispose();
jsr->isolate = nullptr;
delete jsr;
return napi_ok;
}
// Turn a script's source URL into the on-disk JS path we cache next to. Returns
// false for sources that aren't real files (e.g. the synthetic
// "<require_factory>"), which must never be cached.
static bool NormalizeScriptPath(const char* file, std::string& out) {
if (file == nullptr) return false;
std::string f(file);
static const std::string scheme = "file://";
if (f.rfind(scheme, 0) == 0) {
out = f.substr(scheme.size());
} else if (!f.empty() && f[0] == '/') {
out = f; // already a plain absolute path
} else {
return false;
}
return !out.empty();
}
static bool WriteBinaryFile(const std::string& path, const void* data,
int length) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write(static_cast<const char*>(data), length);
out.close();
return out.good();
}
// Create a code cache from an already-compiled script and publish it next to
// the source, stamped with the source's mtime so js_run_cached_script accepts
// it. Best-effort: any failure just leaves no cache behind.
static void PersistCodeCache(v8::Local<v8::UnboundScript> unbound,
const std::string& fsPath) {
ScriptCompiler::CachedData* cachedData =
ScriptCompiler::CreateCodeCache(unbound);
if (cachedData == nullptr) {
DEBUG_WRITE("[code-cache] CreateCodeCache produced no data for: %s",
fsPath.c_str());
return;
}
auto cachePath = fsPath + ".cache";
auto tmpPath = cachePath + ".tmp";
// Write to a temp file then rename into place so a crash or a concurrent
// reader (e.g. a worker loading the same module) never sees a half-written
// cache. Stamp the temp file with the source's mtime *before* the rename so
// the published cache atomically carries the correct staleness marker.
bool wrote = WriteBinaryFile(tmpPath, cachedData->data, cachedData->length);
int cacheLength = cachedData->length;
delete cachedData;
if (!wrote) {
DEBUG_WRITE("[code-cache] failed to write cache file: %s", tmpPath.c_str());
remove(tmpPath.c_str());
return;
}
struct stat srcStat;
struct utimbuf new_times;
new_times.actime = time(nullptr);
new_times.modtime =
(stat(fsPath.c_str(), &srcStat) == 0) ? srcStat.st_mtime : time(nullptr);
utime(tmpPath.c_str(), &new_times);
if (rename(tmpPath.c_str(), cachePath.c_str()) != 0) {
DEBUG_WRITE("[code-cache] failed to publish cache file: %s",
cachePath.c_str());
remove(tmpPath.c_str());
return;
}
DEBUG_WRITE("[code-cache] wrote V8 code cache: %s (%d bytes)",
cachePath.c_str(), cacheLength);
}
// Cold path: compile the source once, publish a code cache from that same
// compilation (so we never compile the file twice), then run it.
static napi_status CompileRunAndCache(napi_env env, napi_value script,
const char* file, napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, script);
CHECK_ARG(env, result);
v8::Local<v8::Value> scriptValue = v8impl::V8LocalValueFromJsValue(script);
if (!scriptValue->IsString()) {
return napi_set_last_error(env, napi_string_expected);
}
v8::Local<v8::String> sourceString = scriptValue.As<v8::String>();
std::string fsPath;
bool cacheable = NormalizeScriptPath(file, fsPath);
// Set the source URL via ScriptOrigin (stack traces + a stable code-cache
// key that matches js_run_cached_script's consume side). For non-file
// sources we still attach the given name for stack traces but don't cache.
std::string sourceUrl = cacheable
? ("file://" + fsPath)
: (file ? std::string(file) : std::string());
auto originStr = v8::String::NewFromUtf8(env->isolate, sourceUrl.c_str());
v8::ScriptOrigin origin(originStr.ToLocalChecked());
ScriptCompiler::Source source(sourceString, origin);
Local<Script> compiled;
if (!ScriptCompiler::Compile(env->context(), &source,
ScriptCompiler::kNoCompileOptions)
.ToLocal(&compiled)) {
// Syntax error — surface it (GET_RETURN_STATUS turns the caught exception
// into napi_pending_exception).
return GET_RETURN_STATUS(env);
}
DEBUG_WRITE("[code-cache] compiling from source (cold): %s (cacheable=%d)",
file, cacheable);
// Publish a code cache from this single compile for the next launch.
if (cacheable) {
PersistCodeCache(compiled->GetUnboundScript(), fsPath);
}
v8::Local<v8::Value> ret;
if (!compiled->Run(env->context()).ToLocal(&ret)) {
return GET_RETURN_STATUS(env); // threw while running
}
*result = v8impl::JsValueFromV8LocalValue(ret);
return GET_RETURN_STATUS(env);
}
napi_status js_execute_script(napi_env env, napi_value script, const char* file,
napi_value* result) {
// Fast path: run V8's on-disk code cache when one is present and current.
// js_run_cached_script returns napi_cannot_run_js on a cache miss (so we fall
// back to source), or any other status when it actually ran the script
// (success or a thrown exception) — in which case we must NOT run it again.
napi_status status = js_run_cached_script(env, file, script, nullptr, result);
if (status != napi_cannot_run_js) {
return status;
}
// Cold path: compile + run the source, producing a code cache from that same
// compilation for the next launch (no second compile).
return CompileRunAndCache(env, script, file, result);
}
napi_status js_execute_pending_jobs(napi_env env) {
#ifndef __ANDROID__
// Apple drives V8's foreground task queue from here; the Android runtime
// pumps its own loop and must not have tasks drained underneath it.
v8::platform::PumpMessageLoop(JSR::platform.get(), env->isolate);
env->isolate->PerformMicrotaskCheckpoint();
env->isolate->ClearKeptObjects();
#endif
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;
}
// Compile `source` and persist a code cache next to `file`. Retained for the
// jsr interface; the hot path (js_execute_script) caches inline from its own
// single compile, so this is only for out-of-band callers that hold just the
// source text. No-op for synthetic / non-file sources.
napi_status js_cache_script(napi_env env, const char* source,
const char* file) {
std::string fsPath;
if (!NormalizeScriptPath(file, fsPath)) {
return napi_ok;
}
v8::Local<v8::String> sourceString =
v8::String::NewFromUtf8(env->isolate, source).ToLocalChecked();
std::string sourceUrl = "file://" + fsPath;
v8::Local<v8::String> fileString =
v8::String::NewFromUtf8(env->isolate, sourceUrl.c_str()).ToLocalChecked();
v8::ScriptOrigin origin(fileString);
// Guard the compile and never let a failed cache write leak a pending
// exception into the caller.
v8::TryCatch tc(env->isolate);
v8::Local<v8::Script> script;
if (!v8::Script::Compile(env->context(), sourceString, &origin)
.ToLocal(&script)) {
if (tc.HasCaught()) tc.Reset();
return napi_ok;
}
PersistCodeCache(script->GetUnboundScript(), fsPath);
return napi_ok;
}
napi_status js_run_cached_script(napi_env env, const char* file,
napi_value script, void* cache,
napi_value* result) {
NAPI_PREAMBLE(env);
CHECK_ARG(env, script);
CHECK_ARG(env, result);
std::string fsPath;
if (!NormalizeScriptPath(file, fsPath)) {
return napi_cannot_run_js; // synthetic / non-file source: no cache
}
auto cachePath = fsPath + ".cache";
struct stat cacheStat;
if (stat(cachePath.c_str(), &cacheStat) != 0) {
DEBUG_WRITE("[code-cache] miss (no cache on disk): %s", fsPath.c_str());
return napi_cannot_run_js; // no cache written yet
}
struct stat srcStat;
if (stat(fsPath.c_str(), &srcStat) == 0 &&
srcStat.st_mtime != cacheStat.st_mtime) {
// Source changed since the cache was written — ignore the stale cache.
DEBUG_WRITE("[code-cache] miss (source newer than cache): %s",
fsPath.c_str());
return napi_cannot_run_js;
}
std::ifstream cacheFile(cachePath, std::ios::binary | std::ios::ate);
if (!cacheFile.is_open()) {
return napi_cannot_run_js;
}
int length = static_cast<int>(cacheFile.tellg());
if (length <= 0) {
return napi_cannot_run_js;
}
cacheFile.seekg(0, std::ios::beg);
auto* data = new uint8_t[length];
cacheFile.read(reinterpret_cast<char*>(data), length);
bool readOk = cacheFile.good() || cacheFile.eof();
cacheFile.close();
if (!readOk) {
delete[] data;
return napi_cannot_run_js;
}
v8::Local<v8::Value> scriptValue = v8impl::V8LocalValueFromJsValue(script);
if (!scriptValue->IsString()) {
delete[] data;
return napi_set_last_error(env, napi_string_expected);
}
v8::Local<v8::String> sourceString = scriptValue.As<v8::String>();
// Source takes ownership of cacheData and frees it.
auto* cacheData = new ScriptCompiler::CachedData(
data, length, ScriptCompiler::CachedData::BufferOwned);
std::string sourceUrl = "file://" + fsPath;
auto originStr = v8::String::NewFromUtf8(env->isolate, sourceUrl.c_str());
v8::ScriptOrigin origin(originStr.ToLocalChecked());
ScriptCompiler::Source source(sourceString, origin, cacheData);
Local<Script> cachedScript;
if (!ScriptCompiler::Compile(env->context(), &source,
ScriptCompiler::kConsumeCodeCache)
.ToLocal(&cachedScript)) {
// Compilation itself failed — the source is genuinely bad (not just a
// stale cache, which V8 handles by recompiling and flagging `rejected`).
// Surface the exception so the caller doesn't retry; there is nothing to
// "fall back" to.
return GET_RETURN_STATUS(env);
}
if (source.GetCachedData() != nullptr && source.GetCachedData()->rejected) {
// The cache was stale/incompatible; V8 recompiled from source but we did
// NOT run it. Report a miss so the caller runs the source and refreshes
// the cache. (No script executed, so no double side effects.)
DEBUG_WRITE("[code-cache] miss (V8 rejected cache as incompatible): %s",
fsPath.c_str());
return napi_cannot_run_js;
}
DEBUG_WRITE("[code-cache] loaded V8 compiled code cache: %s (%d bytes)",
fsPath.c_str(), length);
v8::Local<v8::Value> ret;
if (!cachedScript->Run(env->context()).ToLocal(&ret)) {
// The module threw while executing. This is a real run — propagate the
// exception; the caller must NOT execute the source a second time.
return GET_RETURN_STATUS(env);
}
*result = v8impl::JsValueFromV8LocalValue(ret);
return GET_RETURN_STATUS(env);
}
napi_status js_run_bytecode_file(napi_env env, const char* file,
napi_value* result) {
// V8 has no compile-time bytecode format (it caches code at runtime instead,
// see js_cache_script/js_run_cached_script); always fall back to source.
return napi_cannot_run_js;
}
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;
}