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