Coverage Report

Created: 2026-02-16 07:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/serenity/Userland/Libraries/LibJS/Runtime/ShadowRealm.cpp
Line
Count
Source
1
/*
2
 * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
3
 *
4
 * SPDX-License-Identifier: BSD-2-Clause
5
 */
6
7
#include <LibJS/Bytecode/Executable.h>
8
#include <LibJS/Bytecode/Interpreter.h>
9
#include <LibJS/Lexer.h>
10
#include <LibJS/Parser.h>
11
#include <LibJS/Runtime/AbstractOperations.h>
12
#include <LibJS/Runtime/DeclarativeEnvironment.h>
13
#include <LibJS/Runtime/GlobalEnvironment.h>
14
#include <LibJS/Runtime/ModuleNamespaceObject.h>
15
#include <LibJS/Runtime/NativeFunction.h>
16
#include <LibJS/Runtime/PromiseCapability.h>
17
#include <LibJS/Runtime/PromiseConstructor.h>
18
#include <LibJS/Runtime/ShadowRealm.h>
19
#include <LibJS/Runtime/WrappedFunction.h>
20
21
namespace JS {
22
23
JS_DEFINE_ALLOCATOR(ShadowRealm);
24
25
ShadowRealm::ShadowRealm(Object& prototype)
26
0
    : Object(ConstructWithPrototypeTag::Tag, prototype)
27
0
{
28
0
}
29
30
void ShadowRealm::visit_edges(Visitor& visitor)
31
0
{
32
0
    Base::visit_edges(visitor);
33
34
0
    visitor.visit(m_shadow_realm);
35
0
}
36
37
// 3.1.2 CopyNameAndLength ( F: a function object, Target: a function object, optional prefix: a String, optional argCount: a Number, ), https://tc39.es/proposal-shadowrealm/#sec-copynameandlength
38
ThrowCompletionOr<void> copy_name_and_length(VM& vm, FunctionObject& function, FunctionObject& target, Optional<StringView> prefix, Optional<unsigned> arg_count)
39
0
{
40
    // 1. If argCount is undefined, then set argCount to 0.
41
0
    if (!arg_count.has_value())
42
0
        arg_count = 0;
43
44
    // 2. Let L be 0.
45
0
    double length = 0;
46
47
    // 3. Let targetHasLength be ? HasOwnProperty(Target, "length").
48
0
    auto target_has_length = TRY(target.has_own_property(vm.names.length));
49
50
    // 4. If targetHasLength is true, then
51
0
    if (target_has_length) {
52
        // a. Let targetLen be ? Get(Target, "length").
53
0
        auto target_length = TRY(target.get(vm.names.length));
54
55
        // b. If Type(targetLen) is Number, then
56
0
        if (target_length.is_number()) {
57
            // i. If targetLen is +∞𝔽, set L to +∞.
58
0
            if (target_length.is_positive_infinity()) {
59
0
                length = target_length.as_double();
60
0
            }
61
            // ii. Else if targetLen is -∞𝔽, set L to 0.
62
0
            else if (target_length.is_negative_infinity()) {
63
0
                length = 0;
64
0
            }
65
            // iii. Else,
66
0
            else {
67
                // 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
68
0
                auto target_length_as_int = MUST(target_length.to_integer_or_infinity(vm));
69
70
                // 2. Assert: targetLenAsInt is finite.
71
0
                VERIFY(!isinf(target_length_as_int));
72
73
                // 3. Set L to max(targetLenAsInt - argCount, 0).
74
0
                length = max(target_length_as_int - *arg_count, 0);
75
0
            }
76
0
        }
77
0
    }
78
79
    // 5. Perform SetFunctionLength(F, L).
80
0
    function.set_function_length(length);
81
82
    // 6. Let targetName be ? Get(Target, "name").
83
0
    auto target_name = TRY(target.get(vm.names.name));
84
85
    // 7. If Type(targetName) is not String, set targetName to the empty String.
86
0
    if (!target_name.is_string())
87
0
        target_name = PrimitiveString::create(vm, String {});
88
89
    // 8. Perform SetFunctionName(F, targetName, prefix).
90
0
    function.set_function_name({ target_name.as_string().byte_string() }, move(prefix));
91
92
0
    return {};
93
0
}
94
95
// 3.1.3 PerformShadowRealmEval ( sourceText: a String, callerRealm: a Realm Record, evalRealm: a Realm Record, ), https://tc39.es/proposal-shadowrealm/#sec-performshadowrealmeval
96
ThrowCompletionOr<Value> perform_shadow_realm_eval(VM& vm, StringView source_text, Realm& caller_realm, Realm& eval_realm)
97
0
{
98
    // 1. Perform ? HostEnsureCanCompileStrings(evalRealm, « », sourceText, false).
99
0
    TRY(vm.host_ensure_can_compile_strings(eval_realm, {}, source_text, EvalMode::Indirect));
100
101
    // 2. Perform the following substeps in an implementation-defined order, possibly interleaving parsing and error detection:
102
103
    // a. Let script be ParseText(StringToCodePoints(sourceText), Script).
104
0
    auto parser = Parser(Lexer(source_text), Program::Type::Script, Parser::EvalInitialState {});
105
0
    auto program = parser.parse_program();
106
107
    // b. If script is a List of errors, throw a SyntaxError exception.
108
0
    if (parser.has_errors()) {
109
0
        auto& error = parser.errors()[0];
110
0
        return vm.throw_completion<SyntaxError>(error.to_string());
111
0
    }
112
113
    // c. If script Contains ScriptBody is false, return undefined.
114
0
    if (program->children().is_empty())
115
0
        return js_undefined();
116
117
    // d. Let body be the ScriptBody of script.
118
    // e. If body Contains NewTarget is true, throw a SyntaxError exception.
119
    // f. If body Contains SuperProperty is true, throw a SyntaxError exception.
120
    // g. If body Contains SuperCall is true, throw a SyntaxError exception.
121
    // FIXME: Implement these, we probably need a generic way of scanning the AST for certain nodes.
122
123
    // 3. Let strictEval be IsStrict of script.
124
0
    auto strict_eval = program->is_strict_mode();
125
126
    // 4. Let runningContext be the running execution context.
127
    // 5. If runningContext is not already suspended, suspend runningContext.
128
    // NOTE: This would be unused due to step 9 and is omitted for that reason.
129
130
    // 6. Let evalContext be GetShadowRealmContext(evalRealm, strictEval).
131
0
    auto eval_context = get_shadow_realm_context(eval_realm, strict_eval);
132
133
    // 7. Let lexEnv be evalContext's LexicalEnvironment.
134
0
    auto lexical_environment = eval_context->lexical_environment;
135
136
    // 8. Let varEnv be evalContext's VariableEnvironment.
137
0
    auto variable_environment = eval_context->variable_environment;
138
139
    // 9. Push evalContext onto the execution context stack; evalContext is now the running execution context.
140
0
    TRY(vm.push_execution_context(*eval_context, {}));
141
142
    // 10. Let result be Completion(EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval)).
143
0
    auto eval_result = eval_declaration_instantiation(vm, program, variable_environment, lexical_environment, nullptr, strict_eval);
144
145
0
    Completion result;
146
147
    // 11. If result.[[Type]] is normal, then
148
0
    if (!eval_result.is_throw_completion()) {
149
        // a. Set result to the result of evaluating body.
150
0
        auto maybe_executable = Bytecode::compile(vm, program, FunctionKind::Normal, "ShadowRealmEval"sv);
151
0
        if (maybe_executable.is_error()) {
152
0
            result = maybe_executable.release_error();
153
0
        } else {
154
0
            auto executable = maybe_executable.release_value();
155
156
0
            auto result_and_return_register = vm.bytecode_interpreter().run_executable(*executable, {});
157
0
            if (result_and_return_register.value.is_error()) {
158
0
                result = result_and_return_register.value.release_error();
159
0
            } else {
160
                // Resulting value is in the accumulator.
161
0
                result = result_and_return_register.return_register_value.value_or(js_undefined());
162
0
            }
163
0
        }
164
0
    }
165
166
    // 12. If result.[[Type]] is normal and result.[[Value]] is empty, then
167
0
    if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
168
        // a. Set result to NormalCompletion(undefined).
169
0
        result = normal_completion(js_undefined());
170
0
    }
171
172
    // 13. Suspend evalContext and remove it from the execution context stack.
173
    // NOTE: We don't support this concept yet.
174
0
    vm.pop_execution_context();
175
176
    // 14. Resume the context that is now on the top of the execution context stack as the running execution context.
177
    // NOTE: We don't support this concept yet.
178
179
    // 15. If result.[[Type]] is not normal, then
180
0
    if (result.type() != Completion::Type::Normal) {
181
        // a. Let copiedError be CreateTypeErrorCopy(callerRealm, result.[[Value]]).
182
        // b. Return ThrowCompletion(copiedError).
183
0
        return vm.throw_completion<TypeError>(ErrorType::ShadowRealmEvaluateAbruptCompletion);
184
0
    }
185
186
    // 16. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
187
0
    return get_wrapped_value(vm, caller_realm, *result.value());
188
189
    // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
190
0
}
191
192
// 3.1.4 ShadowRealmImportValue ( specifierString: a String, exportNameString: a String, callerRealm: a Realm Record, evalRealm: a Realm Record, evalContext: an execution context, ), https://tc39.es/proposal-shadowrealm/#sec-shadowrealmimportvalue
193
ThrowCompletionOr<Value> shadow_realm_import_value(VM& vm, ByteString specifier_string, ByteString export_name_string, Realm& caller_realm, Realm& eval_realm)
194
0
{
195
0
    auto& realm = *vm.current_realm();
196
197
    // 1. Let evalContext be GetShadowRealmContext(evalRealm, true).
198
0
    auto eval_context = get_shadow_realm_context(eval_realm, true);
199
200
    // 2. Let innerCapability be ! NewPromiseCapability(%Promise%).
201
0
    auto inner_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
202
203
    // 3. Let runningContext be the running execution context.
204
    // 4. If runningContext is not already suspended, suspend runningContext.
205
    // NOTE: We don't support this concept yet.
206
207
    // 5. Push evalContext onto the execution context stack; evalContext is now the running execution context.
208
0
    TRY(vm.push_execution_context(*eval_context, {}));
209
210
    // 6. Let referrer be the Realm component of evalContext.
211
0
    auto referrer = JS::NonnullGCPtr { *eval_context->realm };
212
213
    // 7. Perform HostLoadImportedModule(referrer, specifierString, empty, innerCapability).
214
0
    vm.host_load_imported_module(referrer, ModuleRequest { specifier_string }, nullptr, inner_capability);
215
216
    // 7. Suspend evalContext and remove it from the execution context stack.
217
    // NOTE: We don't support this concept yet.
218
0
    vm.pop_execution_context();
219
220
    // 8. Resume the context that is now on the top of the execution context stack as the running execution context.
221
    // NOTE: We don't support this concept yet.
222
223
    // 9. Let steps be the steps of an ExportGetter function as described below.
224
0
    auto steps = [string = move(export_name_string)](auto& vm) -> ThrowCompletionOr<Value> {
225
        // 1. Assert: exports is a module namespace exotic object.
226
0
        VERIFY(vm.argument(0).is_object());
227
0
        auto& exports = vm.argument(0).as_object();
228
0
        VERIFY(is<ModuleNamespaceObject>(exports));
229
230
        // 2. Let f be the active function object.
231
0
        auto function = vm.running_execution_context().function;
232
233
        // 3. Let string be f.[[ExportNameString]].
234
        // 4. Assert: Type(string) is String.
235
236
        // 5. Let hasOwn be ? HasOwnProperty(exports, string).
237
0
        auto has_own = TRY(exports.has_own_property(string));
238
239
        // 6. If hasOwn is false, throw a TypeError exception.
240
0
        if (!has_own)
241
0
            return vm.template throw_completion<TypeError>(ErrorType::MissingRequiredProperty, string);
242
243
        // 7. Let value be ? Get(exports, string).
244
0
        auto value = TRY(exports.get(string));
245
246
        // 8. Let realm be f.[[Realm]].
247
0
        auto* realm = function->realm();
248
0
        VERIFY(realm);
249
250
        // 9. Return ? GetWrappedValue(realm, value).
251
0
        return get_wrapped_value(vm, *realm, value);
252
0
    };
253
254
    // 10. Let onFulfilled be CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
255
    // 11. Set onFulfilled.[[ExportNameString]] to exportNameString.
256
0
    auto on_fulfilled = NativeFunction::create(realm, move(steps), 1, "", &caller_realm);
257
258
    // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%).
259
0
    auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
260
261
    // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do.
262
    // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object).
263
0
    auto throw_type_error = NativeFunction::create(realm, {}, [](auto& vm) -> ThrowCompletionOr<Value> {
264
0
        return vm.template throw_completion<TypeError>(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().utf8_string());
265
0
    });
266
267
    // 13. Return PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability).
268
0
    return verify_cast<Promise>(inner_capability->promise().ptr())->perform_then(on_fulfilled, throw_type_error, promise_capability);
269
0
}
270
271
// 3.1.5 GetWrappedValue ( callerRealm: a Realm Record, value: unknown, ), https://tc39.es/proposal-shadowrealm/#sec-getwrappedvalue
272
ThrowCompletionOr<Value> get_wrapped_value(VM& vm, Realm& caller_realm, Value value)
273
0
{
274
0
    auto& realm = *vm.current_realm();
275
276
    // 1. If Type(value) is Object, then
277
0
    if (value.is_object()) {
278
        // a. If IsCallable(value) is false, throw a TypeError exception.
279
0
        if (!value.is_function())
280
0
            return vm.throw_completion<TypeError>(ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
281
282
        // b. Return ? WrappedFunctionCreate(callerRealm, value).
283
0
        return TRY(WrappedFunction::create(realm, caller_realm, value.as_function()));
284
0
    }
285
286
    // 2. Return value.
287
0
    return value;
288
0
}
289
290
// 3.1.7 GetShadowRealmContext ( shadowRealmRecord, strictEval ), https://tc39.es/proposal-shadowrealm/#sec-getshadowrealmcontext
291
NonnullOwnPtr<ExecutionContext> get_shadow_realm_context(Realm& shadow_realm, bool strict_eval)
292
0
{
293
    // 1. Let lexEnv be NewDeclarativeEnvironment(shadowRealmRecord.[[GlobalEnv]]).
294
0
    Environment* lexical_environment = new_declarative_environment(shadow_realm.global_environment()).ptr();
295
296
    // 2. Let varEnv be shadowRealmRecord.[[GlobalEnv]].
297
0
    Environment* variable_environment = &shadow_realm.global_environment();
298
299
    // 3. If strictEval is true, set varEnv to lexEnv.
300
0
    if (strict_eval)
301
0
        variable_environment = lexical_environment;
302
303
    // 4. Let context be a new ECMAScript code execution context.
304
0
    auto context = ExecutionContext::create();
305
306
    // 5. Set context's Function to null.
307
0
    context->function = nullptr;
308
309
    // 6. Set context's Realm to shadowRealmRecord.
310
0
    context->realm = &shadow_realm;
311
312
    // 7. Set context's ScriptOrModule to null.
313
0
    context->script_or_module = {};
314
315
    // 8. Set context's VariableEnvironment to varEnv.
316
0
    context->variable_environment = variable_environment;
317
318
    // 9. Set context's LexicalEnvironment to lexEnv.
319
0
    context->lexical_environment = lexical_environment;
320
321
    // 10. Set context's PrivateEnvironment to null.
322
0
    context->private_environment = nullptr;
323
324
    // Non-standard
325
0
    context->is_strict_mode = strict_eval;
326
327
    // 11. Return context.
328
0
    return context;
329
0
}
330
331
}