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: 2008 litl, LLC
4 : :
5 : : #include <config.h>
6 : :
7 : : #include <inttypes.h> // for PRIu64
8 : : #include <signal.h> // for sigaction, SIGUSR1, sa_handler
9 : : #include <stdint.h>
10 : : #include <stdio.h> // for FILE, fclose, size_t
11 : : #include <stdlib.h> // for exit
12 : : #include <string.h> // for memset
13 : :
14 : : #ifdef HAVE_UNISTD_H
15 : : # include <unistd.h> // for getpid
16 : : #endif
17 : :
18 : : #ifdef G_OS_WIN32
19 : : # include <process.h>
20 : : # include <windows.h>
21 : : #endif
22 : :
23 : : #ifdef HAVE_READLINE_READLINE_H
24 : : # include <readline/history.h>
25 : : #endif
26 : :
27 : : #include <new>
28 : : #include <string> // for u16string
29 : : #include <thread> // for get_id
30 : : #include <unordered_map>
31 : : #include <unordered_set>
32 : : #include <utility> // for move
33 : : #include <vector>
34 : :
35 : : #include <gio/gio.h>
36 : : #include <glib-object.h>
37 : : #include <glib.h>
38 : :
39 : : #include <js/CallAndConstruct.h> // for Call, JS_CallFunctionValue
40 : : #include <js/CallArgs.h> // for UndefinedHandleValue
41 : : #include <js/CharacterEncoding.h>
42 : : #include <js/CompilationAndEvaluation.h>
43 : : #include <js/CompileOptions.h>
44 : : #include <js/Context.h>
45 : : #include <js/EnvironmentChain.h>
46 : : #include <js/ErrorReport.h>
47 : : #include <js/Exception.h> // for StealPendingExceptionStack
48 : : #include <js/GCAPI.h> // for JS_GC, JS_AddExtraGCRootsTr...
49 : : #include <js/GCHashTable.h> // for WeakCache
50 : : #include <js/GlobalObject.h> // for CurrentGlobalOrNull
51 : : #include <js/HeapAPI.h> // for ExposeObjectToActiveJS
52 : : #include <js/Id.h>
53 : : #include <js/Modules.h>
54 : : #include <js/Promise.h> // for JobQueue::SavedJobQueue
55 : : #include <js/PropertyAndElement.h>
56 : : #include <js/PropertyDescriptor.h> // for JSPROP_PERMANENT, JSPROP_RE...
57 : : #include <js/Realm.h>
58 : : #include <js/RootingAPI.h>
59 : : #include <js/ScriptPrivate.h>
60 : : #include <js/SourceText.h>
61 : : #include <js/String.h> // for JS_NewStringCopyZ
62 : : #include <js/TracingAPI.h>
63 : : #include <js/TypeDecls.h>
64 : : #include <js/UniquePtr.h>
65 : : #include <js/Utility.h> // for DeletePolicy via WeakCache
66 : : #include <js/Value.h>
67 : : #include <js/ValueArray.h>
68 : : #include <js/friend/DumpFunctions.h>
69 : : #include <jsapi.h> // for JS_GetFunctionObject, JS_Ge...
70 : : #include <jsfriendapi.h> // for ScriptEnvironmentPreparer
71 : : #include <mozilla/Result.h>
72 : : #include <mozilla/UniquePtr.h> // for UniquePtr::get
73 : :
74 : : #include "gi/function.h"
75 : : #include "gi/info.h"
76 : : #include "gi/object.h"
77 : : #include "gi/private.h"
78 : : #include "gi/repo.h"
79 : : #include "gjs/atoms.h"
80 : : #include "gjs/auto.h"
81 : : #include "gjs/byteArray.h"
82 : : #include "gjs/context-private.h" // IWYU pragma: associated
83 : : #include "gjs/context.h"
84 : : #include "gjs/engine.h"
85 : : #include "gjs/error-types.h"
86 : : #include "gjs/gerror-result.h"
87 : : #include "gjs/global.h"
88 : : #include "gjs/importer.h"
89 : : #include "gjs/internal.h"
90 : : #include "gjs/jsapi-util.h"
91 : : #include "gjs/mainloop.h"
92 : : #include "gjs/mem.h"
93 : : #include "gjs/module.h"
94 : : #include "gjs/native.h"
95 : : #include "gjs/objectbox.h"
96 : : #include "gjs/profiler-private.h"
97 : : #include "gjs/profiler.h"
98 : : #include "gjs/promise.h"
99 : : #include "gjs/text-encoding.h"
100 : : #include "modules/cairo-module.h"
101 : : #include "modules/console.h"
102 : : #include "modules/print.h"
103 : : #include "modules/system.h"
104 : : #include "util/log.h"
105 : :
106 : : namespace mozilla {
107 : : union Utf8Unit;
108 : : }
109 : :
110 : : using Gjs::GErrorResult;
111 : : using mozilla::Err, mozilla::Ok;
112 : :
113 : : static void gjs_context_dispose(GObject*);
114 : : static void gjs_context_finalize(GObject*);
115 : : static void gjs_context_constructed(GObject*);
116 : : static void gjs_context_get_property(GObject*, unsigned prop_id, GValue*,
117 : : GParamSpec*);
118 : : static void gjs_context_set_property(GObject*, unsigned prop_id, const GValue*,
119 : : GParamSpec*);
120 : :
121 : 0 : void GjsContextPrivate::EnvironmentPreparer::invoke(JS::HandleObject scope,
122 : : Closure& closure) {
123 : 0 : g_assert(!JS_IsExceptionPending(m_cx));
124 : :
125 : 0 : JSAutoRealm ar(m_cx, scope);
126 [ # # ]: 0 : if (!closure(m_cx))
127 : 0 : gjs_log_exception(m_cx);
128 : 0 : }
129 : :
130 : : struct _GjsContext {
131 : : GObject parent;
132 : : };
133 : :
134 [ + + + - : 26741 : G_DEFINE_TYPE_WITH_PRIVATE(GjsContext, gjs_context, G_TYPE_OBJECT);
+ + ]
135 : :
136 : 2546 : GjsContextPrivate* GjsContextPrivate::from_object(GObject* js_context) {
137 : 2546 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), nullptr);
138 : : return static_cast<GjsContextPrivate*>(
139 : 2546 : gjs_context_get_instance_private(GJS_CONTEXT(js_context)));
140 : : }
141 : :
142 : 7942 : GjsContextPrivate* GjsContextPrivate::from_object(GjsContext* js_context) {
143 : 7942 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), nullptr);
144 : : return static_cast<GjsContextPrivate*>(
145 : 7942 : gjs_context_get_instance_private(js_context));
146 : : }
147 : :
148 : 5335 : GjsContextPrivate* GjsContextPrivate::from_current_context() {
149 : 5335 : return from_object(gjs_context_get_current());
150 : : }
151 : :
152 : : enum {
153 : : PROP_CONTEXT_0,
154 : : PROP_PROGRAM_PATH,
155 : : PROP_SEARCH_PATH,
156 : : PROP_PROGRAM_NAME,
157 : : PROP_PROFILER_ENABLED,
158 : : PROP_PROFILER_SIGUSR2,
159 : : PROP_EXEC_AS_MODULE,
160 : : PROP_REPL_HISTORY_PATH
161 : : };
162 : :
163 : : static GMutex contexts_lock;
164 : : static GList* all_contexts = nullptr;
165 : :
166 : : static Gjs::AutoChar dump_heap_output;
167 : : static unsigned dump_heap_idle_id = 0;
168 : :
169 : : #ifdef G_OS_UNIX
170 : : // Currently heap dumping via SIGUSR1 is only supported on UNIX platforms!
171 : : // This can reduce performance. See note in system.cpp on System.dumpHeap().
172 : 0 : static void gjs_context_dump_heaps() {
173 : : static unsigned counter = 0;
174 : :
175 : 0 : gjs_memory_report("signal handler", false);
176 : :
177 : : // dump to sequential files to allow easier comparisons
178 : : Gjs::AutoChar filename{g_strdup_printf("%s.%jd.%u", dump_heap_output.get(),
179 : 0 : intmax_t(getpid()), counter)};
180 : 0 : ++counter;
181 : :
182 : 0 : FILE *fp = fopen(filename, "w");
183 [ # # ]: 0 : if (!fp)
184 : 0 : return;
185 : :
186 [ # # # # ]: 0 : for (GList *l = all_contexts; l; l = g_list_next(l)) {
187 : 0 : auto* gjs = static_cast<GjsContextPrivate*>(l->data);
188 : 0 : js::DumpHeap(gjs->context(), fp, js::CollectNurseryBeforeDump);
189 : : }
190 : :
191 : 0 : fclose(fp);
192 [ # # ]: 0 : }
193 : :
194 : 0 : static gboolean dump_heap_idle(void*) {
195 : 0 : dump_heap_idle_id = 0;
196 : :
197 : 0 : gjs_context_dump_heaps();
198 : :
199 : 0 : return false;
200 : : }
201 : :
202 : 0 : static void dump_heap_signal_handler(int signum [[maybe_unused]]) {
203 [ # # ]: 0 : if (dump_heap_idle_id == 0)
204 : 0 : dump_heap_idle_id = g_idle_add_full(G_PRIORITY_HIGH_IDLE,
205 : : dump_heap_idle, nullptr, nullptr);
206 : 0 : }
207 : : #endif
208 : :
209 : 255 : static void setup_dump_heap() {
210 : : static bool dump_heap_initialized = false;
211 [ + + ]: 255 : if (!dump_heap_initialized) {
212 : 114 : dump_heap_initialized = true;
213 : :
214 : : // install signal handler only if environment variable is set
215 : 114 : const char *heap_output = g_getenv("GJS_DEBUG_HEAP_OUTPUT");
216 [ - + ]: 114 : if (heap_output) {
217 : : #ifdef G_OS_UNIX
218 : : struct sigaction sa;
219 : :
220 : 0 : dump_heap_output = g_strdup(heap_output);
221 : :
222 : 0 : memset(&sa, 0, sizeof(sa));
223 : 0 : sa.sa_handler = dump_heap_signal_handler;
224 : 0 : sigaction(SIGUSR1, &sa, nullptr);
225 : : #else
226 : : g_message(
227 : : "heap dump is currently only supported on UNIX platforms");
228 : : #endif
229 : : }
230 : : }
231 : 255 : }
232 : :
233 : : static void
234 : 255 : gjs_context_init(GjsContext *js_context)
235 : : {
236 : 255 : gjs_log_init();
237 : 255 : gjs_context_make_current(js_context);
238 : 255 : }
239 : :
240 : : static void
241 : 114 : gjs_context_class_init(GjsContextClass *klass)
242 : : {
243 : 114 : GObjectClass *object_class = G_OBJECT_CLASS (klass);
244 : : GParamSpec *pspec;
245 : :
246 : 114 : gjs_log_init();
247 : :
248 : 114 : object_class->dispose = gjs_context_dispose;
249 : 114 : object_class->finalize = gjs_context_finalize;
250 : :
251 : 114 : object_class->constructed = gjs_context_constructed;
252 : 114 : object_class->get_property = gjs_context_get_property;
253 : 114 : object_class->set_property = gjs_context_set_property;
254 : :
255 : 114 : pspec = g_param_spec_boxed("search-path",
256 : : "Search path",
257 : : "Path where modules to import should reside",
258 : : G_TYPE_STRV,
259 : : (GParamFlags) (G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
260 : :
261 : 114 : g_object_class_install_property(object_class,
262 : : PROP_SEARCH_PATH,
263 : : pspec);
264 : 114 : g_param_spec_unref(pspec);
265 : :
266 : 114 : pspec = g_param_spec_string("program-name",
267 : : "Program Name",
268 : : "The filename of the launched JS program",
269 : : "",
270 : : (GParamFlags) (G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
271 : :
272 : 114 : g_object_class_install_property(object_class,
273 : : PROP_PROGRAM_NAME,
274 : : pspec);
275 : 114 : g_param_spec_unref(pspec);
276 : :
277 : 114 : pspec = g_param_spec_string(
278 : : "program-path", "Executed File Path",
279 : : "The full path of the launched file or NULL if GJS was launched from "
280 : : "the C API or interactive console.",
281 : : nullptr, (GParamFlags)(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY));
282 : :
283 : 114 : g_object_class_install_property(object_class, PROP_PROGRAM_PATH, pspec);
284 : 114 : g_param_spec_unref(pspec);
285 : :
286 : : /**
287 : : * GjsContext:profiler-enabled:
288 : : *
289 : : * Set this property to profile any JS code run by this context. By
290 : : * default, the profiler is started and stopped when you call
291 : : * gjs_context_eval().
292 : : *
293 : : * The value of this property is superseded by the GJS_ENABLE_PROFILER
294 : : * environment variable.
295 : : *
296 : : * You may only have one context with the profiler enabled at a time.
297 : : */
298 : 114 : pspec = g_param_spec_boolean("profiler-enabled", "Profiler enabled",
299 : : "Whether to profile JS code run by this context",
300 : : FALSE,
301 : : GParamFlags(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
302 : 114 : g_object_class_install_property(object_class, PROP_PROFILER_ENABLED, pspec);
303 : 114 : g_param_spec_unref(pspec);
304 : :
305 : : /**
306 : : * GjsContext:profiler-sigusr2:
307 : : *
308 : : * Set this property to install a SIGUSR2 signal handler that starts and
309 : : * stops the profiler. This property also implies that
310 : : * #GjsContext:profiler-enabled is set.
311 : : */
312 : 114 : pspec = g_param_spec_boolean("profiler-sigusr2", "Profiler SIGUSR2",
313 : : "Whether to activate the profiler on SIGUSR2",
314 : : FALSE,
315 : : GParamFlags(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
316 : 114 : g_object_class_install_property(object_class, PROP_PROFILER_SIGUSR2, pspec);
317 : 114 : g_param_spec_unref(pspec);
318 : :
319 : 114 : pspec = g_param_spec_boolean(
320 : : "exec-as-module", "Execute as module",
321 : : "Whether to execute the file as a module", FALSE,
322 : : GParamFlags(G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY));
323 : 114 : g_object_class_install_property(object_class, PROP_EXEC_AS_MODULE, pspec);
324 : 114 : g_param_spec_unref(pspec);
325 : :
326 : : /**
327 : : * GjsContext:repl-history-path:
328 : : *
329 : : * Set this property to persist repl command history in the console or
330 : : * debugger. If NULL, then command history will not be persisted.
331 : : */
332 : 114 : pspec = g_param_spec_string(
333 : : "repl-history-path", "REPL History Path",
334 : : "The writable path to persist repl history", nullptr,
335 : : (GParamFlags)(G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
336 : : G_PARAM_STATIC_STRINGS));
337 : 114 : g_object_class_install_property(object_class, PROP_REPL_HISTORY_PATH,
338 : : pspec);
339 : 114 : g_param_spec_unref(pspec);
340 : :
341 : : // For GjsPrivate
342 [ - + ]: 114 : if (!g_getenv("GJS_USE_UNINSTALLED_FILES")) {
343 : : #ifdef G_OS_WIN32
344 : : extern HMODULE gjs_dll;
345 : : Gjs::AutoChar basedir{
346 : : g_win32_get_package_installation_directory_of_module(gjs_dll)};
347 : : Gjs::AutoChar priv_typelib_dir{g_build_filename(
348 : : basedir, "lib", "gjs", "girepository-1.0", nullptr)};
349 : : #else
350 : : Gjs::AutoChar priv_typelib_dir{
351 : 0 : g_build_filename(PKGLIBDIR, "girepository-1.0", nullptr)};
352 : : #endif
353 : 0 : GI::Repository repo;
354 : 0 : repo.prepend_search_path(priv_typelib_dir);
355 : 0 : }
356 : 114 : auto& registry = Gjs::NativeModuleDefineFuncs::get();
357 : 114 : registry.add("_promiseNative", gjs_define_native_promise_stuff);
358 : 114 : registry.add("_byteArrayNative", gjs_define_byte_array_stuff);
359 : 114 : registry.add("_encodingNative", gjs_define_text_encoding_stuff);
360 : 114 : registry.add("_gi", gjs_define_private_gi_stuff);
361 : 114 : registry.add("gi", gjs_define_repo);
362 : 114 : registry.add("cairoNative", gjs_js_define_cairo_stuff);
363 : 114 : registry.add("system", gjs_js_define_system_stuff);
364 : 114 : registry.add("console", gjs_define_console_stuff);
365 : 114 : registry.add("_print", gjs_define_print_stuff);
366 : 114 : }
367 : :
368 : 340 : void GjsContextPrivate::trace(JSTracer* trc, void* data) {
369 : 340 : auto* gjs = static_cast<GjsContextPrivate*>(data);
370 : 340 : JS::TraceEdge<JSObject*>(trc, &gjs->m_global, "GJS global object");
371 : 340 : JS::TraceEdge<JSObject*>(trc, &gjs->m_internal_global,
372 : : "GJS internal global object");
373 : 340 : JS::TraceEdge<JSObject*>(trc, &gjs->m_main_loop_hook, "GJS main loop hook");
374 : 340 : gjs->m_atoms->trace(trc);
375 : 340 : gjs->m_job_queue.trace(trc);
376 : 340 : gjs->m_cleanup_tasks.trace(trc);
377 : 340 : gjs->m_object_init_list.trace(trc);
378 : 340 : }
379 : :
380 : 10572 : void GjsContextPrivate::warn_about_unhandled_promise_rejections() {
381 [ + + ]: 10573 : for (auto& kv : m_unhandled_rejection_stacks) {
382 : 1 : const char* stack = kv.second.get();
383 [ + - + - ]: 1 : g_warning("Unhandled promise rejection. To suppress this warning, add "
384 : : "an error handler to your promise chain with .catch() or a "
385 : : "try-catch block around your await expression. %s%s",
386 : : stack ? "Stack trace of the failed promise:\n" :
387 : : "Unfortunately there is no stack trace of the failed promise.",
388 : : stack ? stack : "");
389 : : }
390 : 10572 : m_unhandled_rejection_stacks.clear();
391 : 10572 : }
392 : :
393 : : static void
394 : 253 : gjs_context_dispose(GObject *object)
395 : : {
396 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "JS shutdown sequence");
397 : :
398 : 253 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(object);
399 : :
400 : 253 : g_assert(gjs->is_owner_thread() &&
401 : : "Gjs Context disposed from another thread");
402 : :
403 : : // Profiler must be stopped and freed before context is shut down
404 : 253 : gjs->free_profiler();
405 : :
406 : : /* Stop accepting entries in the toggle queue before running dispose
407 : : * notifications, which causes all GjsMaybeOwned instances to unroot.
408 : : * We don't want any objects to toggle down after that. */
409 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Shutting down toggle queue");
410 : 253 : gjs_object_clear_toggles();
411 : 253 : gjs_object_shutdown_toggle_queue();
412 : :
413 [ + - ]: 253 : if (gjs->context())
414 : 253 : ObjectInstance::context_dispose_notify(nullptr, object);
415 : :
416 : 253 : gjs_debug(GJS_DEBUG_CONTEXT,
417 : : "Notifying external reference holders of GjsContext dispose");
418 : 253 : G_OBJECT_CLASS(gjs_context_parent_class)->dispose(object);
419 : :
420 : 253 : gjs->dispose();
421 : 253 : }
422 : :
423 : 253 : void GjsContextPrivate::free_profiler() {
424 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Stopping profiler");
425 [ + + ]: 253 : if (m_profiler)
426 [ + - ]: 5 : g_clear_pointer(&m_profiler, _gjs_profiler_free);
427 : 253 : }
428 : :
429 : 14313 : void GjsContextPrivate::register_notifier(DestroyNotify notify_func,
430 : : void* data) {
431 : 14313 : m_destroy_notifications.insert({notify_func, data});
432 : 14313 : }
433 : :
434 : 14107 : void GjsContextPrivate::unregister_notifier(DestroyNotify notify_func,
435 : : void* data) {
436 : 14107 : auto target = std::make_pair(notify_func, data);
437 : 14107 : m_destroy_notifications.erase(target);
438 : 14107 : }
439 : :
440 : 253 : void GjsContextPrivate::dispose() {
441 [ + - ]: 253 : if (m_cx) {
442 : 253 : stop_draining_job_queue();
443 : :
444 : 253 : gjs_debug(GJS_DEBUG_CONTEXT,
445 : : "Notifying reference holders of GjsContext dispose");
446 : :
447 [ + + ]: 456 : for (auto const& destroy_notify : m_destroy_notifications)
448 : 203 : destroy_notify.first(m_cx, destroy_notify.second);
449 : :
450 : 253 : gjs_debug(GJS_DEBUG_CONTEXT,
451 : : "Checking unhandled promise rejections");
452 : 253 : warn_about_unhandled_promise_rejections();
453 : :
454 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Releasing cached JS wrappers");
455 : 253 : m_fundamental_table->clear();
456 : 253 : m_gtype_table->clear();
457 : :
458 : : /* Do a full GC here before tearing down, since once we do
459 : : * that we may not have the JS::GetReservedSlot(, 0) to access the
460 : : * context
461 : : */
462 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Final triggered GC");
463 : 253 : JS_GC(m_cx, Gjs::GCReason::GJS_CONTEXT_DISPOSE);
464 : :
465 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Destroying JS context");
466 : 253 : m_destroying.store(true);
467 : :
468 : : /* Now, release all native objects, to avoid recursion between
469 : : * the JS teardown and the C teardown. The JSObject proxies
470 : : * still exist, but point to null.
471 : : */
472 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Releasing all native objects");
473 : 253 : ObjectInstance::prepare_shutdown();
474 : 253 : GjsCallbackTrampoline::prepare_shutdown();
475 : :
476 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Disabling auto GC");
477 [ + + ]: 253 : if (m_auto_gc_id > 0) {
478 : 142 : g_source_remove(m_auto_gc_id);
479 : 142 : m_auto_gc_id = 0;
480 : : }
481 : :
482 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Ending trace on global object");
483 : 253 : JS_RemoveExtraGCRootsTracer(m_cx, &GjsContextPrivate::trace, this);
484 : 253 : m_global = nullptr;
485 : 253 : m_internal_global = nullptr;
486 : 253 : m_main_loop_hook = nullptr;
487 : :
488 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "Freeing allocated resources");
489 [ + - ]: 253 : delete m_fundamental_table;
490 [ + - ]: 253 : delete m_gtype_table;
491 [ + - ]: 253 : delete m_atoms;
492 : :
493 : 253 : m_job_queue.clear();
494 : 253 : m_object_init_list.clear();
495 : :
496 : : // Tear down JS
497 : 253 : JS_DestroyContext(m_cx);
498 : 253 : m_cx = nullptr;
499 : : // don't use g_clear_pointer() as we want the pointer intact while we
500 : : // destroy the context in case we dump stack
501 : 253 : gjs_debug(GJS_DEBUG_CONTEXT, "JS context destroyed");
502 : : }
503 : 253 : }
504 : :
505 : 253 : GjsContextPrivate::~GjsContextPrivate() {
506 [ + + ]: 253 : g_clear_pointer(&m_search_path, g_strfreev);
507 [ + + ]: 253 : g_clear_pointer(&m_program_path, g_free);
508 [ + - ]: 253 : g_clear_pointer(&m_program_name, g_free);
509 [ + + ]: 253 : g_clear_pointer(&m_repl_history_path, g_free);
510 : 253 : }
511 : :
512 : : static void
513 : 253 : gjs_context_finalize(GObject *object)
514 : : {
515 [ + - ]: 253 : if (gjs_context_get_current() == (GjsContext*)object)
516 : 253 : gjs_context_make_current(nullptr);
517 : :
518 : 253 : g_mutex_lock(&contexts_lock);
519 : 253 : all_contexts = g_list_remove(all_contexts, object);
520 : 253 : g_mutex_unlock(&contexts_lock);
521 : :
522 : 253 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(object);
523 : 253 : gjs->~GjsContextPrivate();
524 : 253 : G_OBJECT_CLASS(gjs_context_parent_class)->finalize(object);
525 : :
526 : 253 : g_mutex_lock(&contexts_lock);
527 [ + - ]: 253 : if (!all_contexts)
528 : 253 : gjs_log_cleanup();
529 : 253 : g_mutex_unlock(&contexts_lock);
530 : 253 : }
531 : :
532 : : static void
533 : 255 : gjs_context_constructed(GObject *object)
534 : : {
535 : 255 : GjsContext *js_context = GJS_CONTEXT(object);
536 : :
537 : 255 : G_OBJECT_CLASS(gjs_context_parent_class)->constructed(object);
538 : :
539 : 255 : GjsContextPrivate* gjs_location = GjsContextPrivate::from_object(object);
540 : 255 : JSContext* cx = gjs_create_js_context(gjs_location);
541 [ - + ]: 255 : if (!cx)
542 : 0 : g_error("Failed to create javascript context");
543 : :
544 : 255 : new (gjs_location) GjsContextPrivate(cx, js_context);
545 : :
546 : 255 : g_mutex_lock(&contexts_lock);
547 : 255 : all_contexts = g_list_prepend(all_contexts, object);
548 : 255 : g_mutex_unlock(&contexts_lock);
549 : :
550 : 255 : setup_dump_heap();
551 : :
552 : : #ifdef HAVE_READLINE_READLINE_H
553 : 255 : const char* path = gjs_context_get_repl_history_path(js_context);
554 : : // Populate command history from persisted file
555 [ + + ]: 255 : if (path) {
556 : 63 : int err = read_history(path);
557 [ + + - + : 63 : if (err != 0 && g_getenv("GJS_REPL_HISTORY"))
- + ]
558 : 0 : g_warning("Could not read REPL history file %s: %s", path,
559 : : g_strerror(err));
560 : : }
561 : : #endif
562 : 255 : }
563 : :
564 : 3 : static bool on_context_module_rejected_log_exception(JSContext* cx,
565 : : unsigned argc,
566 : : JS::Value* vp) {
567 : 3 : JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
568 : :
569 : 3 : gjs_debug(GJS_DEBUG_IMPORTER, "Module evaluation promise rejected: %s",
570 : 6 : gjs_debug_callable(&args.callee()).c_str());
571 : :
572 : 3 : JS::HandleValue error = args.get(0);
573 : :
574 : 3 : GjsContextPrivate* gjs_cx = GjsContextPrivate::from_cx(cx);
575 : 3 : gjs_cx->report_unhandled_exception();
576 : :
577 : 3 : gjs_log_exception_full(cx, error, nullptr, G_LOG_LEVEL_CRITICAL);
578 : :
579 : 3 : gjs_cx->main_loop_release();
580 : :
581 : 3 : args.rval().setUndefined();
582 : 3 : return true;
583 : : }
584 : :
585 : 649 : static bool on_context_module_resolved(JSContext* cx, unsigned argc,
586 : : JS::Value* vp) {
587 : 649 : JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
588 : :
589 : 649 : gjs_debug(GJS_DEBUG_IMPORTER, "Module evaluation promise resolved: %s",
590 : 1298 : gjs_debug_callable(&args.callee()).c_str());
591 : :
592 : 649 : args.rval().setUndefined();
593 : :
594 : 649 : GjsContextPrivate::from_cx(cx)->main_loop_release();
595 : :
596 : 649 : return true;
597 : : }
598 : :
599 : 658 : static bool add_promise_reactions(JSContext* cx, JS::HandleValue promise,
600 : : JSNative resolve, JSNative reject,
601 : : const std::string& debug_tag) {
602 : 658 : g_assert(promise.isObject() && "got weird value from JS::ModuleEvaluate");
603 : 658 : JS::RootedObject promise_object(cx, &promise.toObject());
604 : :
605 : 658 : std::string resolved_tag = debug_tag + " async resolved";
606 : 658 : std::string rejected_tag = debug_tag + " async rejected";
607 : :
608 : : JS::RootedFunction on_rejected(
609 : : cx,
610 : 658 : js::NewFunctionWithReserved(cx, reject, 1, 0, rejected_tag.c_str()));
611 [ - + ]: 658 : if (!on_rejected)
612 : 0 : return false;
613 : : JS::RootedFunction on_resolved(
614 : : cx,
615 : 658 : js::NewFunctionWithReserved(cx, resolve, 1, 0, resolved_tag.c_str()));
616 [ - + ]: 658 : if (!on_resolved)
617 : 0 : return false;
618 : :
619 : 658 : JS::RootedObject resolved(cx, JS_GetFunctionObject(on_resolved));
620 : 658 : JS::RootedObject rejected(cx, JS_GetFunctionObject(on_rejected));
621 : :
622 : 658 : return JS::AddPromiseReactions(cx, promise_object, resolved, rejected);
623 : 658 : }
624 : :
625 : 510 : static void load_context_module(JSContext* cx, const char* uri,
626 : : const char* debug_identifier) {
627 : 510 : JS::RootedObject loader(cx, gjs_module_load(cx, uri, uri));
628 : :
629 [ - + ]: 510 : if (!loader) {
630 : 0 : gjs_log_exception(cx);
631 : 0 : g_error("Failed to load %s module.", debug_identifier);
632 : : }
633 : :
634 [ - + ]: 510 : if (!JS::ModuleLink(cx, loader)) {
635 : 0 : gjs_log_exception(cx);
636 : 0 : g_error("Failed to instantiate %s module.", debug_identifier);
637 : : }
638 : :
639 : 510 : JS::RootedValue evaluation_promise(cx);
640 [ - + ]: 510 : if (!JS::ModuleEvaluate(cx, loader, &evaluation_promise)) {
641 : 0 : gjs_log_exception(cx);
642 : 0 : g_error("Failed to evaluate %s module.", debug_identifier);
643 : : }
644 : :
645 : 510 : GjsContextPrivate::from_cx(cx)->main_loop_hold();
646 : 1020 : bool ok = add_promise_reactions(
647 : 510 : cx, evaluation_promise, on_context_module_resolved,
648 : 510 : [](JSContext* cx, unsigned argc, JS::Value* vp) {
649 : 0 : JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
650 : :
651 : 0 : gjs_debug(GJS_DEBUG_IMPORTER,
652 : : "Module evaluation promise rejected: %s",
653 : 0 : gjs_debug_callable(&args.callee()).c_str());
654 : :
655 : 0 : JS::HandleValue error = args.get(0);
656 : : // Abort because this module is required.
657 : 0 : gjs_log_exception_full(cx, error, nullptr, G_LOG_LEVEL_ERROR);
658 : :
659 : 0 : GjsContextPrivate::from_cx(cx)->main_loop_release();
660 : 0 : return false;
661 : : },
662 : 1020 : debug_identifier);
663 : :
664 [ - + ]: 510 : if (!ok) {
665 : 0 : gjs_log_exception(cx);
666 : 0 : g_error("Failed to load %s module.", debug_identifier);
667 : : }
668 : 510 : }
669 : :
670 : 255 : GjsContextPrivate::GjsContextPrivate(JSContext* cx, GjsContext* public_context)
671 : 255 : : m_public_context(public_context),
672 : 255 : m_cx(cx),
673 : 255 : m_owner_thread(std::this_thread::get_id()),
674 : 255 : m_dispatcher(this),
675 : 255 : m_memory_monitor(g_memory_monitor_dup_default()),
676 : 1020 : m_environment_preparer(cx) {
677 : 255 : JS_SetGCCallback(
678 : : cx,
679 : 1281 : [](JSContext*, JSGCStatus status, JS::GCReason reason, void* data) {
680 : 1026 : static_cast<GjsContextPrivate*>(data)->on_garbage_collection(
681 : : status, reason);
682 : 1026 : },
683 : : this);
684 : :
685 : 255 : const char *env_profiler = g_getenv("GJS_ENABLE_PROFILER");
686 [ + + - + ]: 255 : if (env_profiler || m_should_listen_sigusr2)
687 : 1 : m_should_profile = true;
688 : :
689 [ + + ]: 255 : if (m_should_profile) {
690 : 5 : m_profiler = _gjs_profiler_new(public_context);
691 : :
692 [ - + ]: 5 : if (!m_profiler) {
693 : 0 : m_should_profile = false;
694 : : } else {
695 [ - + ]: 5 : if (m_should_listen_sigusr2)
696 : 0 : _gjs_profiler_setup_signals(m_profiler, public_context);
697 : : }
698 : : }
699 : :
700 : 255 : JSRuntime* rt = JS_GetRuntime(m_cx);
701 : 255 : m_fundamental_table = new JS::WeakCache<FundamentalTable>(rt);
702 : 255 : m_gtype_table = new JS::WeakCache<GTypeTable>(rt);
703 : :
704 : 255 : m_atoms = new GjsAtoms();
705 : :
706 [ - + ]: 255 : if (ObjectBox::gtype() == 0)
707 : 0 : g_error("Failed to initialize JSObject GType");
708 : :
709 : : JS::RootedObject internal_global(
710 : 255 : m_cx, gjs_create_global_object(cx, GjsGlobalType::INTERNAL));
711 : :
712 [ - + ]: 255 : if (!internal_global) {
713 : 0 : gjs_log_exception(m_cx);
714 : 0 : g_error("Failed to initialize internal global object");
715 : : }
716 : :
717 : 255 : m_internal_global = internal_global;
718 : 255 : Gjs::AutoInternalRealm ar{this};
719 : 255 : JS_AddExtraGCRootsTracer(m_cx, &GjsContextPrivate::trace, this);
720 : :
721 [ - + ]: 255 : if (!m_atoms->init_atoms(m_cx)) {
722 : 0 : gjs_log_exception(m_cx);
723 : 0 : g_error("Failed to initialize global strings");
724 : : }
725 : :
726 [ - + ]: 255 : if (!gjs_define_global_properties(m_cx, internal_global,
727 : : GjsGlobalType::INTERNAL,
728 : : "GJS internal global", "nullptr")) {
729 : 0 : gjs_log_exception(m_cx);
730 : 0 : g_error("Failed to define properties on internal global object");
731 : : }
732 : :
733 : : JS::RootedObject global(
734 : 255 : m_cx,
735 : 255 : gjs_create_global_object(cx, GjsGlobalType::DEFAULT, internal_global));
736 : :
737 [ - + ]: 255 : if (!global) {
738 : 0 : gjs_log_exception(m_cx);
739 : 0 : g_error("Failed to initialize global object");
740 : : }
741 : :
742 : 255 : m_global = global;
743 : :
744 : : {
745 : 255 : Gjs::AutoMainRealm ar{this};
746 : :
747 : 255 : std::vector<std::string> paths;
748 [ + + ]: 255 : if (m_search_path)
749 : : paths = {m_search_path,
750 : 234 : m_search_path + g_strv_length(m_search_path)};
751 : 255 : JS::RootedObject importer(m_cx, gjs_create_root_importer(m_cx, paths));
752 [ - + ]: 255 : if (!importer) {
753 : 0 : gjs_log_exception(cx);
754 : 0 : g_error("Failed to create root importer");
755 : : }
756 : :
757 : 255 : g_assert(
758 : : gjs_get_global_slot(global, GjsGlobalSlot::IMPORTS).isUndefined() &&
759 : : "Someone else already created root importer");
760 : :
761 : 255 : gjs_set_global_slot(global, GjsGlobalSlot::IMPORTS,
762 : 255 : JS::ObjectValue(*importer));
763 : :
764 [ - + ]: 255 : if (!gjs_define_global_properties(m_cx, global, GjsGlobalType::DEFAULT,
765 : : "GJS", "default")) {
766 : 0 : gjs_log_exception(m_cx);
767 : 0 : g_error("Failed to define properties on global object");
768 : : }
769 : 255 : }
770 : :
771 : 255 : JS::SetModuleResolveHook(rt, gjs_module_resolve);
772 : 255 : JS::SetModuleDynamicImportHook(rt, gjs_dynamic_module_resolve);
773 : 255 : JS::SetModuleMetadataHook(rt, gjs_populate_module_meta);
774 : :
775 [ - + ]: 255 : if (!JS_DefineProperty(m_cx, internal_global, "moduleGlobalThis", global,
776 : : JSPROP_PERMANENT)) {
777 : 0 : gjs_log_exception(m_cx);
778 : 0 : g_error("Failed to define module global in internal global.");
779 : : }
780 : :
781 [ - + ]: 255 : if (!gjs_load_internal_module(cx, "internalLoader")) {
782 : 0 : gjs_log_exception(cx);
783 : 0 : g_error("Failed to load internal module loaders.");
784 : : }
785 : :
786 : 255 : load_context_module(cx,
787 : : "resource:///org/gnome/gjs/modules/internal/loader.js",
788 : : "module loader");
789 : :
790 : : {
791 : 255 : Gjs::AutoMainRealm ar{this};
792 : 255 : load_context_module(
793 : : cx, "resource:///org/gnome/gjs/modules/esm/_bootstrap/default.js",
794 : : "ESM bootstrap");
795 : 255 : }
796 : :
797 : 255 : [[maybe_unused]] bool success = m_main_loop.spin(this);
798 : 255 : g_assert(success && "bootstrap should not call system.exit()");
799 : :
800 : 255 : g_signal_connect_object(
801 : 255 : m_memory_monitor, "low-memory-warning",
802 [ # # ]: 0 : G_CALLBACK(+[](GjsContext* js_cx, GMemoryMonitorWarningLevel level) {
803 : : auto* cx =
804 : : static_cast<JSContext*>(gjs_context_get_native_context(js_cx));
805 : : JS::PrepareForFullGC(cx);
806 : : JS::GCOptions gc_strength = JS::GCOptions::Normal;
807 : : if (level > G_MEMORY_MONITOR_WARNING_LEVEL_LOW)
808 : : gc_strength = JS::GCOptions::Shrink;
809 : : JS::NonIncrementalGC(cx, gc_strength, Gjs::GCReason::LOW_MEMORY);
810 : : }),
811 : 255 : m_public_context, G_CONNECT_SWAPPED);
812 : :
813 : 255 : start_draining_job_queue();
814 : 255 : }
815 : :
816 : 64 : void GjsContextPrivate::set_args(std::vector<std::string>&& args) {
817 : 64 : m_args = args;
818 : 64 : }
819 : :
820 : 65 : JSObject* GjsContextPrivate::build_args_array() {
821 : 65 : return gjs_build_string_array(m_cx, m_args);
822 : : }
823 : :
824 : 0 : static void gjs_context_get_property(GObject* object, unsigned prop_id,
825 : : GValue* value, GParamSpec* pspec) {
826 : 0 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(object);
827 : :
828 [ # # # # ]: 0 : switch (prop_id) {
829 : 0 : case PROP_PROGRAM_NAME:
830 : 0 : g_value_set_string(value, gjs->program_name());
831 : 0 : break;
832 : 0 : case PROP_PROGRAM_PATH:
833 : 0 : g_value_set_string(value, gjs->program_path());
834 : 0 : break;
835 : 0 : case PROP_REPL_HISTORY_PATH:
836 : 0 : g_value_set_string(value, gjs->repl_history_path());
837 : 0 : break;
838 : 0 : default:
839 : 0 : G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
840 : 0 : break;
841 : : }
842 : 0 : }
843 : :
844 : 1785 : static void gjs_context_set_property(GObject* object, unsigned prop_id,
845 : : const GValue* value, GParamSpec* pspec) {
846 : 1785 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(object);
847 : :
848 [ + + + + : 1785 : switch (prop_id) {
+ + + - ]
849 : 255 : case PROP_SEARCH_PATH:
850 : 255 : gjs->set_search_path(static_cast<char**>(g_value_dup_boxed(value)));
851 : 255 : break;
852 : 255 : case PROP_PROGRAM_NAME:
853 : 255 : gjs->set_program_name(g_value_dup_string(value));
854 : 255 : break;
855 : 255 : case PROP_PROGRAM_PATH:
856 : 255 : gjs->set_program_path(g_value_dup_string(value));
857 : 255 : break;
858 : 255 : case PROP_PROFILER_ENABLED:
859 : 255 : gjs->set_should_profile(g_value_get_boolean(value));
860 : 255 : break;
861 : 255 : case PROP_PROFILER_SIGUSR2:
862 : 255 : gjs->set_should_listen_sigusr2(g_value_get_boolean(value));
863 : 255 : break;
864 : 255 : case PROP_EXEC_AS_MODULE:
865 : 255 : gjs->set_execute_as_module(g_value_get_boolean(value));
866 : 255 : break;
867 : 255 : case PROP_REPL_HISTORY_PATH:
868 : 255 : gjs->set_repl_history_path(g_value_dup_string(value));
869 : 255 : break;
870 : 0 : default:
871 : 0 : G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
872 : 0 : break;
873 : : }
874 : 1785 : }
875 : :
876 : 116 : GjsContext* gjs_context_new() {
877 : 116 : return (GjsContext*)g_object_new(GJS_TYPE_CONTEXT, nullptr);
878 : : }
879 : :
880 : : GjsContext*
881 : 75 : gjs_context_new_with_search_path(char** search_path)
882 : : {
883 : 75 : return (GjsContext*)g_object_new(GJS_TYPE_CONTEXT, "search-path",
884 : 75 : search_path, nullptr);
885 : : }
886 : :
887 : 0 : gboolean GjsContextPrivate::trigger_gc_if_needed(void* data) {
888 : 0 : auto* gjs = static_cast<GjsContextPrivate*>(data);
889 : 0 : gjs->m_auto_gc_id = 0;
890 : :
891 [ # # ]: 0 : if (gjs->m_force_gc) {
892 : : gjs_debug_lifecycle(GJS_DEBUG_CONTEXT, "Big Hammer hit");
893 : 0 : JS_GC(gjs->m_cx, Gjs::GCReason::BIG_HAMMER);
894 : : } else {
895 : 0 : gjs_gc_if_needed(gjs->m_cx);
896 : : }
897 : 0 : gjs->m_force_gc = false;
898 : :
899 : 0 : return G_SOURCE_REMOVE;
900 : : }
901 : :
902 : 16450 : void GjsContextPrivate::schedule_gc_internal(bool force_gc) {
903 : 16450 : m_force_gc |= force_gc;
904 : :
905 [ + + ]: 16450 : if (m_auto_gc_id > 0)
906 : 16306 : return;
907 : :
908 : : if (force_gc)
909 : : gjs_debug_lifecycle(GJS_DEBUG_CONTEXT, "Big Hammer scheduled");
910 : :
911 : 144 : m_auto_gc_id = g_timeout_add_seconds_full(G_PRIORITY_LOW, 10,
912 : : trigger_gc_if_needed, this,
913 : : nullptr);
914 : :
915 [ - + ]: 144 : if (force_gc)
916 : 0 : g_source_set_name_by_id(m_auto_gc_id, "[gjs] Garbage Collection (Big Hammer)");
917 : : else
918 : 144 : g_source_set_name_by_id(m_auto_gc_id, "[gjs] Garbage Collection");
919 : : }
920 : :
921 : : /**
922 : : * GjsContextPrivate::schedule_gc_if_needed:
923 : : *
924 : : * Does a minor GC immediately if the JS engine decides one is needed, but also
925 : : * schedules a full GC in the next idle time.
926 : : */
927 : 14878 : void GjsContextPrivate::schedule_gc_if_needed() {
928 : : // We call JS_MaybeGC immediately, but defer a check for a full GC cycle
929 : : // to an idle handler.
930 : 14878 : JS_MaybeGC(m_cx);
931 : :
932 : 14878 : schedule_gc_internal(false);
933 : 14878 : }
934 : :
935 : 1026 : void GjsContextPrivate::on_garbage_collection(JSGCStatus status, JS::GCReason reason) {
936 [ - + ]: 1026 : if (m_profiler)
937 : 0 : _gjs_profiler_set_gc_status(m_profiler, status, reason);
938 : :
939 [ + + - ]: 1026 : switch (status) {
940 : 513 : case JSGC_BEGIN:
941 : : gjs_debug_lifecycle(GJS_DEBUG_CONTEXT,
942 : : "Begin garbage collection because of %s",
943 : : gjs_explain_gc_reason(reason));
944 : :
945 : : // We finalize any pending toggle refs before doing any garbage
946 : : // collection, so that we can collect the JS wrapper objects, and in
947 : : // order to minimize the chances of objects having a pending toggle
948 : : // up queued when they are garbage collected.
949 : 513 : gjs_object_clear_toggles();
950 : :
951 : 513 : m_async_closures.clear();
952 : 513 : m_async_closures.shrink_to_fit();
953 : 513 : break;
954 : 513 : case JSGC_END:
955 : : gjs_debug_lifecycle(GJS_DEBUG_CONTEXT, "End garbage collection");
956 : 513 : break;
957 : 0 : default:
958 : : g_assert_not_reached();
959 : : }
960 : 1026 : }
961 : :
962 : 35 : void GjsContextPrivate::exit(uint8_t exit_code) {
963 : 35 : g_assert(!m_should_exit);
964 : 35 : m_should_exit = true;
965 : 35 : m_exit_code = exit_code;
966 : 35 : }
967 : :
968 : 2058 : bool GjsContextPrivate::should_exit(uint8_t* exit_code_p) const {
969 [ + + ]: 2058 : if (exit_code_p != nullptr)
970 : 381 : *exit_code_p = m_exit_code;
971 : 2058 : return m_should_exit;
972 : : }
973 : :
974 : 2 : void GjsContextPrivate::exit_immediately(uint8_t exit_code) {
975 : 2 : warn_about_unhandled_promise_rejections();
976 : :
977 : 2 : ::exit(exit_code);
978 : : }
979 : :
980 : 3684 : void GjsContextPrivate::start_draining_job_queue() { m_dispatcher.start(); }
981 : :
982 : 3682 : void GjsContextPrivate::stop_draining_job_queue() {
983 : 3682 : m_draining_job_queue = false;
984 : 3682 : m_dispatcher.stop();
985 : 3682 : }
986 : :
987 : 1410 : bool GjsContextPrivate::getHostDefinedData(JSContext* cx,
988 : : JS::MutableHandleObject data) const {
989 : : // This is equivalent to SpiderMonkey's behavior.
990 : 1410 : data.set(JS::CurrentGlobalOrNull(cx));
991 : 1410 : return true;
992 : : }
993 : :
994 : : // See engine.cpp and JS::SetJobQueue().
995 : 1402 : bool GjsContextPrivate::enqueuePromiseJob(JSContext* cx [[maybe_unused]],
996 : : JS::HandleObject promise,
997 : : JS::HandleObject job,
998 : : JS::HandleObject allocation_site,
999 : : JS::HandleObject incumbent_global
1000 : : [[maybe_unused]]) {
1001 : 1402 : g_assert(cx == m_cx);
1002 : 1402 : g_assert(from_cx(cx) == this);
1003 : :
1004 : 4206 : gjs_debug(GJS_DEBUG_MAINLOOP,
1005 : : "Enqueue job %s, promise=%s, allocation site=%s",
1006 : 4206 : gjs_debug_object(job).c_str(), gjs_debug_object(promise).c_str(),
1007 : 2804 : gjs_debug_object(allocation_site).c_str());
1008 : :
1009 [ - + ]: 1402 : if (!m_job_queue.append(job)) {
1010 : 0 : JS_ReportOutOfMemory(m_cx);
1011 : 0 : return false;
1012 : : }
1013 : :
1014 : 1402 : JS::JobQueueMayNotBeEmpty(m_cx);
1015 : 1402 : m_dispatcher.start();
1016 : 1402 : return true;
1017 : : }
1018 : :
1019 : : // Override of JobQueue::runJobs(). Called by js::RunJobs(), and when execution
1020 : : // of the job queue was interrupted by the debugger and is resuming.
1021 : 10323 : void GjsContextPrivate::runJobs(JSContext* cx) {
1022 : 10323 : g_assert(cx == m_cx);
1023 : 10323 : g_assert(from_cx(cx) == this);
1024 [ + + ]: 10323 : if (!run_jobs_fallible())
1025 : 4 : gjs_log_exception(cx);
1026 : 10323 : }
1027 : :
1028 : : /**
1029 : : * GjsContext::run_jobs_fallible:
1030 : : *
1031 : : * Drains the queue of promise callbacks that the JS engine has reported
1032 : : * finished, calling each one and logging any exceptions that it throws.
1033 : : *
1034 : : * Adapted from js::RunJobs() in SpiderMonkey's default job queue
1035 : : * implementation.
1036 : : *
1037 : : * Returns: false if one of the jobs threw an uncatchable exception;
1038 : : * otherwise true.
1039 : : */
1040 : 10352 : bool GjsContextPrivate::run_jobs_fallible() {
1041 : 10352 : bool retval = true;
1042 : :
1043 [ + - + + ]: 10352 : if (m_draining_job_queue || m_should_exit)
1044 : 35 : return true;
1045 : :
1046 : 10317 : m_draining_job_queue = true; // Ignore reentrant calls
1047 : :
1048 : 10317 : JS::RootedObject job(m_cx);
1049 : 10317 : JS::HandleValueArray args(JS::HandleValueArray::empty());
1050 : 10317 : JS::RootedValue rval(m_cx);
1051 : :
1052 [ + + ]: 10317 : if (m_job_queue.length() == 0) {
1053 : : // Check FinalizationRegistry cleanup tasks at least once if there are
1054 : : // no microtasks queued. This may enqueue more microtasks, which will be
1055 : : // appended to m_job_queue.
1056 [ - + ]: 9749 : if (!run_finalization_registry_cleanup())
1057 : 0 : retval = false;
1058 : : }
1059 : :
1060 : : /* Execute jobs in a loop until we've reached the end of the queue.
1061 : : * Since executing a job can trigger enqueueing of additional jobs,
1062 : : * it's crucial to recheck the queue length during each iteration. */
1063 [ + + ]: 11714 : for (size_t ix = 0; ix < m_job_queue.length(); ix++) {
1064 : : // A previous job might have set this flag. e.g., System.exit().
1065 [ + + - + : 1398 : if (m_should_exit || !m_dispatcher.is_running()) {
+ + ]
1066 : 1 : gjs_debug(GJS_DEBUG_MAINLOOP, "Stopping jobs because of %s",
1067 [ + - ]: 1 : m_should_exit ? "exit" : "main loop cancel");
1068 : 1 : break;
1069 : : }
1070 : :
1071 : 1397 : job = m_job_queue[ix];
1072 : :
1073 : : /* It's possible that job draining was interrupted prematurely,
1074 : : * leaving the queue partly processed. In that case, slots for
1075 : : * already-executed entries will contain nullptrs, which we should
1076 : : * just skip. */
1077 [ - + ]: 1397 : if (!job)
1078 : 0 : continue;
1079 : :
1080 : 1397 : m_job_queue[ix] = nullptr;
1081 : : {
1082 : 1397 : JSAutoRealm ar(m_cx, job);
1083 : 1397 : gjs_debug(GJS_DEBUG_MAINLOOP, "handling job %zu, %s", ix,
1084 : 2794 : gjs_debug_object(job).c_str());
1085 [ + + ]: 1397 : if (!JS::Call(m_cx, JS::UndefinedHandleValue, job, args, &rval)) {
1086 : : /* Uncatchable exception - return false so that
1087 : : * System.exit() works in the interactive shell and when
1088 : : * exiting the interpreter. */
1089 [ + - ]: 4 : if (!JS_IsExceptionPending(m_cx)) {
1090 : : /* System.exit() is an uncatchable exception, but does not
1091 : : * indicate a bug. Log everything else. */
1092 [ - + ]: 4 : if (!should_exit(nullptr))
1093 : 0 : g_critical("Promise callback terminated with uncatchable exception");
1094 : 4 : retval = false;
1095 : 4 : continue;
1096 : : }
1097 : :
1098 : : // There's nowhere for the exception to go at this point
1099 : 0 : gjs_log_exception_uncaught(m_cx);
1100 : : }
1101 [ + + ]: 1397 : }
1102 : 1393 : gjs_debug(GJS_DEBUG_MAINLOOP, "Completed job %zu", ix);
1103 : :
1104 : : // Run FinalizationRegistry cleanup tasks after each job. Cleanup tasks
1105 : : // may enqueue more microtasks, which will be appended to m_job_queue.
1106 [ - + ]: 1393 : if (!run_finalization_registry_cleanup())
1107 : 0 : retval = false;
1108 : : }
1109 : :
1110 : 10317 : m_draining_job_queue = false;
1111 : 10317 : m_job_queue.clear();
1112 : 10317 : warn_about_unhandled_promise_rejections();
1113 : 10317 : JS::JobQueueIsEmpty(m_cx);
1114 : 10317 : return retval;
1115 : 10317 : }
1116 : :
1117 : 11142 : bool GjsContextPrivate::run_finalization_registry_cleanup() {
1118 : 11142 : bool retval = true;
1119 : :
1120 : 11142 : JS::Rooted<FunctionVector> tasks{m_cx};
1121 : 11142 : std::swap(tasks.get(), m_cleanup_tasks);
1122 : 11142 : g_assert(m_cleanup_tasks.empty());
1123 : :
1124 : 11142 : JS::RootedFunction task{m_cx};
1125 : 11142 : JS::RootedValue unused_rval{m_cx};
1126 [ + + ]: 11147 : for (JSFunction* func : tasks) {
1127 : 5 : gjs_debug(GJS_DEBUG_MAINLOOP,
1128 : : "Running FinalizationRegistry cleanup callback");
1129 : :
1130 : 5 : task.set(func);
1131 : 5 : JS::ExposeObjectToActiveJS(JS_GetFunctionObject(func));
1132 : :
1133 : 5 : JSAutoRealm ar{m_cx, JS_GetFunctionObject(func)};
1134 [ - + ]: 5 : if (!JS_CallFunction(m_cx, nullptr, task, JS::HandleValueArray::empty(),
1135 : 5 : &unused_rval)) {
1136 : : // Same logic as above
1137 [ # # ]: 0 : if (!JS_IsExceptionPending(m_cx)) {
1138 [ # # ]: 0 : if (!should_exit(nullptr))
1139 : 0 : g_critical(
1140 : : "FinalizationRegistry callback terminated with "
1141 : : "uncatchable exception");
1142 : 0 : retval = false;
1143 : 0 : continue;
1144 : : }
1145 : 0 : gjs_log_exception_uncaught(m_cx);
1146 : : }
1147 : :
1148 : 5 : gjs_debug(GJS_DEBUG_MAINLOOP,
1149 : : "Completed FinalizationRegistry cleanup callback");
1150 [ + - ]: 5 : }
1151 : :
1152 : 22284 : return retval;
1153 : 11142 : }
1154 : :
1155 : : class GjsContextPrivate::SavedQueue : public JS::JobQueue::SavedJobQueue {
1156 : : private:
1157 : : GjsContextPrivate* m_gjs;
1158 : : JS::PersistentRooted<JobQueueStorage> m_queue;
1159 : : bool m_was_draining : 1;
1160 : :
1161 : : public:
1162 : 3429 : explicit SavedQueue(GjsContextPrivate* gjs)
1163 : 6858 : : m_gjs(gjs),
1164 : 3429 : m_queue(gjs->m_cx, std::move(gjs->m_job_queue)),
1165 : 3429 : m_was_draining(gjs->m_draining_job_queue) {
1166 : 3429 : gjs_debug(GJS_DEBUG_CONTEXT, "Pausing job queue");
1167 : 3429 : gjs->stop_draining_job_queue();
1168 : 3429 : }
1169 : :
1170 : 3429 : ~SavedQueue() {
1171 : 3429 : gjs_debug(GJS_DEBUG_CONTEXT, "Unpausing job queue");
1172 : 6858 : m_gjs->m_job_queue = std::move(m_queue.get());
1173 : 3429 : m_gjs->m_draining_job_queue = m_was_draining;
1174 : 3429 : m_gjs->start_draining_job_queue();
1175 : 3429 : }
1176 : : };
1177 : :
1178 : 3429 : js::UniquePtr<JS::JobQueue::SavedJobQueue> GjsContextPrivate::saveJobQueue(
1179 : : JSContext* cx) {
1180 : 3429 : g_assert(cx == m_cx);
1181 : 3429 : g_assert(from_cx(cx) == this);
1182 : :
1183 : 3429 : auto saved_queue = js::MakeUnique<SavedQueue>(this);
1184 [ - + ]: 3429 : if (!saved_queue) {
1185 : 0 : JS_ReportOutOfMemory(cx);
1186 : 0 : return nullptr;
1187 : : }
1188 : :
1189 : 3429 : g_assert(m_job_queue.empty());
1190 : 3429 : return saved_queue;
1191 : 3429 : }
1192 : :
1193 : 26 : void GjsContextPrivate::register_unhandled_promise_rejection(
1194 : : uint64_t id, JS::UniqueChars&& stack) {
1195 : 26 : m_unhandled_rejection_stacks[id] = std::move(stack);
1196 : 26 : }
1197 : :
1198 : 25 : void GjsContextPrivate::unregister_unhandled_promise_rejection(uint64_t id) {
1199 : 25 : size_t erased = m_unhandled_rejection_stacks.erase(id);
1200 [ - + ]: 25 : if (erased != 1) {
1201 : 0 : g_critical(
1202 : : "Promise %" PRIu64
1203 : : " handler attached to rejected promise that wasn't previously "
1204 : : "marked as unhandled or that we wrongly reported as unhandled",
1205 : : id);
1206 : : }
1207 : 25 : }
1208 : :
1209 : 5 : bool GjsContextPrivate::queue_finalization_registry_cleanup(
1210 : : JSFunction* cleanup_task) {
1211 : 5 : return m_cleanup_tasks.append(cleanup_task);
1212 : : }
1213 : :
1214 : 132 : void GjsContextPrivate::async_closure_enqueue_for_gc(Gjs::Closure* trampoline) {
1215 : : // Because we can't free the mmap'd data for a callback
1216 : : // while it's in use, this list keeps track of ones that
1217 : : // will be freed the next time gc happens
1218 : 132 : g_assert(!trampoline->cx() || trampoline->cx() == m_cx);
1219 : 132 : m_async_closures.emplace_back(trampoline);
1220 : 132 : }
1221 : :
1222 : : /**
1223 : : * gjs_context_maybe_gc:
1224 : : * @context: a #GjsContext
1225 : : *
1226 : : * Similar to the Spidermonkey JS_MaybeGC() call which
1227 : : * heuristically looks at JS runtime memory usage and
1228 : : * may initiate a garbage collection.
1229 : : *
1230 : : * This function always unconditionally invokes JS_MaybeGC(), but
1231 : : * additionally looks at memory usage from the system malloc()
1232 : : * when available, and if the delta has grown since the last run
1233 : : * significantly, also initiates a full JavaScript garbage
1234 : : * collection. The idea is that since GJS is a bridge between
1235 : : * JavaScript and system libraries, and JS objects act as proxies
1236 : : * for these system memory objects, GJS consumers need a way to
1237 : : * hint to the runtime that it may be a good idea to try a
1238 : : * collection.
1239 : : *
1240 : : * A good time to call this function is when your application
1241 : : * transitions to an idle state.
1242 : : */
1243 : : void
1244 : 0 : gjs_context_maybe_gc (GjsContext *context)
1245 : : {
1246 : 0 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(context);
1247 : 0 : gjs_maybe_gc(gjs->context());
1248 : 0 : }
1249 : :
1250 : : /**
1251 : : * gjs_context_gc:
1252 : : * @context: a #GjsContext
1253 : : *
1254 : : * Initiate a full GC; may or may not block until complete. This
1255 : : * function just calls Spidermonkey JS_GC().
1256 : : */
1257 : : void
1258 : 0 : gjs_context_gc (GjsContext *context)
1259 : : {
1260 : 0 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(context);
1261 : 0 : JS_GC(gjs->context(), Gjs::GCReason::GJS_API_CALL);
1262 : 0 : }
1263 : :
1264 : : /**
1265 : : * gjs_context_get_all:
1266 : : *
1267 : : * Returns a newly-allocated list containing all known instances of #GjsContext.
1268 : : * This is useful for operating on the contexts from a process-global situation
1269 : : * such as a debugger.
1270 : : *
1271 : : * Return value: (element-type GjsContext) (transfer full): Known #GjsContext instances
1272 : : */
1273 : 44 : GList* gjs_context_get_all() {
1274 : : GList *result;
1275 : : GList *iter;
1276 : 44 : g_mutex_lock (&contexts_lock);
1277 : 44 : result = g_list_copy(all_contexts);
1278 [ + + ]: 88 : for (iter = result; iter; iter = iter->next)
1279 : 44 : g_object_ref((GObject*)iter->data);
1280 : 44 : g_mutex_unlock (&contexts_lock);
1281 : 44 : return result;
1282 : : }
1283 : :
1284 : : /**
1285 : : * gjs_context_get_native_context:
1286 : : *
1287 : : * Returns a pointer to the underlying native context. For SpiderMonkey, this
1288 : : * is a JSContext *
1289 : : */
1290 : : void*
1291 : 1635 : gjs_context_get_native_context (GjsContext *js_context)
1292 : : {
1293 : 1635 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), nullptr);
1294 : 1635 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1295 : 1635 : return gjs->context();
1296 : : }
1297 : :
1298 : 538 : static inline bool result_to_c(GErrorResult<> result, GError** error_out) {
1299 [ + + ]: 538 : if (result.isOk())
1300 : 493 : return true;
1301 : 45 : *error_out = result.unwrapErr().release();
1302 : 45 : return false;
1303 : : }
1304 : :
1305 : 232 : bool gjs_context_eval(GjsContext* js_context, const char* script,
1306 : : ssize_t script_len, const char* filename,
1307 : : int* exit_status_p, GError** error) {
1308 : 232 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), false);
1309 : :
1310 [ + + ]: 232 : size_t real_len = script_len < 0 ? strlen(script) : script_len;
1311 : :
1312 : 232 : Gjs::AutoUnref<GjsContext> js_context_ref{js_context, Gjs::TakeOwnership{}};
1313 : 232 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1314 : :
1315 : 232 : gjs->register_non_module_sourcemap(script, filename);
1316 : 463 : return result_to_c(gjs->eval(script, real_len, filename, exit_status_p),
1317 : 231 : error);
1318 : 231 : }
1319 : :
1320 : 153 : bool gjs_context_eval_module(GjsContext* js_context, const char* identifier,
1321 : : uint8_t* exit_code, GError** error) {
1322 : 153 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), false);
1323 : :
1324 : 153 : Gjs::AutoUnref<GjsContext> js_context_ref{js_context, Gjs::TakeOwnership{}};
1325 : :
1326 : 153 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1327 : 153 : return result_to_c(gjs->eval_module(identifier, exit_code), error);
1328 : 152 : }
1329 : :
1330 : 155 : bool gjs_context_register_module(GjsContext* js_context, const char* identifier,
1331 : : const char* uri, GError** error) {
1332 : 155 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), false);
1333 : :
1334 : 155 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1335 : :
1336 : 155 : return result_to_c(gjs->register_module(identifier, uri), error);
1337 : : }
1338 : :
1339 : 385 : bool GjsContextPrivate::auto_profile_enter() {
1340 : 385 : bool auto_profile = m_should_profile;
1341 [ + + + + : 493 : if (auto_profile &&
+ + ]
1342 [ - + ]: 108 : (_gjs_profiler_is_running(m_profiler) || m_should_listen_sigusr2))
1343 : 100 : auto_profile = false;
1344 : :
1345 : 385 : Gjs::AutoMainRealm ar{this};
1346 : :
1347 [ + + ]: 385 : if (auto_profile)
1348 : 4 : gjs_profiler_start(m_profiler);
1349 : :
1350 : 770 : return auto_profile;
1351 : 385 : }
1352 : :
1353 : 379 : void GjsContextPrivate::auto_profile_exit(bool auto_profile) {
1354 [ + + ]: 379 : if (auto_profile)
1355 : 4 : gjs_profiler_stop(m_profiler);
1356 : 379 : }
1357 : :
1358 : 379 : GErrorResult<> GjsContextPrivate::handle_exit_code(bool no_sync_error_pending,
1359 : : const char* source_type,
1360 : : const char* identifier,
1361 : : uint8_t* exit_code) {
1362 : : uint8_t code;
1363 [ + + ]: 379 : if (should_exit(&code)) {
1364 : : /* exit_status_p is public API so can't be changed, but should be
1365 : : * uint8_t, not int */
1366 : 33 : Gjs::AutoError error;
1367 : 33 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_SYSTEM_EXIT,
1368 : : "Exit with code %d", code);
1369 : :
1370 : 33 : *exit_code = code;
1371 : 33 : return Err(error.release()); // Don't log anything
1372 : 33 : }
1373 : :
1374 : : // Once the main loop exits an exception could
1375 : : // be pending even if the script returned
1376 : : // true synchronously
1377 [ + + ]: 346 : if (JS_IsExceptionPending(m_cx)) {
1378 : 4 : Gjs::AutoError error;
1379 : 4 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1380 : : "%s %s threw an exception", source_type, identifier);
1381 : 4 : gjs_log_exception_uncaught(m_cx);
1382 : :
1383 : 4 : *exit_code = 1;
1384 : 4 : return Err(error.release());
1385 : 4 : }
1386 : :
1387 [ + + ]: 342 : if (m_unhandled_exception) {
1388 : 3 : Gjs::AutoError error;
1389 : 3 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1390 : : "%s %s threw an exception", source_type, identifier);
1391 : 3 : *exit_code = 1;
1392 : 3 : return Err(error.release());
1393 : 3 : }
1394 : :
1395 : : // Assume success if no error was thrown and should exit isn't set
1396 [ + - ]: 339 : if (no_sync_error_pending) {
1397 : 339 : *exit_code = 0;
1398 : 339 : return Ok{};
1399 : : }
1400 : :
1401 : 0 : g_critical("%s %s terminated with an uncatchable exception", source_type,
1402 : : identifier);
1403 : 0 : Gjs::AutoError error;
1404 : 0 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1405 : : "%s %s terminated with an uncatchable exception", source_type,
1406 : : identifier);
1407 : :
1408 : 0 : gjs_log_exception_uncaught(m_cx);
1409 : : // No exit code from script, but we don't want to exit(0)
1410 : 0 : *exit_code = 1;
1411 : 0 : return Err(error.release());
1412 : 0 : }
1413 : :
1414 : 51 : bool GjsContextPrivate::set_main_loop_hook(JSObject* callable) {
1415 : 51 : g_assert(JS::IsCallable(callable) && "main loop hook must be a callable object");
1416 : :
1417 [ - + ]: 51 : if (!callable) {
1418 : 0 : m_main_loop_hook = nullptr;
1419 : 0 : return true;
1420 : : }
1421 : :
1422 [ - + ]: 51 : if (m_main_loop_hook)
1423 : 0 : return false;
1424 : :
1425 : 51 : m_main_loop_hook = callable;
1426 : 51 : return true;
1427 : : }
1428 : :
1429 : 51 : bool GjsContextPrivate::run_main_loop_hook() {
1430 : 51 : JS::RootedObject hook(m_cx, m_main_loop_hook.get());
1431 : 51 : m_main_loop_hook = nullptr;
1432 : 51 : gjs_debug(GJS_DEBUG_MAINLOOP, "Running and clearing main loop hook");
1433 : 51 : JS::RootedValue ignored_rval(m_cx);
1434 : 51 : return JS::Call(m_cx, JS::NullHandleValue, hook,
1435 : 102 : JS::HandleValueArray::empty(), &ignored_rval);
1436 : 51 : }
1437 : :
1438 : : // source maps parsing is built upon hooks for resolving or loading modules
1439 : : // for non-module runs we need to invoke this logic manually
1440 : 232 : void GjsContextPrivate::register_non_module_sourcemap(const char* script,
1441 : : const char* filename) {
1442 : 24680 : using AutoURI = Gjs::AutoPointer<GUri, GUri, g_uri_unref>;
1443 : 232 : Gjs::AutoMainRealm ar{this};
1444 : :
1445 : 232 : JS::RootedObject global{m_cx, JS::CurrentGlobalOrNull(m_cx)};
1446 : : JS::RootedValue v_loader{
1447 : 232 : m_cx, gjs_get_global_slot(global, GjsGlobalSlot::MODULE_LOADER)};
1448 : 232 : g_assert(v_loader.isObject());
1449 : 232 : JS::RootedObject v_loader_obj{m_cx, &v_loader.toObject()};
1450 : :
1451 : 232 : JS::RootedValueArray<3> args{m_cx};
1452 : 232 : JS::RootedString script_str{m_cx, JS_NewStringCopyZ(m_cx, script)};
1453 : 232 : JS::RootedString file_name_str{m_cx, JS_NewStringCopyZ(m_cx, filename)};
1454 : 232 : args[0].setString(script_str);
1455 : 232 : args[1].setString(file_name_str);
1456 : :
1457 : : // if the file uri is not an absolute uri with a scheme, build one assuming
1458 : : // file:// this parameter is used to help locate non-inlined source map file
1459 : 232 : AutoURI uri = g_uri_parse(filename, G_URI_FLAGS_NONE, nullptr);
1460 [ + + ]: 232 : if (!uri) {
1461 : 227 : Gjs::AutoUnref<GFile> file = g_file_new_for_path(filename);
1462 : 227 : Gjs::AutoChar file_uri = g_file_get_uri(file);
1463 : : JS::RootedString abs_filename_scheme_str{
1464 : 227 : m_cx, JS_NewStringCopyZ(m_cx, file_uri.get())};
1465 : 227 : args[2].setString(abs_filename_scheme_str);
1466 : 227 : }
1467 : :
1468 : 232 : JS::RootedValue ignored{m_cx};
1469 : 232 : JS::Call(m_cx, v_loader_obj, "populateSourceMap", args, &ignored);
1470 : 232 : }
1471 : :
1472 : 232 : GErrorResult<> GjsContextPrivate::eval(const char* script, size_t script_len,
1473 : : const char* filename,
1474 : : int* exit_status_p) {
1475 : 232 : AutoResetExit reset(this);
1476 : :
1477 : 232 : bool auto_profile = auto_profile_enter();
1478 : :
1479 : 232 : Gjs::AutoMainRealm ar{this};
1480 : :
1481 : 232 : JS::RootedValue retval(m_cx);
1482 : 232 : bool ok = eval_with_scope(nullptr, script, script_len, filename, &retval);
1483 : :
1484 : : // If there are no errors and the mainloop hook is set, call it.
1485 [ + + - + : 231 : if (ok && m_main_loop_hook)
- + ]
1486 : 0 : ok = run_main_loop_hook();
1487 : :
1488 : 231 : bool exiting = false;
1489 : :
1490 : : // Spin the internal loop until the main loop hook is set or no holds
1491 : : // remain.
1492 : : // If the main loop returns false we cannot guarantee the state of our
1493 : : // promise queue (a module promise could be pending) so instead of draining
1494 : : // draining the queue we instead just exit.
1495 [ + + + + : 231 : if (ok && !m_main_loop.spin(this)) {
+ + ]
1496 : 2 : exiting = true;
1497 : : }
1498 : :
1499 : : // If the hook has been set again, enter a loop until an error is
1500 : : // encountered or the main loop is quit.
1501 [ + + + + : 231 : while (ok && !exiting && m_main_loop_hook) {
- + - + ]
1502 : 0 : ok = run_main_loop_hook();
1503 : :
1504 : : // Additional jobs could have been enqueued from the
1505 : : // main loop hook
1506 [ # # # # : 0 : if (ok && !m_main_loop.spin(this)) {
# # ]
1507 : 0 : exiting = true;
1508 : : }
1509 : : }
1510 : :
1511 : : // The promise job queue should be drained even on error, to finish
1512 : : // outstanding async tasks before the context is torn down. Drain after
1513 : : // uncaught exceptions have been reported since draining runs callbacks.
1514 : : // We do not drain if we are exiting.
1515 [ + + + - ]: 231 : if (!ok && !exiting) {
1516 : 29 : JS::AutoSaveExceptionState saved_exc(m_cx);
1517 [ + - - + ]: 29 : ok = run_jobs_fallible() && ok;
1518 : 29 : }
1519 : :
1520 : 231 : auto_profile_exit(auto_profile);
1521 : :
1522 : : uint8_t out_code;
1523 : 231 : GErrorResult<> result = handle_exit_code(ok, "Script", filename, &out_code);
1524 : :
1525 [ + + ]: 231 : if (exit_status_p) {
1526 [ + + + + : 206 : if (result.isOk() && retval.isInt32()) {
+ + ]
1527 : 5 : int code = retval.toInt32();
1528 : 5 : gjs_debug(GJS_DEBUG_CONTEXT,
1529 : : "Script returned integer code %d", code);
1530 : 5 : *exit_status_p = code;
1531 : : } else {
1532 : 201 : *exit_status_p = out_code;
1533 : : }
1534 : : }
1535 : :
1536 : 462 : return result;
1537 : 231 : }
1538 : :
1539 : 153 : GErrorResult<> GjsContextPrivate::eval_module(const char* identifier,
1540 : : uint8_t* exit_status_p) {
1541 : 153 : AutoResetExit reset(this);
1542 : :
1543 : 153 : bool auto_profile = auto_profile_enter();
1544 : :
1545 : 153 : Gjs::AutoMainRealm ar{this};
1546 : :
1547 : 153 : JS::RootedObject registry(m_cx, gjs_get_module_registry(m_global));
1548 : 153 : JS::RootedId key(m_cx, gjs_intern_string_to_id(m_cx, identifier));
1549 : 153 : JS::RootedObject obj(m_cx);
1550 [ + - + + : 153 : if (!gjs_global_registry_get(m_cx, registry, key, &obj) || !obj) {
+ + ]
1551 : 2 : Gjs::AutoError error;
1552 : 2 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1553 : : "Cannot load module with identifier: '%s'", identifier);
1554 : :
1555 [ + + ]: 2 : if (exit_status_p)
1556 : 1 : *exit_status_p = 1;
1557 : 2 : return Err(error.release());
1558 : 2 : }
1559 : :
1560 [ + + ]: 151 : if (!JS::ModuleLink(m_cx, obj)) {
1561 : 2 : gjs_log_exception(m_cx);
1562 : 2 : Gjs::AutoError error;
1563 : 2 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1564 : : "Failed to resolve imports for module: '%s'", identifier);
1565 : :
1566 [ + + ]: 2 : if (exit_status_p)
1567 : 1 : *exit_status_p = 1;
1568 : 2 : return Err(error.release());
1569 : 2 : }
1570 : :
1571 : 149 : JS::RootedValue evaluation_promise(m_cx);
1572 : 149 : bool ok = JS::ModuleEvaluate(m_cx, obj, &evaluation_promise);
1573 : :
1574 [ + - ]: 148 : if (ok) {
1575 : 148 : GjsContextPrivate::from_cx(m_cx)->main_loop_hold();
1576 : :
1577 : 148 : ok = add_promise_reactions(
1578 : 148 : m_cx, evaluation_promise, on_context_module_resolved,
1579 : 444 : on_context_module_rejected_log_exception, identifier);
1580 : : }
1581 : :
1582 : 148 : bool exiting = false;
1583 : :
1584 : : do {
1585 : : // If there are no errors and the mainloop hook is set, call it.
1586 [ + - + + : 150 : if (ok && m_main_loop_hook)
+ + ]
1587 : 51 : ok = run_main_loop_hook();
1588 : :
1589 : : // Spin the internal loop until the main loop hook is set or no holds
1590 : : // remain.
1591 : : //
1592 : : // If the main loop returns false we cannot guarantee the state of our
1593 : : // promise queue (a module promise could be pending) so instead of
1594 : : // draining the queue we instead just exit.
1595 : : //
1596 : : // Additional jobs could have been enqueued from the
1597 : : // main loop hook
1598 [ + - + + : 150 : if (ok && !m_main_loop.spin(this)) {
+ + ]
1599 : 6 : exiting = true;
1600 : : }
1601 [ + - + + : 150 : } while (ok && !exiting && m_main_loop_hook);
+ + + + ]
1602 : :
1603 : : // The promise job queue should be drained even on error, to finish
1604 : : // outstanding async tasks before the context is torn down. Drain after
1605 : : // uncaught exceptions have been reported since draining runs callbacks.
1606 : : // We do not drain if we are exiting.
1607 [ - + - - ]: 148 : if (!ok && !exiting) {
1608 : 0 : JS::AutoSaveExceptionState saved_exc(m_cx);
1609 [ # # # # ]: 0 : ok = run_jobs_fallible() && ok;
1610 : 0 : }
1611 : :
1612 : 148 : auto_profile_exit(auto_profile);
1613 : :
1614 : : uint8_t out_code;
1615 : : GErrorResult<> result =
1616 : 148 : handle_exit_code(ok, "Module", identifier, &out_code);
1617 [ + + ]: 148 : if (exit_status_p)
1618 : 146 : *exit_status_p = out_code;
1619 : :
1620 : 148 : return result;
1621 : 152 : }
1622 : :
1623 : 155 : GErrorResult<> GjsContextPrivate::register_module(const char* identifier,
1624 : : const char* uri) {
1625 : 155 : Gjs::AutoMainRealm ar{this};
1626 : :
1627 [ + + ]: 155 : if (gjs_module_load(m_cx, identifier, uri))
1628 : 154 : return Ok{};
1629 : :
1630 : 1 : const char* msg = "unknown";
1631 : 1 : JS::ExceptionStack exn_stack(m_cx);
1632 : 1 : JS::ErrorReportBuilder builder(m_cx);
1633 [ + - + - : 2 : if (JS::StealPendingExceptionStack(m_cx, &exn_stack) &&
+ - ]
1634 : 1 : builder.init(m_cx, exn_stack,
1635 : : JS::ErrorReportBuilder::WithSideEffects)) {
1636 : 1 : msg = builder.toStringResult().c_str();
1637 : : } else {
1638 : 0 : JS_ClearPendingException(m_cx);
1639 : : }
1640 : :
1641 : 1 : Gjs::AutoError error;
1642 [ + - ]: 1 : g_set_error(error.out(), GJS_ERROR, GJS_ERROR_FAILED,
1643 : : "Failed to parse module '%s': %s", identifier,
1644 : : msg ? msg : "unknown");
1645 : :
1646 : 1 : return Err(error.release());
1647 : 155 : }
1648 : :
1649 : : bool
1650 : 40 : gjs_context_eval_file(GjsContext *js_context,
1651 : : const char *filename,
1652 : : int *exit_status_p,
1653 : : GError **error)
1654 : : {
1655 : 40 : Gjs::AutoChar script;
1656 : : size_t script_len;
1657 : 40 : Gjs::AutoUnref<GFile> file{g_file_new_for_commandline_arg(filename)};
1658 : :
1659 [ + + ]: 40 : if (!g_file_load_contents(file, nullptr, script.out(), &script_len, nullptr,
1660 : : error))
1661 : 1 : return false;
1662 : :
1663 : 39 : return gjs_context_eval(js_context, script, script_len, filename,
1664 : 39 : exit_status_p, error);
1665 : 40 : }
1666 : :
1667 : 141 : bool gjs_context_eval_module_file(GjsContext* js_context, const char* filename,
1668 : : uint8_t* exit_status_p, GError** error) {
1669 : 141 : Gjs::AutoUnref<GFile> file{g_file_new_for_commandline_arg(filename)};
1670 : 141 : Gjs::AutoChar uri{g_file_get_uri(file)};
1671 : :
1672 [ + - + + ]: 282 : return gjs_context_register_module(js_context, uri, uri, error) &&
1673 : 141 : gjs_context_eval_module(js_context, uri, exit_status_p, error);
1674 : 141 : }
1675 : :
1676 : : /**
1677 : : * GjsContextPrivate::eval_with_scope:
1678 : : * @scope_object: an object to use as the global scope, or nullptr
1679 : : * @source: JavaScript program encoded in UTF-8
1680 : : * @source_len: length of @source, or -1 if @source is 0-terminated
1681 : : * @filename: filename to use as the origin of @source
1682 : : * @retval: location for the return value of @source
1683 : : *
1684 : : * Executes @source with a local scope so that nothing from the source code
1685 : : * leaks out into the global scope.
1686 : : * If @scope_object is given, then everything that @source placed in the global
1687 : : * namespace is defined on @scope_object.
1688 : : * Otherwise, the global definitions are just discarded.
1689 : : */
1690 : 235 : bool GjsContextPrivate::eval_with_scope(JS::HandleObject scope_object,
1691 : : const char* source, size_t source_len,
1692 : : const char* filename,
1693 : : JS::MutableHandleValue retval) {
1694 : : // log and clear exception if it's set (should not be, normally...)
1695 [ - + ]: 235 : if (JS_IsExceptionPending(m_cx)) {
1696 : 0 : g_warning("eval_with_scope() called with a pending exception");
1697 : 0 : return false;
1698 : : }
1699 : :
1700 : 235 : JS::RootedObject eval_obj(m_cx, scope_object);
1701 [ + + ]: 235 : if (!eval_obj)
1702 : 232 : eval_obj = JS_NewPlainObject(m_cx);
1703 : :
1704 : 235 : JS::SourceText<mozilla::Utf8Unit> buf;
1705 [ - + ]: 235 : if (!buf.init(m_cx, source, source_len, JS::SourceOwnership::Borrowed))
1706 : 0 : return false;
1707 : :
1708 : 235 : JS::EnvironmentChain scope_chain{m_cx, JS::SupportUnscopables::No};
1709 [ - + ]: 235 : if (!scope_chain.append(eval_obj)) {
1710 : 0 : JS_ReportOutOfMemory(m_cx);
1711 : 0 : return false;
1712 : : }
1713 : :
1714 : 235 : JS::CompileOptions options(m_cx);
1715 : 235 : options.setFileAndLine(filename, 1).setNonSyntacticScope(true);
1716 : :
1717 : 235 : Gjs::AutoUnref<GFile> file{g_file_new_for_commandline_arg(filename)};
1718 : 235 : Gjs::AutoChar uri{g_file_get_uri(file)};
1719 : 235 : JS::RootedObject priv(m_cx, gjs_script_module_build_private(m_cx, uri));
1720 [ - + ]: 235 : if (!priv)
1721 : 0 : return false;
1722 : :
1723 : 235 : JS::RootedScript script(m_cx);
1724 : 235 : script.set(JS::Compile(m_cx, options, buf));
1725 [ + + ]: 235 : if (!script)
1726 : 1 : return false;
1727 : :
1728 : 234 : JS::SetScriptPrivate(script, JS::ObjectValue(*priv));
1729 [ + + ]: 234 : if (!JS_ExecuteScript(m_cx, scope_chain, script, retval))
1730 : 30 : return false;
1731 : :
1732 : 203 : schedule_gc_if_needed();
1733 : :
1734 [ - + ]: 203 : if (JS_IsExceptionPending(m_cx)) {
1735 : 0 : g_warning(
1736 : : "JS::Evaluate() returned true but exception was pending; "
1737 : : "did somebody call gjs_throw() without returning false?");
1738 : 0 : return false;
1739 : : }
1740 : :
1741 : 203 : gjs_debug(GJS_DEBUG_CONTEXT, "Script evaluation succeeded");
1742 : :
1743 : 203 : return true;
1744 : 234 : }
1745 : :
1746 : : /**
1747 : : * GjsContextPrivate::call_function:
1748 : : * @this_obj: Object to use as the 'this' for the function call
1749 : : * @func_val: Callable to call, as a JS value
1750 : : * @args: Arguments to pass to the callable
1751 : : * @rval: Location for the return value
1752 : : *
1753 : : * Use this instead of JS_CallFunctionValue(), because it schedules a GC if
1754 : : * one is needed. It's good practice to check if a GC should be run every time
1755 : : * we return from JS back into C++.
1756 : : */
1757 : 2813 : bool GjsContextPrivate::call_function(JS::HandleObject this_obj,
1758 : : JS::HandleValue func_val,
1759 : : const JS::HandleValueArray& args,
1760 : : JS::MutableHandleValue rval) {
1761 [ + + ]: 2813 : if (!JS_CallFunctionValue(m_cx, this_obj, func_val, args, rval))
1762 : 21 : return false;
1763 : :
1764 : 2792 : schedule_gc_if_needed();
1765 : :
1766 : 2792 : return true;
1767 : : }
1768 : :
1769 : 1 : bool gjs_context_define_string_array(GjsContext* js_context,
1770 : : const char* array_name,
1771 : : ssize_t array_length,
1772 : : const char** array_values,
1773 : : GError** error) {
1774 : 1 : g_return_val_if_fail(GJS_IS_CONTEXT(js_context), false);
1775 : 1 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1776 : :
1777 : 1 : Gjs::AutoMainRealm ar{gjs};
1778 : :
1779 : 1 : std::vector<std::string> strings;
1780 [ + - ]: 1 : if (array_values) {
1781 [ - + ]: 1 : if (array_length < 0)
1782 : 0 : array_length = g_strv_length(const_cast<char**>(array_values));
1783 : 3 : strings = {array_values, array_values + array_length};
1784 : : }
1785 : :
1786 : : // ARGV is a special case to preserve backwards compatibility.
1787 [ + - ]: 1 : if (strcmp(array_name, "ARGV") == 0) {
1788 : 2 : gjs->set_args(std::move(strings));
1789 : :
1790 : 1 : return true;
1791 : : }
1792 : :
1793 : 0 : JS::RootedObject global_root(gjs->context(), gjs->global());
1794 [ # # ]: 0 : if (!gjs_define_string_array(gjs->context(), global_root, array_name,
1795 : : strings, JSPROP_READONLY | JSPROP_PERMANENT)) {
1796 : 0 : gjs_log_exception(gjs->context());
1797 : 0 : g_set_error(error,
1798 : : GJS_ERROR,
1799 : : GJS_ERROR_FAILED,
1800 : : "gjs_define_string_array() failed");
1801 : 0 : return false;
1802 : : }
1803 : :
1804 : 0 : return true;
1805 : 1 : }
1806 : :
1807 : 63 : void gjs_context_set_argv(GjsContext* js_context, ssize_t array_length,
1808 : : const char** array_values) {
1809 : 63 : g_return_if_fail(GJS_IS_CONTEXT(js_context));
1810 : 63 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(js_context);
1811 : 63 : std::vector<std::string> args(array_values, array_values + array_length);
1812 : 126 : gjs->set_args(std::move(args));
1813 : 63 : }
1814 : :
1815 : : static GjsContext *current_context;
1816 : :
1817 : 6932 : GjsContext* gjs_context_get_current() { return current_context; }
1818 : :
1819 : : void
1820 : 508 : gjs_context_make_current (GjsContext *context)
1821 : : {
1822 : 508 : g_assert(context == nullptr || current_context == nullptr);
1823 : :
1824 : 508 : current_context = context;
1825 : 508 : }
1826 : :
1827 : : namespace Gjs {
1828 : : /**
1829 : : * Gjs::AutoMainRealm:
1830 : : * @gjs: a #GjsContextPrivate
1831 : : *
1832 : : * Enters the realm of the "main global" for the context, and leaves when the
1833 : : * object is destructed at the end of the scope. The main global is the global
1834 : : * object under which all user JS code is executed. It is used as the root
1835 : : * object for the scope of modules loaded by GJS in this context.
1836 : : *
1837 : : * Only code in a different realm, such as the debugger code or the module
1838 : : * loader code, uses a different global object.
1839 : : */
1840 : 25356 : AutoMainRealm::AutoMainRealm(GjsContextPrivate* gjs)
1841 : 25356 : : JSAutoRealm(gjs->context(), gjs->global()) {}
1842 : :
1843 : 23555 : AutoMainRealm::AutoMainRealm(JSContext* cx)
1844 : 23555 : : AutoMainRealm(static_cast<GjsContextPrivate*>(JS_GetContextPrivate(cx))) {
1845 : 23555 : }
1846 : :
1847 : : /**
1848 : : * Gjs::AutoInternalRealm:
1849 : : * @gjs: a #GjsContextPrivate
1850 : : *
1851 : : * Enters the realm of the "internal global" for the context, and leaves when
1852 : : * the object is destructed at the end of the scope. The internal global is only
1853 : : * used for executing the module loader code, to keep it separate from user
1854 : : * code.
1855 : : */
1856 : 2550 : AutoInternalRealm::AutoInternalRealm(GjsContextPrivate* gjs)
1857 : 2550 : : JSAutoRealm(gjs->context(), gjs->internal_global()) {}
1858 : :
1859 : 2295 : AutoInternalRealm::AutoInternalRealm(JSContext* cx)
1860 : : : AutoInternalRealm(
1861 : 2295 : static_cast<GjsContextPrivate*>(JS_GetContextPrivate(cx))) {}
1862 : :
1863 : : } // namespace Gjs
1864 : :
1865 : : /**
1866 : : * gjs_context_get_profiler:
1867 : : * @self: the #GjsContext
1868 : : *
1869 : : * Returns the profiler's internal instance of #GjsProfiler for you to
1870 : : * customize, or %NULL if profiling is not enabled on this #GjsContext.
1871 : : *
1872 : : * Returns: (transfer none) (nullable): a #GjsProfiler
1873 : : */
1874 : : GjsProfiler *
1875 : 8 : gjs_context_get_profiler(GjsContext *self)
1876 : : {
1877 : 8 : return GjsContextPrivate::from_object(self)->profiler();
1878 : : }
1879 : :
1880 : : /**
1881 : : * gjs_get_js_version:
1882 : : *
1883 : : * Returns the underlying version of the JS engine.
1884 : : *
1885 : : * Returns: a string
1886 : : */
1887 : 2 : const char* gjs_get_js_version() { return JS_GetImplementationVersion(); }
1888 : :
1889 : : /**
1890 : : * gjs_context_get_repl_history_path:
1891 : : *
1892 : : * Returns the path property for persisting REPL command history
1893 : : *
1894 : : * Returns: a string
1895 : : */
1896 : 255 : const char* gjs_context_get_repl_history_path(GjsContext* self) {
1897 : 255 : return GjsContextPrivate::from_object(self)->repl_history_path();
1898 : : }
1899 : :
1900 : : /**
1901 : : * gjs_context_run_in_realm:
1902 : : * @self: the #GjsContext
1903 : : * @func: (scope call): function to run
1904 : : * @user_data: (closure func): pointer to pass to @func
1905 : : *
1906 : : * Runs @func immediately, not asynchronously, after entering the JS context's
1907 : : * main realm. After @func completes, leaves the realm again.
1908 : : *
1909 : : * You only need this if you are using JSAPI calls from the SpiderMonkey API
1910 : : * directly.
1911 : : */
1912 : 1 : void gjs_context_run_in_realm(GjsContext* self, GjsContextInRealmFunc func,
1913 : : void* user_data) {
1914 : 1 : g_return_if_fail(GJS_IS_CONTEXT(self));
1915 : 1 : g_return_if_fail(func);
1916 : :
1917 : 1 : GjsContextPrivate* gjs = GjsContextPrivate::from_object(self);
1918 : 1 : Gjs::AutoMainRealm ar{gjs};
1919 : 1 : func(self, user_data);
1920 : 1 : }
|