LCOV - code coverage report
Current view: top level - gjs - module.cpp (source / functions) Coverage Total Hit
Test: gjs-1.89.90 Code Coverage Lines: 89.5 % 325 291
Test Date: 2026-11-08 19:38:12 Functions: 100.0 % 27 27
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed Branches: 61.2 % 116 71

             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: 2017 Philip Chimento <philip.chimento@gmail.com>
       4                 :             : 
       5                 :             : #include <config.h>
       6                 :             : 
       7                 :             : #include <stddef.h>     // for size_t
       8                 :             : 
       9                 :             : #include <string>
      10                 :             : 
      11                 :             : #include <gio/gio.h>
      12                 :             : #include <glib-object.h>
      13                 :             : #include <glib.h>
      14                 :             : 
      15                 :             : #include <js/CallAndConstruct.h>
      16                 :             : #include <js/CallArgs.h>
      17                 :             : #include <js/CharacterEncoding.h>  // for ConstUTF8CharsZ
      18                 :             : #include <js/Class.h>
      19                 :             : #include <js/CompilationAndEvaluation.h>
      20                 :             : #include <js/CompileOptions.h>
      21                 :             : #include <js/Conversions.h>
      22                 :             : #include <js/EnvironmentChain.h>
      23                 :             : #include <js/ErrorReport.h>  // for JS_ReportOutOfMemory
      24                 :             : #include <js/Exception.h>
      25                 :             : #include <js/GlobalObject.h>  // for CurrentGlobalOrNull
      26                 :             : #include <js/Id.h>
      27                 :             : #include <js/Modules.h>
      28                 :             : #include <js/Object.h>
      29                 :             : #include <js/Promise.h>
      30                 :             : #include <js/PropertyAndElement.h>
      31                 :             : #include <js/PropertyDescriptor.h>
      32                 :             : #include <js/RootingAPI.h>
      33                 :             : #include <js/ScriptPrivate.h>
      34                 :             : #include <js/SourceText.h>
      35                 :             : #include <js/String.h>
      36                 :             : #include <js/TypeDecls.h>
      37                 :             : #include <js/Utility.h>  // for UniqueChars
      38                 :             : #include <js/Value.h>
      39                 :             : #include <js/ValueArray.h>
      40                 :             : #include <jsapi.h>        // for JS_GetFunctionObject, JS_Ne...
      41                 :             : #include <jsfriendapi.h>  // for NewFunctionWithReserved
      42                 :             : #include <mozilla/Maybe.h>
      43                 :             : 
      44                 :             : #include "gjs/atoms.h"
      45                 :             : #include "gjs/auto.h"
      46                 :             : #include "gjs/context-private.h"
      47                 :             : #include "gjs/deprecation.h"
      48                 :             : #include "gjs/gerror-result.h"
      49                 :             : #include "gjs/global.h"
      50                 :             : #include "gjs/jsapi-util-args.h"
      51                 :             : #include "gjs/jsapi-util.h"
      52                 :             : #include "gjs/macros.h"
      53                 :             : #include "gjs/mem-private.h"
      54                 :             : #include "gjs/module.h"
      55                 :             : #include "gjs/native.h"
      56                 :             : #include "util/log.h"
      57                 :             : #include "util/misc.h"
      58                 :             : 
      59                 :             : namespace mozilla {
      60                 :             : union Utf8Unit;
      61                 :             : }
      62                 :             : 
      63                 :             : class GjsScriptModule {
      64                 :             :     std::string m_name;
      65                 :             : 
      66                 :             :     // Reserved slots
      67                 :             :     static const size_t POINTER = 0;
      68                 :             : 
      69                 :         880 :     explicit GjsScriptModule(std::string_view name) : m_name(name) {
      70                 :         440 :         GJS_INC_COUNTER(module);
      71                 :         440 :     }
      72                 :             : 
      73                 :         434 :     ~GjsScriptModule() { GJS_DEC_COUNTER(module); }
      74                 :             : 
      75                 :             :     // Private data accessors
      76                 :             : 
      77                 :             :     [[nodiscard]]
      78                 :      289200 :     static GjsScriptModule* priv(JSObject* module) {
      79                 :      289200 :         return JS::GetMaybePtrFromReservedSlot<GjsScriptModule>(
      80                 :      289200 :             module, GjsScriptModule::POINTER);
      81                 :             :     }
      82                 :             : 
      83                 :             :     // Creates a JS module object. Use instead of the class's constructor
      84                 :             :     [[nodiscard]]
      85                 :         440 :     static JSObject* create(JSContext* cx, std::string_view name) {
      86                 :         440 :         JSObject* module = JS_NewObject(cx, &GjsScriptModule::klass);
      87                 :         440 :         JS::SetReservedSlot(module, GjsScriptModule::POINTER,
      88                 :         440 :                             JS::PrivateValue(new GjsScriptModule(name)));
      89                 :         440 :         return module;
      90                 :             :     }
      91                 :             : 
      92                 :             :     // Defines the empty module as a property on the importer
      93                 :             :     GJS_JSAPI_RETURN_CONVENTION
      94                 :         440 :     bool define_import(JSContext* cx, JS::HandleObject module,
      95                 :             :                        JS::HandleObject importer, JS::HandleId name) const {
      96         [ -  + ]:         440 :         if (!JS_DefinePropertyById(cx, importer, name, module,
      97                 :             :                                    GJS_MODULE_PROP_FLAGS & ~JSPROP_PERMANENT)) {
      98                 :           0 :             gjs_debug(GJS_DEBUG_IMPORTER, "Failed to define '{}' in importer",
      99                 :           0 :                       m_name);
     100                 :           0 :             return false;
     101                 :             :         }
     102                 :             : 
     103                 :         440 :         return true;
     104                 :             :     }
     105                 :             : 
     106                 :             :     // Carries out the actual execution of the module code
     107                 :             :     GJS_JSAPI_RETURN_CONVENTION
     108                 :         440 :     bool evaluate_import(JSContext* cx, JS::HandleObject module,
     109                 :             :                          const char* source, size_t source_len,
     110                 :             :                          const char* filename, const char* uri) {
     111                 :         440 :         JS::SourceText<mozilla::Utf8Unit> buf;
     112         [ -  + ]:         440 :         if (!buf.init(cx, source, source_len, JS::SourceOwnership::Borrowed))
     113                 :           0 :             return false;
     114                 :             : 
     115                 :         440 :         JS::EnvironmentChain scope_chain{cx, JS::SupportUnscopables::No};
     116         [ -  + ]:         440 :         if (!scope_chain.append(module)) {
     117                 :           0 :             JS_ReportOutOfMemory(cx);
     118                 :           0 :             return false;
     119                 :             :         }
     120                 :             : 
     121                 :         440 :         JS::CompileOptions options(cx);
     122                 :         440 :         options.setFileAndLine(filename, 1).setNonSyntacticScope(true);
     123                 :             : 
     124                 :         440 :         JS::RootedObject priv(cx, build_private(cx, uri));
     125         [ -  + ]:         440 :         if (!priv)
     126                 :           0 :             return false;
     127                 :             : 
     128                 :         440 :         JS::RootedScript script(cx, JS::Compile(cx, options, buf));
     129         [ +  + ]:         440 :         if (!script)
     130                 :           1 :             return false;
     131                 :             : 
     132                 :         439 :         JS::SetScriptPrivate(script, JS::ObjectValue(*priv));
     133                 :         439 :         JS::RootedValue ignored_retval(cx);
     134         [ +  + ]:         439 :         if (!JS_ExecuteScript(cx, scope_chain, script, &ignored_retval))
     135                 :           3 :             return false;
     136                 :             : 
     137                 :         436 :         GjsContextPrivate* gjs = GjsContextPrivate::from_cx(cx);
     138                 :         436 :         gjs->schedule_gc_if_needed();
     139                 :             : 
     140                 :         436 :         gjs_debug(GJS_DEBUG_IMPORTER, "Importing module {} succeeded", m_name);
     141                 :             : 
     142                 :         436 :         return true;
     143                 :         440 :     }
     144                 :             : 
     145                 :             :     // Loads JS code from a file and imports it
     146                 :             :     GJS_JSAPI_RETURN_CONVENTION
     147                 :         440 :     bool import_file(JSContext* cx, JS::HandleObject module, GFile* file) {
     148                 :         440 :         Gjs::AutoError error;
     149                 :         440 :         Gjs::AutoChar script;
     150                 :         440 :         size_t script_len = 0;
     151                 :             : 
     152         [ -  + ]:         440 :         if (!(g_file_load_contents(file, nullptr, script.out(), &script_len,
     153                 :             :                                    nullptr, &error)))
     154                 :           0 :             return gjs_throw_gerror_message(cx, error);
     155                 :         440 :         g_assert(script);
     156                 :             : 
     157                 :         440 :         Gjs::AutoChar full_path{g_file_get_parse_name(file)};
     158                 :         440 :         Gjs::AutoChar uri{g_file_get_uri(file)};
     159                 :         440 :         return evaluate_import(cx, module, script, script_len, full_path, uri);
     160                 :         440 :     }
     161                 :             : 
     162                 :             :     // JSClass operations
     163                 :             : 
     164                 :             :     GJS_JSAPI_RETURN_CONVENTION
     165                 :      287886 :     bool resolve_impl(JSContext* cx, JS::HandleObject module, JS::HandleId id,
     166                 :             :                       bool* resolved) {
     167                 :      287886 :         JS::RootedObject lexical(cx, JS_ExtensibleLexicalEnvironment(module));
     168         [ -  + ]:      287886 :         if (!lexical) {
     169                 :           0 :             *resolved = false;
     170                 :           0 :             return true;  // nothing imported yet
     171                 :             :         }
     172                 :             : 
     173                 :      287886 :         JS::Rooted<mozilla::Maybe<JS::PropertyDescriptor>> maybe_desc(cx);
     174                 :      287886 :         JS::RootedObject holder(cx);
     175         [ -  + ]:      287886 :         if (!JS_GetPropertyDescriptorById(cx, lexical, id, &maybe_desc,
     176                 :      287886 :                                           &holder))
     177                 :           0 :             return false;
     178         [ +  + ]:      287886 :         if (maybe_desc.isNothing())
     179                 :      287884 :             return true;
     180                 :             : 
     181                 :             :         /* The property is present in the lexical environment. This should not
     182                 :             :          * be supported according to ES6. For compatibility with earlier GJS, we
     183                 :             :          * treat it as if it were a real property, but warn about it. */
     184                 :             : 
     185                 :             :         gjs_warn_deprecated_once_per_callsite<
     186                 :           2 :             GjsDeprecationMessageId::ModuleExportedLetOrConst>(cx, id, m_name);
     187                 :             : 
     188                 :           2 :         JS::Rooted<JS::PropertyDescriptor> desc(cx, maybe_desc.value());
     189                 :           2 :         return JS_DefinePropertyById(cx, module, id, desc);
     190                 :      287886 :     }
     191                 :             : 
     192                 :             :     GJS_JSAPI_RETURN_CONVENTION
     193                 :      287886 :     static bool resolve(JSContext* cx, JS::HandleObject module, JS::HandleId id,
     194                 :             :                         bool* resolved) {
     195                 :      287886 :         return priv(module)->resolve_impl(cx, module, id, resolved);
     196                 :             :     }
     197                 :             : 
     198                 :         434 :     static void finalize(JS::GCContext*, JSObject* module) {
     199         [ +  - ]:         434 :         delete priv(module);
     200                 :         434 :     }
     201                 :             : 
     202                 :             :     static constexpr JSClassOps class_ops = {
     203                 :             :         .resolve = &GjsScriptModule::resolve,
     204                 :             :         .finalize = &GjsScriptModule::finalize};
     205                 :             : 
     206                 :             :     static constexpr JSClass klass = {
     207                 :             :         .name = "GjsScriptModule",
     208                 :             :         .flags = JSCLASS_HAS_RESERVED_SLOTS(1) | JSCLASS_BACKGROUND_FINALIZE,
     209                 :             :         .cOps = &GjsScriptModule::class_ops};
     210                 :             : 
     211                 :             :  public:
     212                 :             :     /* Creates a JS object to pass to JS::SetScriptPrivate as a script's
     213                 :             :      * private.
     214                 :             :      */
     215                 :             :     GJS_JSAPI_RETURN_CONVENTION
     216                 :         670 :     static JSObject* build_private(JSContext* cx, const char* script_uri) {
     217                 :         670 :         JS::RootedObject priv(cx, JS_NewPlainObject(cx));
     218                 :         670 :         const GjsAtoms& atoms = GjsContextPrivate::atoms(cx);
     219                 :             : 
     220                 :         670 :         JS::RootedValue val(cx);
     221         [ +  - ]:        1340 :         if (!gjs_string_from_utf8(cx, script_uri, &val) ||
     222   [ -  +  -  + ]:        1340 :             !JS_SetPropertyById(cx, priv, atoms.uri(), val))
     223                 :           0 :             return nullptr;
     224                 :             : 
     225                 :         670 :         return priv;
     226                 :         670 :     }
     227                 :             : 
     228                 :             :     // Carries out the import operation
     229                 :             :     GJS_JSAPI_RETURN_CONVENTION
     230                 :         440 :     static JSObject* import(JSContext* cx, JS::HandleObject importer,
     231                 :             :                             JS::HandleId id, std::string_view name,
     232                 :             :                             GFile* file) {
     233                 :         440 :         JS::RootedObject module(cx, GjsScriptModule::create(cx, name));
     234                 :         440 :         if (!module ||
     235   [ +  -  +  - ]:         880 :             !priv(module)->define_import(cx, module, importer, id) ||
     236   [ +  +  +  + ]:         880 :             !priv(module)->import_file(cx, module, file))
     237                 :           4 :             return nullptr;
     238                 :             : 
     239                 :         436 :         return module;
     240                 :         440 :     }
     241                 :             : 
     242                 :             :     GjsScriptModule(GjsScriptModule&) = delete;
     243                 :             :     GjsScriptModule& operator=(GjsScriptModule&) = delete;
     244                 :             : };
     245                 :             : 
     246                 :             : /**
     247                 :             :  * gjs_script_module_build_private:
     248                 :             :  * @cx: the #JSContext
     249                 :             :  * @uri: the URI this script module is loaded from
     250                 :             :  *
     251                 :             :  * To support dynamic imports from scripts, we need to provide private data when
     252                 :             :  * we compile scripts which is compatible with our module resolution hooks in
     253                 :             :  * modules/internal/loader.js
     254                 :             :  *
     255                 :             :  * Returns: a JSObject which can be used for a JSScript's private data.
     256                 :             :  */
     257                 :         230 : JSObject* gjs_script_module_build_private(JSContext* cx, const char* uri) {
     258                 :         230 :     return GjsScriptModule::build_private(cx, uri);
     259                 :             : }
     260                 :             : 
     261                 :             : /**
     262                 :             :  * gjs_module_import:
     263                 :             :  * @cx: the JS context
     264                 :             :  * @importer: the JS importer object, parent of the module to be imported
     265                 :             :  * @id: module name in the form of a jsid
     266                 :             :  * @name: module name, used for logging and identification
     267                 :             :  * @file: location of the file to import
     268                 :             :  *
     269                 :             :  * Carries out an import of a GJS module.
     270                 :             :  * Defines a property @name on @importer pointing to the module object, which
     271                 :             :  * is necessary in the case of cyclic imports.
     272                 :             :  * This property is not permanent; the caller is responsible for making it
     273                 :             :  * permanent if the import succeeds.
     274                 :             :  *
     275                 :             :  * Returns: the JS module object, or nullptr on failure.
     276                 :             :  */
     277                 :         440 : JSObject* gjs_module_import(JSContext* cx, JS::HandleObject importer,
     278                 :             :                             JS::HandleId id, std::string_view name,
     279                 :             :                             GFile* file) {
     280                 :         440 :     return GjsScriptModule::import(cx, importer, id, name, file);
     281                 :             : }
     282                 :             : 
     283                 :             : /**
     284                 :             :  * gjs_get_native_registry:
     285                 :             :  * @global: The JS global object
     286                 :             :  *
     287                 :             :  * Retrieves a global's native registry from the NATIVE_REGISTRY slot.
     288                 :             :  * Registries are JS Map objects created with JS::NewMapObject instead of
     289                 :             :  * GCHashMaps (used elsewhere in GJS) because the objects need to be exposed to
     290                 :             :  * internal JS code and accessed from native C++ code.
     291                 :             :  *
     292                 :             :  * Returns: the native module registry, a JS Map object.
     293                 :             :  */
     294                 :       37271 : JSObject* gjs_get_native_registry(JSObject* global) {
     295                 :       37271 :     JS::Value native_registry =
     296                 :       37271 :         gjs_get_global_slot(global, GjsGlobalSlot::NATIVE_REGISTRY);
     297                 :             : 
     298                 :       37271 :     g_assert(native_registry.isObject());
     299                 :       37271 :     return &native_registry.toObject();
     300                 :             : }
     301                 :             : 
     302                 :             : /**
     303                 :             :  * gjs_get_module_registry:
     304                 :             :  * @global: the JS global object
     305                 :             :  *
     306                 :             :  * Retrieves a global's module registry from the MODULE_REGISTRY slot.
     307                 :             :  * Registries are JS Maps. See gjs_get_native_registry() for more detail.
     308                 :             :  *
     309                 :             :  * Returns: the module registry, a JS Map object
     310                 :             :  */
     311                 :       14615 : JSObject* gjs_get_module_registry(JSObject* global) {
     312                 :       14615 :     JS::Value esm_registry =
     313                 :       14615 :         gjs_get_global_slot(global, GjsGlobalSlot::MODULE_REGISTRY);
     314                 :             : 
     315                 :       14615 :     g_assert(esm_registry.isObject());
     316                 :       14615 :     return &esm_registry.toObject();
     317                 :             : }
     318                 :             : 
     319                 :             : /**
     320                 :             :  * gjs_get_source_map_registry:
     321                 :             :  * @global: The JS global object
     322                 :             :  *
     323                 :             :  * Retrieves a global's source map registry from the SOURCE_MAP_REGISTRY slot.
     324                 :             :  * Registries are JS Maps.
     325                 :             :  *
     326                 :             :  * Returns: the source map registry, a JS Map object
     327                 :             :  */
     328                 :         266 : JSObject* gjs_get_source_map_registry(JSObject* global) {
     329                 :         266 :     JS::Value source_map_registry =
     330                 :         266 :         gjs_get_global_slot(global, GjsGlobalSlot::SOURCE_MAP_REGISTRY);
     331                 :             : 
     332                 :         266 :     g_assert(source_map_registry.isObject());
     333                 :         266 :     return &source_map_registry.toObject();
     334                 :             : }
     335                 :             : 
     336                 :             : /**
     337                 :             :  * gjs_module_load:
     338                 :             :  * @cx: the current JSContext
     339                 :             :  * @identifier: specifier of the module to load
     340                 :             :  * @file_uri: URI to load the module from
     341                 :             :  *
     342                 :             :  * Loads and registers a module given a specifier and URI.
     343                 :             :  *
     344                 :             :  * Returns: whether an error occurred while resolving the specifier.
     345                 :             :  */
     346                 :         745 : JSObject* gjs_module_load(JSContext* cx, const char* identifier,
     347                 :             :                           const char* file_uri) {
     348                 :         745 :     g_assert((gjs_global_is_type(cx, GjsGlobalType::DEFAULT) ||
     349                 :             :               gjs_global_is_type(cx, GjsGlobalType::INTERNAL)) &&
     350                 :             :              "gjs_module_load can only be called from module-enabled "
     351                 :             :              "globals.");
     352                 :             : 
     353                 :         745 :     JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
     354                 :         745 :     JS::RootedValue v_loader(
     355                 :         745 :         cx, gjs_get_global_slot(global, GjsGlobalSlot::MODULE_LOADER));
     356                 :         745 :     g_assert(v_loader.isObject());
     357                 :         745 :     JS::RootedObject loader(cx, &v_loader.toObject());
     358                 :             : 
     359                 :         745 :     JS::ConstUTF8CharsZ id_chars{identifier};
     360                 :         745 :     JS::ConstUTF8CharsZ uri_chars{file_uri};
     361                 :         745 :     JS::RootedString id(cx, JS_NewStringCopyUTF8Z(cx, id_chars));
     362         [ -  + ]:         745 :     if (!id)
     363                 :           0 :         return nullptr;
     364                 :         745 :     JS::RootedString uri(cx, JS_NewStringCopyUTF8Z(cx, uri_chars));
     365         [ -  + ]:         745 :     if (!uri)
     366                 :           0 :         return nullptr;
     367                 :             : 
     368                 :         745 :     JS::RootedValueArray<2> args(cx);
     369                 :         745 :     args[0].setString(id);
     370                 :         745 :     args[1].setString(uri);
     371                 :             : 
     372                 :         745 :     gjs_debug(GJS_DEBUG_IMPORTER,
     373                 :             :               "Module load hook for module '{}' ({}), global {:?}", identifier,
     374                 :             :               file_uri, global);
     375                 :             : 
     376                 :         745 :     JS::RootedValue result(cx);
     377         [ +  + ]:         745 :     if (!JS::Call(cx, loader, "moduleLoadHook", args, &result))
     378                 :           1 :         return nullptr;
     379                 :             : 
     380                 :         744 :     g_assert(result.isObject() && "Module hook failed to return an object!");
     381                 :         744 :     return &result.toObject();
     382                 :         745 : }
     383                 :             : 
     384                 :             : /**
     385                 :             :  * import_native_module_sync:
     386                 :             :  * @identifier: the specifier for the module to import
     387                 :             :  *
     388                 :             :  * JS function exposed as `import.meta.importSync` in internal modules only.
     389                 :             :  *
     390                 :             :  * Synchronously imports native "modules" from the import global's
     391                 :             :  * native registry. This function does not do blocking I/O so it is
     392                 :             :  * safe to call it synchronously for accessing native "modules" within
     393                 :             :  * modules. This function is always called within the import global's
     394                 :             :  * realm.
     395                 :             :  *
     396                 :             :  * Compare gjs_import_native_module() for the legacy importer.
     397                 :             :  *
     398                 :             :  * Returns: the imported JS module object.
     399                 :             :  */
     400                 :       10672 : static bool import_native_module_sync(JSContext* cx, unsigned argc,
     401                 :             :                                       JS::Value* vp) {
     402                 :       10672 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     403                 :       10672 :     JS::UniqueChars id;
     404         [ -  + ]:       10672 :     if (!gjs_parse_call_args(cx, "importSync", args, "s", "identifier", &id))
     405                 :           0 :         return false;
     406                 :             : 
     407                 :       10672 :     Gjs::AutoMainRealm ar{cx};
     408                 :       10672 :     JS::RootedObject global{cx, JS::CurrentGlobalOrNull(cx)};
     409                 :             : 
     410                 :       10672 :     JS::AutoSaveExceptionState exc_state(cx);
     411                 :             : 
     412                 :       10672 :     JS::RootedObject native_registry(cx, gjs_get_native_registry(global));
     413                 :       10672 :     JS::RootedObject v_module(cx);
     414                 :             : 
     415                 :       10672 :     JS::RootedId key(cx, gjs_intern_string_to_id(cx, id.get()));
     416         [ -  + ]:       10672 :     if (!gjs_global_registry_get(cx, native_registry, key, &v_module))
     417                 :           0 :         return false;
     418                 :             : 
     419         [ +  + ]:       10672 :     if (v_module) {
     420                 :       10550 :         args.rval().setObject(*v_module);
     421                 :       10550 :         return true;
     422                 :             :     }
     423                 :             : 
     424                 :         122 :     JS::RootedObject native_obj(cx);
     425         [ -  + ]:         244 :     if (!Gjs::NativeModuleDefineFuncs::get().define(cx, id.get(),
     426                 :         122 :                                                     &native_obj)) {
     427                 :           0 :         gjs_throw(cx, "Failed to load native module: {}", id);
     428                 :           0 :         return false;
     429                 :             :     }
     430                 :             : 
     431         [ -  + ]:         122 :     if (!gjs_global_registry_set(cx, native_registry, key, native_obj))
     432                 :           0 :         return false;
     433                 :             : 
     434                 :         122 :     args.rval().setObject(*native_obj);
     435                 :         122 :     return true;
     436                 :       10672 : }
     437                 :             : 
     438                 :             : /**
     439                 :             :  * gjs_populate_module_meta:
     440                 :             :  * @cx: the current JSContext
     441                 :             :  * @private_ref: the JS private value for the #Module object, as a JS Object
     442                 :             :  * @meta: the JS `import.meta` object
     443                 :             :  *
     444                 :             :  * Hook SpiderMonkey calls to populate the `import.meta` object.
     445                 :             :  * Defines a property `import.meta.url`, and additionally a method
     446                 :             :  * `import.meta.importSync` if this is an internal module.
     447                 :             :  *
     448                 :             :  * Returns: whether an error occurred while populating the module meta.
     449                 :             :  */
     450                 :         182 : bool gjs_populate_module_meta(JSContext* cx, JS::HandleValue private_ref,
     451                 :             :                               JS::HandleObject meta) {
     452                 :         182 :     g_assert(private_ref.isObject());
     453                 :         182 :     JS::RootedObject module(cx, &private_ref.toObject());
     454                 :             : 
     455                 :         364 :     gjs_debug(GJS_DEBUG_IMPORTER, "Module metadata hook for module {:?}",
     456                 :         182 :               &private_ref.toObject());
     457                 :             : 
     458                 :         182 :     const GjsAtoms& atoms = GjsContextPrivate::atoms(cx);
     459                 :         182 :     JS::RootedValue specifier{cx};
     460         [ +  - ]:         364 :     if (!JS_GetProperty(cx, module, "id", &specifier) ||
     461   [ -  +  -  + ]:         364 :         !JS_DefinePropertyById(cx, meta, atoms.url(), specifier,
     462                 :             :                                GJS_MODULE_PROP_FLAGS))
     463                 :           0 :         return false;
     464                 :             : 
     465                 :         182 :     JS::RootedValue v_internal(cx);
     466         [ -  + ]:         182 :     if (!JS_GetPropertyById(cx, module, atoms.internal(), &v_internal))
     467                 :           0 :         return false;
     468         [ +  + ]:         182 :     if (JS::ToBoolean(v_internal)) {
     469                 :         354 :         gjs_debug(GJS_DEBUG_IMPORTER,
     470                 :             :                   "Defining meta.importSync for module {:?}",
     471                 :         177 :                   &private_ref.toObject());
     472         [ -  + ]:         177 :         if (!JS_DefineFunctionById(cx, meta, atoms.importSync(),
     473                 :             :                                    import_native_module_sync, 1,
     474                 :             :                                    GJS_MODULE_PROP_FLAGS))
     475                 :           0 :             return false;
     476                 :             :     }
     477                 :             : 
     478                 :         182 :     return true;
     479                 :         182 : }
     480                 :             : 
     481                 :             : // Canonicalize specifier so that differently-spelled specifiers referring to
     482                 :             : // the same module don't result in duplicate entries in the registry
     483                 :       13413 : static bool canonicalize_specifier(JSContext* cx,
     484                 :             :                                    JS::MutableHandleString specifier) {
     485                 :       13413 :     JS::UniqueChars specifier_utf8 = JS_EncodeStringToUTF8(cx, specifier);
     486         [ -  + ]:       13413 :     if (!specifier_utf8)
     487                 :           0 :         return false;
     488                 :             : 
     489                 :       13413 :     Gjs::AutoChar scheme, host, path, query;
     490         [ -  + ]:       13413 :     if (!g_uri_split(specifier_utf8.get(), G_URI_FLAGS_NONE, scheme.out(),
     491                 :             :                      nullptr, host.out(), nullptr, path.out(), query.out(),
     492                 :             :                      nullptr, nullptr))
     493                 :           0 :         return false;
     494                 :             : 
     495         [ +  + ]:       13413 :     if (g_strcmp0(scheme, "gi")) {
     496                 :             :         // canonicalize without the query portion to avoid it being encoded
     497                 :       12788 :         Gjs::AutoChar for_file_uri{g_uri_join(G_URI_FLAGS_NONE, scheme.get(),
     498                 :       12788 :                                               nullptr, host.get(), -1,
     499                 :       25576 :                                               path.get(), nullptr, nullptr)};
     500                 :       12788 :         Gjs::AutoUnref<GFile> file{g_file_new_for_uri(for_file_uri.get())};
     501                 :       12788 :         for_file_uri = g_file_get_uri(file);
     502                 :       12788 :         host.reset();
     503                 :       12788 :         path.reset();
     504         [ -  + ]:       12788 :         if (!g_uri_split(for_file_uri.get(), G_URI_FLAGS_NONE, nullptr, nullptr,
     505                 :             :                          host.out(), nullptr, path.out(), nullptr, nullptr,
     506                 :             :                          nullptr))
     507                 :           0 :             return false;
     508   [ +  -  +  - ]:       25576 :     }
     509                 :             : 
     510                 :       13413 :     Gjs::AutoChar canonical_specifier{
     511                 :       13413 :         g_uri_join(G_URI_FLAGS_NONE, scheme.get(), nullptr, host.get(), -1,
     512                 :       26826 :                    path.get(), query.get(), nullptr)};
     513                 :       13413 :     JS::ConstUTF8CharsZ chars{canonical_specifier};
     514                 :       13413 :     JS::RootedString new_specifier{cx, JS_NewStringCopyUTF8Z(cx, chars)};
     515         [ -  + ]:       13413 :     if (!new_specifier)
     516                 :           0 :         return false;
     517                 :             : 
     518                 :       13413 :     specifier.set(new_specifier);
     519                 :       13413 :     return true;
     520                 :       13413 : }
     521                 :             : 
     522                 :             : /**
     523                 :             :  * gjs_module_resolve:
     524                 :             :  * @cx: the current JSContext
     525                 :             :  * @importing_module_priv: the private JS Object of the #Module object
     526                 :             :  *   initiating the import, or a JS null value
     527                 :             :  * @module_request: the module request object
     528                 :             :  *
     529                 :             :  * This function resolves import specifiers. It is called internally by
     530                 :             :  * SpiderMonkey as a hook.
     531                 :             :  *
     532                 :             :  * Returns: whether an error occurred while resolving the specifier.
     533                 :             :  */
     534                 :       13366 : JSObject* gjs_module_resolve(JSContext* cx,
     535                 :             :                              JS::HandleValue importing_module_priv,
     536                 :             :                              JS::HandleObject module_request) {
     537                 :       13366 :     g_assert((gjs_global_is_type(cx, GjsGlobalType::DEFAULT) ||
     538                 :             :               gjs_global_is_type(cx, GjsGlobalType::INTERNAL)) &&
     539                 :             :              "gjs_module_resolve can only be called from module-enabled "
     540                 :             :              "globals.");
     541                 :       13366 :     JS::RootedString specifier(
     542                 :       13366 :         cx, JS::GetModuleRequestSpecifier(cx, module_request));
     543                 :             : 
     544                 :       13366 :     JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
     545                 :       13366 :     JS::RootedValue v_loader(
     546                 :       13366 :         cx, gjs_get_global_slot(global, GjsGlobalSlot::MODULE_LOADER));
     547                 :       13366 :     g_assert(v_loader.isObject());
     548                 :       13366 :     JS::RootedObject loader(cx, &v_loader.toObject());
     549                 :             : 
     550         [ -  + ]:       13366 :     if (!canonicalize_specifier(cx, &specifier))
     551                 :           0 :         return nullptr;
     552                 :             : 
     553                 :       13366 :     JS::RootedValueArray<2> args(cx);
     554                 :       13366 :     args[0].set(importing_module_priv);
     555                 :       13366 :     args[1].setString(specifier);
     556                 :             : 
     557                 :       13366 :     gjs_debug(GJS_DEBUG_IMPORTER,
     558                 :             :               "Module resolve hook for module {} (relative to {}), global {:?}",
     559                 :             :               specifier, importing_module_priv, global);
     560                 :             : 
     561                 :       13366 :     JS::RootedValue result(cx);
     562         [ +  + ]:       13366 :     if (!JS::Call(cx, loader, "moduleResolveHook", args, &result))
     563                 :           4 :         return nullptr;
     564                 :             : 
     565                 :       13362 :     g_assert(result.isObject() && "resolve hook failed to return an object!");
     566                 :       13362 :     return &result.toObject();
     567                 :       13366 : }
     568                 :             : 
     569                 :             : // Call JS::FinishDynamicModuleImport() with the values stashed in the function.
     570                 :             : // Can fail in JS::FinishDynamicModuleImport(), but will assert if anything
     571                 :             : // fails in fetching the stashed values, since that would be a serious GJS bug.
     572                 :             : GJS_JSAPI_RETURN_CONVENTION
     573                 :          47 : static bool finish_import(JSContext* cx, JS::HandleObject evaluation_promise,
     574                 :             :                           const JS::CallArgs& args) {
     575                 :          47 :     GjsContextPrivate* priv = GjsContextPrivate::from_cx(cx);
     576                 :          47 :     priv->main_loop_release();
     577                 :             : 
     578                 :          47 :     JS::Value callback_priv = js::GetFunctionNativeReserved(&args.callee(), 0);
     579                 :          47 :     g_assert(callback_priv.isObject() && "Wrong private value");
     580                 :          47 :     JS::RootedObject callback_data(cx, &callback_priv.toObject());
     581                 :             : 
     582                 :          47 :     JS::RootedValue importing_module_priv(cx);
     583                 :          47 :     JS::RootedValue v_module_request(cx);
     584                 :          47 :     JS::RootedValue v_internal_promise(cx);
     585                 :             :     bool ok GJS_USED_ASSERT =
     586         [ +  - ]:          94 :         JS_GetProperty(cx, callback_data, "priv", &importing_module_priv) &&
     587   [ +  -  +  - ]:          94 :         JS_GetProperty(cx, callback_data, "promise", &v_internal_promise) &&
     588                 :          47 :         JS_GetProperty(cx, callback_data, "module_request", &v_module_request);
     589                 :          47 :     g_assert(ok && "Wrong properties on private value");
     590                 :             : 
     591                 :          47 :     g_assert(v_module_request.isObject() && "Wrong type for module request");
     592                 :          47 :     g_assert(v_internal_promise.isObject() && "Wrong type for promise");
     593                 :             : 
     594                 :          47 :     JS::RootedObject module_request(cx, &v_module_request.toObject());
     595                 :          47 :     JS::RootedObject internal_promise(cx, &v_internal_promise.toObject());
     596                 :             : 
     597                 :          47 :     args.rval().setUndefined();
     598                 :             : 
     599                 :          47 :     return JS::FinishDynamicModuleImport(cx, evaluation_promise,
     600                 :          47 :                                          importing_module_priv, module_request,
     601                 :          94 :                                          internal_promise);
     602                 :          47 : }
     603                 :             : 
     604                 :             : // Failing a JSAPI function may result either in an exception pending on the
     605                 :             : // context, in which case we must call JS::FinishDynamicModuleImport() to reject
     606                 :             : // the internal promise; or in an uncatchable exception such as OOM, in which
     607                 :             : // case we must not call JS::FinishDynamicModuleImport().
     608                 :             : GJS_JSAPI_RETURN_CONVENTION
     609                 :           2 : static bool fail_import(JSContext* cx, const JS::CallArgs& args) {
     610         [ +  - ]:           2 :     if (JS_IsExceptionPending(cx))
     611                 :           2 :         return finish_import(cx, nullptr, args);
     612                 :           0 :     return false;
     613                 :             : }
     614                 :             : 
     615                 :             : GJS_JSAPI_RETURN_CONVENTION
     616                 :           6 : static bool import_rejected(JSContext* cx, unsigned argc, JS::Value* vp) {
     617                 :           6 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     618                 :             : 
     619                 :           6 :     gjs_debug(GJS_DEBUG_IMPORTER, "Async import promise rejected");
     620                 :             : 
     621                 :             :     // Throw the value that the promise is rejected with, so that
     622                 :             :     // FinishDynamicModuleImport will reject the internal_promise with it.
     623                 :           6 :     JS_SetPendingException(cx, args.get(0),
     624                 :             :                            JS::ExceptionStackBehavior::DoNotCapture);
     625                 :             : 
     626                 :           6 :     return finish_import(cx, nullptr, args);
     627                 :             : }
     628                 :             : 
     629                 :             : GJS_JSAPI_RETURN_CONVENTION
     630                 :          41 : static bool import_resolved(JSContext* cx, unsigned argc, JS::Value* vp) {
     631                 :          41 :     JS::CallArgs args = JS::CallArgsFromVp(argc, vp);
     632                 :             : 
     633                 :          41 :     gjs_debug(GJS_DEBUG_IMPORTER, "Async import promise resolved");
     634                 :             : 
     635                 :          41 :     Gjs::AutoMainRealm ar{cx};
     636                 :             : 
     637                 :          41 :     g_assert(args[0].isObject());
     638                 :          41 :     JS::RootedObject module(cx, &args[0].toObject());
     639                 :             : 
     640                 :          41 :     JS::RootedValue evaluation_promise(cx);
     641         [ +  + ]:          80 :     if (!JS::ModuleLink(cx, module) ||
     642   [ -  +  +  + ]:          80 :         !JS::ModuleEvaluate(cx, module, &evaluation_promise))
     643                 :           2 :         return fail_import(cx, args);
     644                 :             : 
     645                 :          39 :     g_assert(evaluation_promise.isObject() &&
     646                 :             :              "got weird value from JS::ModuleEvaluate");
     647                 :          39 :     JS::RootedObject evaluation_promise_object(cx,
     648                 :          39 :                                                &evaluation_promise.toObject());
     649                 :          39 :     return finish_import(cx, evaluation_promise_object, args);
     650                 :          41 : }
     651                 :             : 
     652                 :          47 : bool gjs_dynamic_module_resolve(JSContext* cx,
     653                 :             :                                 JS::HandleValue importing_module_priv,
     654                 :             :                                 JS::HandleObject module_request,
     655                 :             :                                 JS::HandleObject internal_promise) {
     656                 :          47 :     g_assert(gjs_global_is_type(cx, GjsGlobalType::DEFAULT) &&
     657                 :             :              "gjs_dynamic_module_resolve can only be called from the default "
     658                 :             :              "global.");
     659                 :             : 
     660                 :          47 :     JS::RootedObject global(cx, JS::CurrentGlobalOrNull(cx));
     661                 :          47 :     g_assert(global && "gjs_dynamic_module_resolve must be in a realm");
     662                 :             : 
     663                 :          47 :     JS::RootedValue v_loader(
     664                 :          47 :         cx, gjs_get_global_slot(global, GjsGlobalSlot::MODULE_LOADER));
     665                 :          47 :     g_assert(v_loader.isObject());
     666                 :          47 :     JS::RootedObject loader(cx, &v_loader.toObject());
     667                 :          47 :     JS::RootedString specifier(
     668                 :          47 :         cx, JS::GetModuleRequestSpecifier(cx, module_request));
     669                 :             : 
     670         [ -  + ]:          47 :     if (!canonicalize_specifier(cx, &specifier))
     671                 :           0 :         return false;
     672                 :             : 
     673                 :          47 :     JS::RootedObject callback_data(cx, JS_NewPlainObject(cx));
     674                 :          47 :     if (!callback_data ||
     675         [ +  - ]:          47 :         !JS_DefineProperty(cx, callback_data, "module_request", module_request,
     676                 :          47 :                            JSPROP_PERMANENT) ||
     677         [ +  - ]:          47 :         !JS_DefineProperty(cx, callback_data, "promise", internal_promise,
     678         [ +  - ]:          94 :                            JSPROP_PERMANENT) ||
     679   [ -  +  -  + ]:          94 :         !JS_DefineProperty(cx, callback_data, "priv", importing_module_priv,
     680                 :             :                            JSPROP_PERMANENT))
     681                 :           0 :         return false;
     682                 :             : 
     683         [ +  + ]:          47 :     if (importing_module_priv.isObject()) {
     684                 :          88 :         gjs_debug(GJS_DEBUG_IMPORTER,
     685                 :             :                   "Async module resolve hook for module {} (relative to {:?}), "
     686                 :             :                   "global {:?}",
     687                 :          44 :                   specifier, &importing_module_priv.toObject(), global);
     688                 :             :     } else {
     689                 :           3 :         gjs_debug(GJS_DEBUG_IMPORTER,
     690                 :             :                   "Async module resolve hook for module {} (unknown path), "
     691                 :             :                   "global {:?}",
     692                 :             :                   specifier, global);
     693                 :             :     }
     694                 :             : 
     695                 :          47 :     JS::RootedValueArray<2> args(cx);
     696                 :          47 :     args[0].set(importing_module_priv);
     697                 :          47 :     args[1].setString(specifier);
     698                 :             : 
     699                 :          47 :     JS::RootedValue result(cx);
     700         [ -  + ]:          47 :     if (!JS::Call(cx, loader, "moduleResolveAsyncHook", args, &result))
     701                 :           0 :         return JS::FinishDynamicModuleImport(cx, nullptr, importing_module_priv,
     702                 :           0 :                                              module_request, internal_promise);
     703                 :             : 
     704                 :             :     // Release in finish_import
     705                 :          47 :     GjsContextPrivate* priv = GjsContextPrivate::from_cx(cx);
     706                 :          47 :     priv->main_loop_hold();
     707                 :             : 
     708                 :          47 :     JS::RootedObject resolved(
     709                 :          47 :         cx, JS_GetFunctionObject(js::NewFunctionWithReserved(
     710                 :          47 :                 cx, import_resolved, 1, 0, "async import resolved")));
     711         [ -  + ]:          47 :     if (!resolved)
     712                 :           0 :         return false;
     713                 :          47 :     JS::RootedObject rejected(
     714                 :          47 :         cx, JS_GetFunctionObject(js::NewFunctionWithReserved(
     715                 :          47 :                 cx, import_rejected, 1, 0, "async import rejected")));
     716         [ -  + ]:          47 :     if (!rejected)
     717                 :           0 :         return false;
     718                 :          47 :     js::SetFunctionNativeReserved(resolved, 0, JS::ObjectValue(*callback_data));
     719                 :          47 :     js::SetFunctionNativeReserved(rejected, 0, JS::ObjectValue(*callback_data));
     720                 :             : 
     721                 :          47 :     JS::RootedObject promise(cx, &result.toObject());
     722                 :             : 
     723                 :             :     // Calling JS::FinishDynamicModuleImport() at the end of the resolve and
     724                 :             :     // reject handlers will also call the module resolve hook. The module will
     725                 :             :     // already have been resolved, but that is how SpiderMonkey obtains the
     726                 :             :     // module object.
     727                 :          47 :     return JS::AddPromiseReactions(cx, promise, resolved, rejected);
     728                 :          47 : }
        

Generated by: LCOV version 2.0-1