Repository navigation
Expand file tree
/
Copy pathjsr.cpp
More file actions
372 lines (329 loc) · 13.7 KB
/
Copy pathjsr.cpp
File metadata and controls
372 lines (329 loc) · 13.7 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
#include "jsr.h"
#ifdef __ANDROID__
// Both of these are jsc-android specific. JSContextRefPrivate.h is JSC SPI --
// Apple exports JSGlobalContextSetUnhandledRejectionCallback from
// JavaScriptCore.tbd but ships no public header for it. JSBytecodeCache.h does
// not exist on Apple at all: the on-disk program bytecode cache is added by the
// jsc-android build via jsc_android_bytecode_cache.patch. So the whole cache
// path below, and the rejection tracker, are Android-only; Apple runs from
// source and reports rejections through its own FFI layer.
#include <JavaScriptCore/JSBytecodeCache.h>
#include <JavaScriptCore/JSContextRefPrivate.h>
#include <sys/stat.h>
#include <utime.h>
#include <cstdio>
#include <ctime>
#include <string>
#include "NativeScriptAssert.h"
#endif
#ifdef __ANDROID__
// Native trampoline for JSC's unhandled-promise-rejection callback. JSC invokes
// it with (promise, reason); we forward to the JS-side
// globalThis.onUnhandledPromiseRejectionTracker (installed by ts_helpers.js),
// mirroring how the V8 path routes rejections.
static napi_value JscUnhandledRejectionCallback(napi_env env,
napi_callback_info info) {
size_t argc = 2;
napi_value args[2];
napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);
napi_value global, tracker;
napi_get_global(env, &global);
napi_get_named_property(env, global, "onUnhandledPromiseRejectionTracker",
&tracker);
napi_valuetype type;
napi_typeof(env, tracker, &type);
if (type == napi_function) {
napi_call_function(env, global, tracker, argc, args, nullptr);
}
return nullptr;
}
#endif // __ANDROID__
napi_status js_create_runtime(jsr_ns_runtime* runtime) {
if (!runtime) return napi_invalid_arg;
*runtime = (jsr_ns_runtime)JSGlobalContextCreateInGroup(nullptr, nullptr);
return napi_ok;
}
napi_status js_create_napi_env(napi_env* env, jsr_ns_runtime runtime) {
if (env == nullptr) return napi_invalid_arg;
*env = new napi_env__((JSGlobalContextRef)runtime);
JSGlobalContextRelease((JSGlobalContextRef)runtime);
napi_value gc;
napi_create_function(
*env, "gc", strlen("gc"),
[](napi_env env, napi_callback_info info) -> napi_value {
// JSGarbageCollect only hints: JSC may defer or decline the collection,
// so an unreachable object need not be reclaimed by the time this
// returns. That is how the engine is designed rather than a defect, and
// the specs that observe reclamation account for it instead of forcing
// a collection through JSC's debug-only synchronous entry point.
JSGarbageCollect(env->context);
napi_value undefined;
napi_get_undefined(env, &undefined);
return undefined;
},
nullptr, &gc);
napi_value global;
napi_get_global(*env, &global);
napi_set_named_property(*env, global, "gc", gc);
#ifdef __ANDROID__
// Report unhandled promise rejections. JSC keeps the callback alive (it is
// stored on and marked by the global object), so no extra protection is
// needed. JSC only surfaces the "unhandled" event, not a later "handled"
// retraction, so the JS tracker treats every call as unhandled.
napi_value rejectionCallback;
napi_create_function(*env, "onUnhandledRejection", NAPI_AUTO_LENGTH,
JscUnhandledRejectionCallback, nullptr,
&rejectionCallback);
JSValueRef rejectionException = nullptr;
JSGlobalContextSetUnhandledRejectionCallback(
(*env)->context, reinterpret_cast<JSObjectRef>(rejectionCallback),
&rejectionException);
#endif
return napi_ok;
}
napi_status js_set_runtime_flags(const char* flags) { return napi_ok; }
napi_status js_lock_env(napi_env env) {
if (env == nullptr) return napi_invalid_arg;
env->js_mutex.lock();
return napi_ok;
}
napi_status js_unlock_env(napi_env env) {
if (env == nullptr) return napi_invalid_arg;
env->js_mutex.unlock();
return napi_ok;
}
napi_status js_free_napi_env(napi_env env) {
if (env == nullptr) return napi_invalid_arg;
#ifndef __ANDROID__
// Defined in the Apple runtime (ThreadSafeFunction.mm); Android has no
// equivalent, same as the quickjs and hermes backends.
js_run_env_cleanup_hooks(env);
#endif
delete env;
return napi_ok;
}
napi_status js_free_runtime(jsr_ns_runtime runtime) {
// JSContextGroupRelease((JSContextGroupRef) runtime);
return napi_ok;
}
#ifdef __ANDROID__
// ---------------------------------------------------------------------------
// Bytecode code cache
//
// JSC has no ahead-of-time bytecode format, so — exactly like the V8 path — we
// cache the engine's own serialized bytecode next to each source file and reuse
// it on later launches. The heavy lifting (serialize / validate /
// run-from-cache) lives in JSC behind the JSBytecodeCache.h C API; here we only
// manage the cache file: where it lives, when it is stale, and publishing it
// atomically.
//
// The .cache file is stamped with its source file's mtime; a mismatch means the
// source changed and the cache is ignored (and JSC re-validates internally
// too).
// ---------------------------------------------------------------------------
// 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();
}
// Publish a freshly written temp cache file: stamp it with the source's mtime
// so js_run_cached_script accepts it, then atomically rename it into place. Any
// failure leaves no cache behind. Best-effort.
static void PublishCacheFile(const std::string& tmpPath,
const std::string& cachePath,
const std::string& fsPath) {
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 JSC bytecode cache: %s", cachePath.c_str());
}
// Serialize `sourceStr` to a bytecode cache published next to `fsPath`, stamped
// with the source's mtime. Writes to a temp file first then renames, so a crash
// or a concurrent reader never sees a half-written cache. Best-effort: any
// failure just leaves no cache behind. Returns true if a cache was published.
static bool WriteCacheForSource(napi_env env, JSStringRef sourceStr,
JSStringRef sourceUrl,
const std::string& fsPath) {
auto cachePath = fsPath + ".cache";
auto tmpPath = cachePath + ".tmp";
JSStringRef errorMessage = nullptr;
bool ok = JSWriteBytecodeCacheForProgram(env->context, sourceStr, sourceUrl,
tmpPath.c_str(), &errorMessage);
if (!ok) {
if (errorMessage) {
size_t maxSize = JSStringGetMaximumUTF8CStringSize(errorMessage);
std::string msg(maxSize, '\0');
JSStringGetUTF8CString(errorMessage, &msg[0], maxSize);
DEBUG_WRITE("[code-cache] failed to generate bytecode for %s: %s",
fsPath.c_str(), msg.c_str());
JSStringRelease(errorMessage);
} else {
DEBUG_WRITE(
"[code-cache] failed to generate bytecode for %s (no error message)",
fsPath.c_str());
}
remove(tmpPath.c_str());
return false;
}
PublishCacheFile(tmpPath, cachePath, fsPath);
return true;
}
#endif // __ANDROID__
napi_status js_execute_script(napi_env env, napi_value script, const char* file,
napi_value* result) {
#ifdef __ANDROID__
// Fast path: run JSC's on-disk bytecode 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: publish a bytecode cache for the next launch, then run. When the
// cache is written we run straight from it (JSC decodes the bytecode instead
// of parsing again), so the source is compiled only once even on this first
// launch; otherwise we fall back to running the source directly.
std::string fsPath;
if (NormalizeScriptPath(file, fsPath)) {
JSValueRef exception = nullptr;
JSStringRef sourceStr = JSValueToStringCopy(
env->context, reinterpret_cast<JSValueRef>(script), &exception);
if (sourceStr != nullptr && exception == nullptr) {
JSStringRef sourceUrl = JSStringCreateWithUTF8CString(file);
DEBUG_WRITE("[code-cache] compiling from source (cold): %s", file);
bool wrote = WriteCacheForSource(env, sourceStr, sourceUrl, fsPath);
JSStringRelease(sourceUrl);
JSStringRelease(sourceStr);
if (wrote) {
napi_status cached =
js_run_cached_script(env, file, script, nullptr, result);
if (cached != napi_cannot_run_js) {
return cached;
}
}
} else if (sourceStr != nullptr) {
JSStringRelease(sourceStr);
}
}
#endif // __ANDROID__
return napi_run_script_source(env, script, file, result);
}
napi_status js_execute_pending_jobs(napi_env env) { return napi_ok; }
napi_status js_get_engine_ptr(napi_env env, int64_t* engine_ptr) {
*engine_ptr = (int64_t)0;
return napi_ok;
}
napi_status js_adjust_external_memory(napi_env env, int64_t changeInBytes,
int64_t* externalMemory) {
return napi_ok;
}
// Compile `source` and publish a bytecode cache next to `file`. Retained for
// the jsr interface; the hot path (js_execute_script) caches inline. No-op for
// synthetic / non-file sources.
napi_status js_cache_script(napi_env env, const char* source,
const char* file) {
#ifdef __ANDROID__
std::string fsPath;
if (!NormalizeScriptPath(file, fsPath)) {
return napi_ok;
}
JSStringRef sourceStr = JSStringCreateWithUTF8CString(source);
JSStringRef sourceUrl = JSStringCreateWithUTF8CString(file);
WriteCacheForSource(env, sourceStr, sourceUrl, fsPath);
JSStringRelease(sourceUrl);
JSStringRelease(sourceStr);
#endif // __ANDROID__
return napi_ok;
}
napi_status js_run_cached_script(napi_env env, const char* file,
napi_value script, void* cache,
napi_value* result) {
if (env == nullptr || script == nullptr) return napi_invalid_arg;
#ifndef __ANDROID__
return napi_cannot_run_js; // no bytecode cache API on Apple's JSC
#else
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;
}
JSValueRef exception = nullptr;
JSStringRef sourceStr = JSValueToStringCopy(
env->context, reinterpret_cast<JSValueRef>(script), &exception);
if (sourceStr == nullptr || exception != nullptr) {
if (sourceStr) JSStringRelease(sourceStr);
return napi_cannot_run_js;
}
JSStringRef sourceUrl = JSStringCreateWithUTF8CString(file);
bool cacheRejected = false;
JSValueRef exc = nullptr;
JSValueRef ret = JSEvaluateProgramWithBytecodeCacheFile(
env->context, sourceStr, sourceUrl, cachePath.c_str(), nullptr,
&cacheRejected, &exc);
JSStringRelease(sourceUrl);
JSStringRelease(sourceStr);
if (cacheRejected) {
// The cache was stale/incompatible; JSC did NOT run anything. Report a
// miss so the caller runs the source and refreshes the cache.
DEBUG_WRITE("[code-cache] miss (JSC rejected cache as incompatible): %s",
fsPath.c_str());
return napi_cannot_run_js;
}
if (exc != nullptr) {
// The script threw while executing. This is a real run — surface the
// exception; the caller must NOT execute the source a second time.
return napi_set_pending_exception(env, exc);
}
DEBUG_WRITE("[code-cache] loaded JSC bytecode cache: %s", fsPath.c_str());
if (result != nullptr) {
*result = reinterpret_cast<napi_value>(const_cast<OpaqueJSValue*>(ret));
}
return napi_ok;
#endif // __ANDROID__
}
napi_status js_run_bytecode_file(napi_env env, const char* file,
napi_value* result) {
// JSC has no compile-time bytecode format (it caches serialized bytecode 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, "JSC", NAPI_AUTO_LENGTH, version);
return napi_ok;
}