LCOV - code coverage report
Current view: top level - gjs - context.cpp (source / functions) Coverage Total Hit
Test: gjs- Code Coverage Lines: 81.4 % 872 710
Test Date: 2024-04-20 17:42:51 Functions: 87.0 % 92 80
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 63.4 % 350 222

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

Generated by: LCOV version 2.0-1