Branch data Line data Source code
1 : : /* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
2 : : // SPDX-License-Identifier: MIT OR LGPL-2.0-or-later
3 : : // SPDX-FileCopyrightText: 2013 Giovanni Campagna <scampa.giovanni@gmail.com>
4 : :
5 : : #include <config.h>
6 : :
7 : : #include <stdint.h>
8 : :
9 : : #ifdef _WIN32
10 : : # include <windows.h>
11 : : #endif
12 : :
13 : : #include <utility> // for move
14 : :
15 : : #include <gio/gio.h>
16 : : #include <glib.h>
17 : :
18 : : #include <js/Context.h>
19 : : #include <js/ContextOptions.h>
20 : : #include <js/GCAPI.h> // for JS_SetGCParameter, JS_AddFin...
21 : : #include <js/Initialization.h> // for JS_Init, JS_ShutDown
22 : : #include <js/Principals.h>
23 : : #include <js/Promise.h>
24 : : #include <js/RootingAPI.h>
25 : : #include <js/Stack.h> // for JS_SetNativeStackQuota
26 : : #include <js/StructuredClone.h> // for JS_WriteUint32Pair
27 : : #include <js/TypeDecls.h>
28 : : #include <js/Utility.h> // for UniqueChars
29 : : #include <js/Warnings.h>
30 : : #include <js/experimental/SourceHook.h>
31 : : #include <jsapi.h> // for JS_SetGlobalJitCompilerOption
32 : : #include <jsfriendapi.h> // for SetDOMCallbacks, DOMCallbacks
33 : : #include <mozilla/UniquePtr.h>
34 : :
35 : : #ifndef G_DISABLE_ASSERT
36 : : # include <mozilla/Atomics.h> // for Atomic::operator==
37 : : #endif
38 : :
39 : : #include "gi/gerror.h"
40 : : #include "gjs/context-private.h"
41 : : #include "gjs/engine.h"
42 : : #include "gjs/gerror-result.h"
43 : : #include "gjs/jsapi-util.h"
44 : : #include "gjs/profiler-private.h"
45 : : #include "util/log.h"
46 : :
47 : 2652 : static void gjs_finalize_callback(JS::GCContext*, JSFinalizeStatus status,
48 : : void* data) {
49 : 2652 : auto* gjs = static_cast<GjsContextPrivate*>(data);
50 [ - + ]: 2652 : if (gjs->profiler())
51 : 0 : gjs_profiler_set_finalize_status(gjs->profiler(), status);
52 : 2652 : }
53 : :
54 : 67 : static void on_promise_unhandled_rejection(
55 : : JSContext* cx, bool mutedErrors [[maybe_unused]], JS::HandleObject promise,
56 : : JS::PromiseRejectionHandlingState state, void* data) {
57 : 67 : auto* gjs = static_cast<GjsContextPrivate*>(data);
58 : 67 : uint64_t id = JS::GetPromiseID(promise);
59 : :
60 [ + + ]: 67 : if (state == JS::PromiseRejectionHandlingState::Handled) {
61 : : // This happens when catching an exception from an await expression.
62 : 33 : gjs->unregister_unhandled_promise_rejection(id);
63 : 33 : return;
64 : : }
65 : :
66 : 34 : JS::RootedObject allocation_site(cx, JS::GetPromiseAllocationSite(promise));
67 : 34 : JS::UniqueChars stack = format_saved_frame(cx, allocation_site);
68 : 68 : gjs->register_unhandled_promise_rejection(id, std::move(stack));
69 : 34 : }
70 : :
71 : 14 : static bool gjs_dispatch_wasm_to_event_loop(void* closure, WasmJob&& d) {
72 : 14 : auto* gjs = static_cast<GjsContextPrivate*>(closure);
73 : 28 : return gjs->dispatch_wasm_job(std::move(d));
74 : : }
75 : :
76 : 5 : static void on_cleanup_finalization_registry(JSFunction* cleanup_task,
77 : : JSObject* incumbent_global
78 : : [[maybe_unused]],
79 : : void* data) {
80 : 5 : auto* gjs = static_cast<GjsContextPrivate*>(data);
81 [ - + ]: 5 : if (!gjs->queue_finalization_registry_cleanup(cleanup_task))
82 : 0 : gjs_critical(
83 : : "Out of memory queueing FinalizationRegistry cleanup task");
84 : 5 : }
85 : :
86 : 605 : bool gjs_load_internal_source(JSContext* cx, const char* filename, char** src,
87 : : size_t* length) {
88 : 605 : Gjs::AutoError error;
89 : 605 : const char* path = filename + 11; // len("resource://")
90 : : GBytes* script_bytes =
91 : 605 : g_resources_lookup_data(path, G_RESOURCE_LOOKUP_FLAGS_NONE, &error);
92 [ - + ]: 605 : if (!script_bytes)
93 : 0 : return gjs_throw_gerror_message(cx, error);
94 : :
95 : 605 : *src = static_cast<char*>(g_bytes_unref_to_data(script_bytes, length));
96 : 605 : return true;
97 : 605 : }
98 : :
99 : : class GjsSourceHook : public js::SourceHook {
100 : 0 : bool load(JSContext* cx, const char* filename,
101 : : char16_t** two_byte_source [[maybe_unused]], char** utf8_source,
102 : : size_t* length) override {
103 : : // caller owns the source, per documentation of SourceHook
104 : 0 : return gjs_load_internal_source(cx, filename, utf8_source, length);
105 : : }
106 : : };
107 : :
108 : : #ifdef G_OS_WIN32
109 : : HMODULE gjs_dll;
110 : : static bool gjs_is_inited = false;
111 : :
112 : : BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
113 : : switch (fdwReason) {
114 : : case DLL_PROCESS_ATTACH: {
115 : : gjs_dll = hinstDLL;
116 : : const char* reason = JS_InitWithFailureDiagnostic();
117 : : if (reason)
118 : : gjs_error("Could not initialize JavaScript: {}", reason);
119 : : gjs_is_inited = true;
120 : : } break;
121 : :
122 : : case DLL_THREAD_DETACH:
123 : : JS_ShutDown();
124 : : break;
125 : :
126 : : default: {
127 : : }
128 : : }
129 : :
130 : : return TRUE;
131 : : }
132 : :
133 : : #else
134 : : class GjsInit {
135 : : public:
136 : 132 : GjsInit() {
137 : 132 : const char* reason = JS_InitWithFailureDiagnostic();
138 [ - + ]: 132 : if (reason)
139 : 0 : gjs_error("Could not initialize JavaScript: {}", reason);
140 : 132 : }
141 : :
142 : 132 : ~GjsInit() {
143 : 132 : JS_ShutDown();
144 : 132 : }
145 : :
146 : 285 : explicit operator bool() const { return true; }
147 : : };
148 : :
149 : : static GjsInit gjs_is_inited;
150 : : #endif
151 : :
152 : : // JSPrincipals (basically a weird name for security callbacks) which are in
153 : : // effect in the module loader's realm (GjsInternalGlobal). This prevents module
154 : : // loader stack frames from showing up in public stack traces.
155 : : class ModuleLoaderPrincipals final : public JSPrincipals {
156 : : static constexpr uint32_t STRUCTURED_CLONE_TAG = JS_SCTAG_USER_MIN;
157 : :
158 : 0 : bool write(JSContext* cx [[maybe_unused]],
159 : : JSStructuredCloneWriter* writer) override {
160 : : g_assert_not_reached();
161 : : return JS_WriteUint32Pair(writer, STRUCTURED_CLONE_TAG, 1);
162 : : }
163 : :
164 : 0 : bool isSystemOrAddonPrincipal() override { return true; }
165 : :
166 : : public:
167 : 143870 : static bool subsumes(JSPrincipals* first, JSPrincipals* second) {
168 [ + - + + ]: 143870 : return first == &the_principals || second != &the_principals;
169 : : }
170 : :
171 : 283 : static void destroy(JSPrincipals* principals [[maybe_unused]]) {
172 : 283 : g_assert(principals == &the_principals &&
173 : : "Should not create other instances of ModuleLoaderPrinciples");
174 : 283 : g_assert(principals->refcount == 0 &&
175 : : "Mismatched JS_HoldPrincipals/JS_DropPrincipals");
176 : 283 : }
177 : :
178 : : // Singleton
179 : : static ModuleLoaderPrincipals the_principals;
180 : : };
181 : :
182 : : ModuleLoaderPrincipals ModuleLoaderPrincipals::the_principals{};
183 : :
184 : 285 : JSPrincipals* get_internal_principals() {
185 : 285 : return &ModuleLoaderPrincipals::the_principals;
186 : : }
187 : :
188 : : static const JSSecurityCallbacks security_callbacks = {
189 : : .subsumes = &ModuleLoaderPrincipals::subsumes};
190 : :
191 : 4 : static bool instance_class_is_error(const JSClass* klass) {
192 : 4 : return klass == &ErrorBase::klass;
193 : : }
194 : :
195 : : static const js::DOMCallbacks dom_callbacks = {.instanceClassIsError =
196 : : &instance_class_is_error};
197 : :
198 : 285 : JSContext* gjs_create_js_context(GjsContextPrivate* uninitialized_gjs) {
199 : 285 : g_assert(gjs_is_inited);
200 : 285 : JSContext* cx = JS_NewContext(/* max bytes = */ 32 * 1024 * 1024);
201 [ - + ]: 285 : if (!cx)
202 : 0 : return nullptr;
203 : :
204 [ - + ]: 285 : if (!JS::InitSelfHostedCode(cx)) {
205 : 0 : JS_DestroyContext(cx);
206 : 0 : return nullptr;
207 : : }
208 : :
209 : : // For additional context on these options, see
210 : : // https://searchfox.org/mozilla-esr91/rev/c49725508e97c1e2e2bb3bf9ed0ba14b2016abac/js/public/GCAPI.h#53
211 : 285 : JS_SetNativeStackQuota(cx, 1024UL * 1024UL);
212 : 285 : JS_SetGCParameter(cx, JSGC_MAX_BYTES, -1);
213 : 285 : JS_SetGCParameter(cx, JSGC_INCREMENTAL_GC_ENABLED, 1);
214 : 285 : JS_SetGCParameter(cx, JSGC_SLICE_TIME_BUDGET_MS, 10);
215 : :
216 : : // set ourselves as the private data
217 : 285 : JS_SetContextPrivate(cx, uninitialized_gjs);
218 : :
219 : 285 : JS_SetSecurityCallbacks(cx, &security_callbacks);
220 : 285 : JS_InitDestroyPrincipalsCallback(cx, &ModuleLoaderPrincipals::destroy);
221 : 285 : JS_AddFinalizeCallback(cx, gjs_finalize_callback, uninitialized_gjs);
222 : 285 : JS::SetWarningReporter(cx, gjs_warning_reporter);
223 : 285 : JS::SetJobQueue(cx, dynamic_cast<JS::JobQueue*>(uninitialized_gjs));
224 : : // Second callback is not used unless Atomics enabled
225 : 285 : JS::InitDispatchsToEventLoop(cx, gjs_dispatch_wasm_to_event_loop, nullptr,
226 : : uninitialized_gjs);
227 : 285 : JS::SetPromiseRejectionTrackerCallback(cx, on_promise_unhandled_rejection,
228 : : uninitialized_gjs);
229 : 285 : JS::SetHostCleanupFinalizationRegistryCallback(
230 : : cx, on_cleanup_finalization_registry, uninitialized_gjs);
231 : 285 : js::SetDOMCallbacks(cx, &dom_callbacks);
232 : :
233 : : // We use this to handle "lazy sources" that SpiderMonkey doesn't need to
234 : : // keep in memory. Most sources should be kept in memory, but we can skip
235 : : // doing that for the realm bootstrap code, as it is already in memory in
236 : : // the form of a GResource. Instead we use the "source hook" to retrieve it.
237 : 285 : auto hook = mozilla::MakeUnique<GjsSourceHook>();
238 : 285 : js::SetSourceHook(cx, std::move(hook));
239 : :
240 [ - + ]: 285 : if (g_getenv("GJS_DISABLE_EXTRA_WARNINGS")) {
241 : 0 : gjs_warning(
242 : : "GJS_DISABLE_EXTRA_WARNINGS has been removed, GJS no longer logs "
243 : : "extra warnings");
244 : : }
245 : :
246 : 285 : bool enable_jit = !(g_getenv("GJS_DISABLE_JIT"));
247 [ + - ]: 285 : if (enable_jit) {
248 : 285 : gjs_debug(GJS_DEBUG_CONTEXT, "Enabling JIT");
249 : : }
250 : 285 : JS::ContextOptionsRef(cx).setAsmJS(enable_jit);
251 : :
252 [ + - ]: 285 : uint32_t value = enable_jit ? 1 : 0;
253 : :
254 : 285 : JS_SetGlobalJitCompilerOption(
255 : : cx, JSJitCompilerOption::JSJITCOMPILER_ION_ENABLE, value);
256 : 285 : JS_SetGlobalJitCompilerOption(
257 : : cx, JSJitCompilerOption::JSJITCOMPILER_BASELINE_ENABLE, value);
258 : 285 : JS_SetGlobalJitCompilerOption(
259 : : cx, JSJitCompilerOption::JSJITCOMPILER_BASELINE_INTERPRETER_ENABLE,
260 : : value);
261 : :
262 : 285 : return cx;
263 : 285 : }
|