Debian Codegraph @

js/src/vm/Interpreter.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 /*
8 * JavaScript bytecode interpreter.
9 */
10
11 #include "vm/Interpreter-inl.h"
12
13 #include "mozilla/DebugOnly.h"
14 #include "mozilla/FloatingPoint.h"
15 #include "mozilla/Maybe.h"
16 #include "mozilla/ScopeExit.h"
17 #include "mozilla/Sprintf.h"
18 #include "mozilla/TimeStamp.h"
19
20 #include <string.h>
21
22 #include "jsapi.h"
23 #include "jsnum.h"
24
25 #include "builtin/Array.h"
26 #include "builtin/Eval.h"
27 #include "builtin/ModuleObject.h"
28 #include "builtin/Object.h"
29 #include "builtin/Promise.h"
30 #include "gc/GC.h"
31 #include "jit/BaselineJIT.h"
32 #include "jit/Jit.h"
33 #include "jit/JitRuntime.h"
34 #include "js/EnvironmentChain.h" // JS::SupportUnscopables
35 #include "js/experimental/JitInfo.h" // JSJitInfo
36 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
37 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
38 #include "js/friend/WindowProxy.h" // js::IsWindowProxy
39 #include "js/Printer.h"
40 #include "proxy/DeadObjectProxy.h"
41 #include "util/StringBuilder.h"
42 #include "vm/AsyncFunction.h"
43 #include "vm/AsyncIteration.h"
44 #include "vm/BigIntType.h"
45 #include "vm/BytecodeUtil.h" // JSDVG_SEARCH_STACK
46 #include "vm/ConstantCompareOperand.h"
47 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
48 # include "vm/ErrorObject.h"
49 #endif
50 #include "vm/EqualityOperations.h" // js::StrictlyEqual
51 #include "vm/GeneratorObject.h"
52 #include "vm/Iteration.h"
53 #include "vm/JSContext.h"
54 #include "vm/JSFunction.h"
55 #include "vm/JSObject.h"
56 #include "vm/JSScript.h"
57 #include "vm/Opcodes.h"
58 #include "vm/PlainObject.h" // js::PlainObject
59 #include "vm/Scope.h"
60 #include "vm/Shape.h"
61 #include "vm/SharedStencil.h" // GCThingIndex
62 #include "vm/StringType.h"
63 #include "vm/ThrowMsgKind.h" // ThrowMsgKind
64 #include "vm/TypeofEqOperand.h" // TypeofEqOperand
65 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
66 # include "vm/UsingHint.h"
67 #endif
68 #include "builtin/Boolean-inl.h"
69 #include "debugger/DebugAPI-inl.h"
70 #include "vm/ArgumentsObject-inl.h"
71 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
72 # include "vm/DisposableRecord-inl.h"
73 #endif
74 #include "vm/EnvironmentObject-inl.h"
75 #include "vm/GeckoProfiler-inl.h"
76 #include "vm/JSScript-inl.h"
77 #include "vm/NativeObject-inl.h"
78 #include "vm/ObjectOperations-inl.h"
79 #include "vm/PlainObject-inl.h" // js::CopyInitializerObject, js::CreateThis
80 #include "vm/Probes-inl.h"
81 #include "vm/Stack-inl.h"
82
83 using namespace js;
84
85 using mozilla::DebugOnly;
86 using mozilla::NumberEqualsInt32;
87
88 template <bool Eq>
89 static MOZ_ALWAYS_INLINE bool LooseEqualityOp(JSContext* cx,
90 InterpreterRegs& regs) {
91 HandleValue rval = regs.stackHandleAt(-1);
92 HandleValue lval = regs.stackHandleAt(-2);
93 bool cond;
94 if (!LooselyEqual(cx, lval, rval, &cond)) {
95 return false;
96 }
97 cond = (cond == Eq);
98 regs.sp--;
99 regs.sp[-1].setBoolean(cond);
100 return true;
101 }
102
103 JSObject* js::BoxNonStrictThis(JSContext* cx, HandleValue thisv) {
104 MOZ_ASSERT(!thisv.isMagic());
105
106 if (thisv.isNullOrUndefined()) {
107 return cx->global()->lexicalEnvironment().thisObject();
108 }
109
110 if (thisv.isObject()) {
111 return &thisv.toObject();
112 }
113
114 return PrimitiveToObject(cx, thisv);
115 }
116
117 static bool IsNSVOLexicalEnvironment(JSObject* env) {
118 return env->is<LexicalEnvironmentObject>() &&
119 env->as<LexicalEnvironmentObject>()
120 .enclosingEnvironment()
121 .is<NonSyntacticVariablesObject>();
122 }
123
124 bool js::GetFunctionThis(JSContext* cx, AbstractFramePtr frame,
125 MutableHandleValue res) {
126 MOZ_ASSERT(frame.isFunctionFrame());
127 MOZ_ASSERT(!frame.callee()->isArrow());
128
129 if (frame.thisArgument().isObject() || frame.callee()->strict()) {
130 res.set(frame.thisArgument());
131 return true;
132 }
133
134 MOZ_ASSERT(!frame.callee()->isSelfHostedBuiltin(),
135 "Self-hosted builtins must be strict");
136
137 RootedValue thisv(cx, frame.thisArgument());
138
139 // If there is a NSVO on environment chain, use it as basis for fallback
140 // global |this|. This gives a consistent definition of global lexical
141 // |this| between function and global contexts.
142 //
143 // NOTE: If only non-syntactic WithEnvironments are on the chain, we use the
144 // global lexical |this| value. This is for compatibility with the Subscript
145 // Loader.
146 if (frame.script()->hasNonSyntacticScope() && thisv.isNullOrUndefined()) {
147 JSObject* env = frame.environmentChain();
148 while (true) {
149 if (IsNSVOLexicalEnvironment(env) ||
150 env->is<GlobalLexicalEnvironmentObject>()) {
151 auto* obj = env->as<ExtensibleLexicalEnvironmentObject>().thisObject();
152 res.setObject(*obj);
153 return true;
154 }
155 if (!env->enclosingEnvironment()) {
156 // This can only happen in Debugger eval frames: in that case we
157 // don't always have a global lexical env, see EvaluateInEnv.
158 MOZ_ASSERT(env->is<GlobalObject>());
159 res.setObject(*GetThisObject(env));
160 return true;
161 }
162 env = env->enclosingEnvironment();
163 }
164 }
165
166 JSObject* obj = BoxNonStrictThis(cx, thisv);
167 if (!obj) {
168 return false;
169 }
170
171 res.setObject(*obj);
172 return true;
173 }
174
175 void js::GetNonSyntacticGlobalThis(JSContext* cx, HandleObject envChain,
176 MutableHandleValue res) {
177 JSObject* env = envChain;
178 while (true) {
179 if (env->is<ExtensibleLexicalEnvironmentObject>()) {
180 auto* obj = env->as<ExtensibleLexicalEnvironmentObject>().thisObject();
181 res.setObject(*obj);
182 return;
183 }
184 if (!env->enclosingEnvironment()) {
185 // This can only happen in Debugger eval frames: in that case we
186 // don't always have a global lexical env, see EvaluateInEnv.
187 MOZ_ASSERT(env->is<GlobalObject>());
188 res.setObject(*GetThisObject(env));
189 return;
190 }
191 env = env->enclosingEnvironment();
192 }
193 }
194
195 #ifdef DEBUG
196 static bool IsSelfHostedOrKnownBuiltinCtor(JSFunction* fun, JSContext* cx) {
197 if (fun->isSelfHostedOrIntrinsic()) {
198 return true;
199 }
200
201 // GetBuiltinConstructor in MapGroupBy
202 if (fun == cx->global()->maybeGetConstructor(JSProto_Map)) {
203 return true;
204 }
205
206 // GetBuiltinConstructor in intlFallbackSymbol
207 if (fun == cx->global()->maybeGetConstructor(JSProto_Symbol)) {
208 return true;
209 }
210
211 // ConstructorForTypedArray in MergeSortTypedArray
212 if (fun == cx->global()->maybeGetConstructor(JSProto_Int8Array) ||
213 fun == cx->global()->maybeGetConstructor(JSProto_Uint8Array) ||
214 fun == cx->global()->maybeGetConstructor(JSProto_Int16Array) ||
215 fun == cx->global()->maybeGetConstructor(JSProto_Uint16Array) ||
216 fun == cx->global()->maybeGetConstructor(JSProto_Int32Array) ||
217 fun == cx->global()->maybeGetConstructor(JSProto_Uint32Array) ||
218 fun == cx->global()->maybeGetConstructor(JSProto_Float32Array) ||
219 fun == cx->global()->maybeGetConstructor(JSProto_Float64Array) ||
220 fun == cx->global()->maybeGetConstructor(JSProto_Uint8ClampedArray) ||
221 fun == cx->global()->maybeGetConstructor(JSProto_BigInt64Array) ||
222 fun == cx->global()->maybeGetConstructor(JSProto_BigUint64Array)) {
223 return true;
224 }
225
226 return false;
227 }
228 #endif // DEBUG
229
230 bool js::Debug_CheckSelfHosted(JSContext* cx, HandleValue funVal) {
231 #ifdef DEBUG
232 JSFunction* fun = &UncheckedUnwrap(&funVal.toObject())->as<JSFunction>();
233 MOZ_ASSERT(IsSelfHostedOrKnownBuiltinCtor(fun, cx),
234 "functions directly called inside self-hosted JS must be one of "
235 "selfhosted function, self-hosted intrinsic, or known built-in "
236 "constructor");
237 #else
238 MOZ_CRASH("self-hosted checks should only be done in Debug builds");
239 #endif
240
241 // This is purely to police self-hosted code. There is no actual operation.
242 return true;
243 }
244
245 static inline bool GetLengthProperty(const Value& lval, MutableHandleValue vp) {
246 /* Optimize length accesses on strings, arrays, and arguments. */
247 if (lval.isString()) {
248 vp.setInt32(lval.toString()->length());
249 return true;
250 }
251 if (lval.isObject()) {
252 JSObject* obj = &lval.toObject();
253 if (obj->is<ArrayObject>()) {
254 vp.setNumber(obj->as<ArrayObject>().length());
255 return true;
256 }
257
258 if (obj->is<ArgumentsObject>()) {
259 ArgumentsObject* argsobj = &obj->as<ArgumentsObject>();
260 if (!argsobj->hasOverriddenLength()) {
261 uint32_t length = argsobj->initialLength();
262 MOZ_ASSERT(length < INT32_MAX);
263 vp.setInt32(int32_t(length));
264 return true;
265 }
266 }
267 }
268
269 return false;
270 }
271
272 static inline bool GetPropertyOperation(JSContext* cx,
273 Handle<PropertyName*> name,
274 HandleValue lval,
275 MutableHandleValue vp) {
276 if (name == cx->names().length && ::GetLengthProperty(lval, vp)) {
277 return true;
278 }
279
280 return GetProperty(cx, lval, name, vp);
281 }
282
283 static inline bool GetNameOperation(JSContext* cx, HandleObject envChain,
284 Handle<PropertyName*> name, JSOp nextOp,
285 MutableHandleValue vp) {
286 /* Kludge to allow (typeof foo == "undefined") tests. */
287 if (IsTypeOfNameOp(nextOp)) {
288 return GetEnvironmentName<GetNameMode::TypeOf>(cx, envChain, name, vp);
289 }
290 return GetEnvironmentName<GetNameMode::Normal>(cx, envChain, name, vp);
291 }
292
293 bool js::GetImportOperation(JSContext* cx, HandleObject envChain,
294 HandleScript script, jsbytecode* pc,
295 MutableHandleValue vp) {
296 RootedObject env(cx), pobj(cx);
297 Rooted<PropertyName*> name(cx, script->getName(pc));
298 PropertyResult prop;
299
300 MOZ_ALWAYS_TRUE(LookupName(cx, name, envChain, &env, &pobj, &prop));
301 MOZ_ASSERT(env && env->is<ModuleEnvironmentObject>());
302 MOZ_ASSERT(env->as<ModuleEnvironmentObject>().hasImportBinding(name));
303 return FetchName<GetNameMode::Normal>(cx, env, pobj, name, prop, vp);
304 }
305
306 bool js::ReportIsNotFunction(JSContext* cx, HandleValue v, int numToSkip,
307 MaybeConstruct construct) {
308 unsigned error = construct ? JSMSG_NOT_CONSTRUCTOR : JSMSG_NOT_FUNCTION;
309 int spIndex = numToSkip >= 0 ? -(numToSkip + 1) : JSDVG_SEARCH_STACK;
310
311 ReportValueError(cx, error, spIndex, v, nullptr);
312 return false;
313 }
314
315 JSObject* js::ValueToCallable(JSContext* cx, HandleValue v, int numToSkip,
316 MaybeConstruct construct) {
317 if (v.isObject() && v.toObject().isCallable()) {
318 return &v.toObject();
319 }
320
321 ReportIsNotFunction(cx, v, numToSkip, construct);
322 return nullptr;
323 }
324
325 static bool MaybeCreateThisForConstructor(JSContext* cx, const CallArgs& args) {
326 if (args.thisv().isObject()) {
327 return true;
328 }
329
330 RootedFunction callee(cx, &args.callee().as<JSFunction>());
331 RootedObject newTarget(cx, &args.newTarget().toObject());
332
333 MOZ_ASSERT(callee->hasBytecode());
334
335 if (!CreateThis(cx, callee, newTarget, GenericObject, args.mutableThisv())) {
336 return false;
337 }
338
339 // Ensure the callee still has a non-lazy script. We normally don't relazify
340 // in active compartments, but the .prototype lookup might have called the
341 // relazifyFunctions testing function that doesn't have this restriction.
342 return JSFunction::getOrCreateScript(cx, callee);
343 }
344
345 InterpreterFrame* InvokeState::pushInterpreterFrame(JSContext* cx) {
346 return cx->interpreterStack().pushInvokeFrame(cx, args_, construct_);
347 }
348
349 InterpreterFrame* ExecuteState::pushInterpreterFrame(JSContext* cx) {
350 return cx->interpreterStack().pushExecuteFrame(cx, script_, envChain_,
351 evalInFrame_);
352 }
353
354 InterpreterFrame* RunState::pushInterpreterFrame(JSContext* cx) {
355 if (isInvoke()) {
356 return asInvoke()->pushInterpreterFrame(cx);
357 }
358 return asExecute()->pushInterpreterFrame(cx);
359 }
360
361 static MOZ_ALWAYS_INLINE bool MaybeEnterInterpreterTrampoline(JSContext* cx,
362 RunState& state) {
363 #ifdef NIGHTLY_BUILD
364 if (jit::JitOptions.emitInterpreterEntryTrampoline &&
365 cx->runtime()->hasJitRuntime()) {
366 js::jit::JitRuntime* jitRuntime = cx->runtime()->jitRuntime();
367 JSScript* script = state.script();
368
369 uint8_t* codeRaw = nullptr;
370 auto p = jitRuntime->getInterpreterEntryMap()->lookup(script);
371 if (p) {
372 codeRaw = p->value().raw();
373 } else {
374 js::jit::JitCode* code =
375 jitRuntime->generateEntryTrampolineForScript(cx, script);
376 if (!code) {
377 ReportOutOfMemory(cx);
378 return false;
379 }
380
381 js::jit::EntryTrampoline entry(cx, code);
382 if (!jitRuntime->getInterpreterEntryMap()->put(script, entry)) {
383 ReportOutOfMemory(cx);
384 return false;
385 }
386 codeRaw = code->raw();
387 }
388
389 MOZ_ASSERT(codeRaw, "Should have a valid trampoline here.");
390 // The C++ entry thunk is located at the vmInterpreterEntryOffset offset.
391 codeRaw += jitRuntime->vmInterpreterEntryOffset();
392 return js::jit::EnterInterpreterEntryTrampoline(codeRaw, cx, &state);
393 }
394 #endif
395 return Interpret(cx, state);
396 }
397
398 static void AssertExceptionResult(JSContext* cx) {
399 // If this assertion fails, a JSNative or code in the VM returned false
400 // without throwing an exception or calling JS::ReportUncatchableException.
401 MOZ_ASSERT(cx->isExceptionPending() || cx->isPropagatingForcedReturn() ||
402 cx->hadUncatchableException());
403 }
404
405 // MSVC with PGO inlines a lot of functions in RunScript, resulting in large
406 // stack frames and stack overflow issues, see bug 1167883. Turn off PGO to
407 // avoid this.
408 #ifdef _MSC_VER
409 # pragma optimize("g", off)
410 #endif
411 bool js::RunScript(JSContext* cx, RunState& state) {
412 AutoCheckRecursionLimit recursion(cx);
413 if (!recursion.check(cx)) {
414 return false;
415 }
416
417 MOZ_ASSERT_IF(cx->runtime()->hasJitRuntime(),
418 !cx->runtime()->jitRuntime()->disallowArbitraryCode());
419
420 // Since any script can conceivably GC, make sure it's safe to do so.
421 cx->verifyIsSafeToGC();
422
423 // Don't run script while suppressing GC to not confuse JIT code that assumes
424 // some new objects will be allocated in the nursery.
425 MOZ_ASSERT(!cx->suppressGC);
426
427 MOZ_ASSERT(cx->realm() == state.script()->realm());
428
429 MOZ_DIAGNOSTIC_ASSERT(cx->realm()->isSystem() ||
430 cx->runtime()->allowContentJS());
431
432 if (!DebugAPI::checkNoExecute(cx, state.script())) {
433 return false;
434 }
435
436 GeckoProfilerEntryMarker marker(cx, state.script());
437
438 bool measuringTime = !cx->isMeasuringExecutionTime();
439 mozilla::TimeStamp startTime;
440 if (measuringTime) {
441 cx->setIsMeasuringExecutionTime(true);
442 cx->setIsExecuting(true);
443 startTime = mozilla::TimeStamp::Now();
444 }
445 auto timerEnd = mozilla::MakeScopeExit([&]() {
446 if (measuringTime) {
447 mozilla::TimeDuration delta = mozilla::TimeStamp::Now() - startTime;
448 cx->realm()->timers.executionTime += delta;
449 cx->setIsMeasuringExecutionTime(false);
450 cx->setIsExecuting(false);
451 }
452 });
453
454 jit::EnterJitStatus status = jit::MaybeEnterJit(cx, state);
455 switch (status) {
456 case jit::EnterJitStatus::Error:
457 return false;
458 case jit::EnterJitStatus::Ok:
459 return true;
460 case jit::EnterJitStatus::NotEntered:
461 break;
462 }
463
464 bool ok = MaybeEnterInterpreterTrampoline(cx, state);
465 if (!ok) {
466 AssertExceptionResult(cx);
467 }
468 return ok;
469 }
470 #ifdef _MSC_VER
471 # pragma optimize("", on)
472 #endif
473
474 STATIC_PRECONDITION_ASSUME(ubound(args.argv_) >= argc)
475 MOZ_ALWAYS_INLINE bool CallJSNative(JSContext* cx, Native native,
476 CallReason reason, const CallArgs& args) {
477 AutoCheckRecursionLimit recursion(cx);
478 if (!recursion.check(cx)) {
479 return false;
480 }
481
482 NativeResumeMode resumeMode = DebugAPI::onNativeCall(cx, args, reason);
483 if (resumeMode != NativeResumeMode::Continue) {
484 return resumeMode == NativeResumeMode::Override;
485 }
486
487 #ifdef DEBUG
488 bool alreadyThrowing = cx->isExceptionPending();
489 #endif
490 cx->check(args);
491 MOZ_ASSERT(!args.callee().is<ProxyObject>());
492
493 AutoRealm ar(cx, &args.callee());
494 bool ok = native(cx, args.length(), args.base());
495 if (ok) {
496 cx->check(args.rval());
497 MOZ_ASSERT_IF(!alreadyThrowing, !cx->isExceptionPending());
498 } else {
499 AssertExceptionResult(cx);
500 }
501 return ok;
502 }
503
504 STATIC_PRECONDITION(ubound(args.argv_) >= argc)
505 MOZ_ALWAYS_INLINE bool CallJSNativeConstructor(JSContext* cx, Native native,
506 const CallArgs& args) {
507 #ifdef DEBUG
508 RootedObject callee(cx, &args.callee());
509 #endif
510
511 MOZ_ASSERT(args.thisv().isMagic());
512 if (!CallJSNative(cx, native, CallReason::Call, args)) {
513 return false;
514 }
515
516 /*
517 * Native constructors must return non-primitive values on success.
518 * Although it is legal, if a constructor returns the callee, there is a
519 * 99.9999% chance it is a bug. If any valid code actually wants the
520 * constructor to return the callee, the assertion can be removed or
521 * (another) conjunct can be added to the antecedent.
522 *
523 * Exceptions:
524 * - (new Object(Object)) returns the callee.
525 * - The bound function construct hook can return an arbitrary object,
526 * including the callee.
527 *
528 * Also allow if this may be due to a debugger hook since fuzzing may let this
529 * happen.
530 */
531 MOZ_ASSERT(args.rval().isObject());
532 MOZ_ASSERT_IF(!JS_IsNativeFunction(callee, obj_construct) &&
533 !callee->is<BoundFunctionObject>() &&
534 !cx->realm()->debuggerObservesNativeCall(),
535 args.rval() != ObjectValue(*callee));
536
537 return true;
538 }
539
540 /*
541 * Find a function reference and its 'this' value implicit first parameter
542 * under argc arguments on cx's stack, and call the function. Push missing
543 * required arguments, allocate declared local variables, and pop everything
544 * when done. Then push the return value.
545 *
546 * Note: This function DOES NOT call GetThisValue to munge |args.thisv()| if
547 * necessary. The caller (usually the interpreter) must have performed
548 * this step already!
549 */
550 bool js::InternalCallOrConstruct(JSContext* cx, const CallArgs& args,
551 MaybeConstruct construct,
552 CallReason reason /* = CallReason::Call */) {
553 MOZ_ASSERT(args.length() <= ARGS_LENGTH_MAX);
554
555 unsigned skipForCallee = args.length() + 1 + (construct == CONSTRUCT);
556 if (args.calleev().isPrimitive()) {
557 return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct);
558 }
559
560 /* Invoke non-functions. */
561 if (MOZ_UNLIKELY(!args.callee().is<JSFunction>())) {
562 MOZ_ASSERT_IF(construct, !args.callee().isConstructor());
563
564 if (!args.callee().isCallable()) {
565 return ReportIsNotFunction(cx, args.calleev(), skipForCallee, construct);
566 }
567
568 if (args.callee().is<ProxyObject>()) {
569 RootedObject proxy(cx, &args.callee());
570 return Proxy::call(cx, proxy, args);
571 }
572
573 JSNative call = args.callee().callHook();
574 MOZ_ASSERT(call, "isCallable without a callHook?");
575
576 return CallJSNative(cx, call, reason, args);
577 }
578
579 /* Invoke native functions. */
580 RootedFunction fun(cx, &args.callee().as<JSFunction>());
581 if (fun->isNativeFun()) {
582 MOZ_ASSERT_IF(construct, !fun->isConstructor());
583 JSNative native = fun->native();
584 if (!construct && args.ignoresReturnValue() && fun->hasJitInfo()) {
585 const JSJitInfo* jitInfo = fun->jitInfo();
586 if (jitInfo->type() == JSJitInfo::IgnoresReturnValueNative) {
587 native = jitInfo->ignoresReturnValueMethod;
588 }
589 }
590 return CallJSNative(cx, native, reason, args);
591 }
592
593 // Self-hosted builtins are considered native by the onNativeCall hook.
594 if (fun->isSelfHostedBuiltin()) {
595 NativeResumeMode resumeMode = DebugAPI::onNativeCall(cx, args, reason);
596 if (resumeMode != NativeResumeMode::Continue) {
597 return resumeMode == NativeResumeMode::Override;
598 }
599 }
600
601 if (!JSFunction::getOrCreateScript(cx, fun)) {
602 return false;
603 }
604
605 /* Run function until JSOp::RetRval, JSOp::Return or error. */
606 InvokeState state(cx, args, construct);
607
608 // Create |this| if we're constructing. Switch to the callee's realm to
609 // ensure this object has the correct realm.
610 AutoRealm ar(cx, state.script());
611 if (construct && !MaybeCreateThisForConstructor(cx, args)) {
612 return false;
613 }
614
615 // Calling class constructors throws an error from the callee's realm.
616 if (construct != CONSTRUCT && fun->isClassConstructor()) {
617 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
618 JSMSG_CANT_CALL_CLASS_CONSTRUCTOR);
619 return false;
620 }
621
622 bool ok = RunScript(cx, state);
623
624 MOZ_ASSERT_IF(ok && construct, args.rval().isObject());
625 return ok;
626 }
627
628 // Returns true if the callee needs an outerized |this| object. Outerization
629 // means passing the WindowProxy instead of the Window (a GlobalObject) because
630 // we must never expose the Window to script. This returns false only for DOM
631 // getters or setters.
632 static bool CalleeNeedsOuterizedThisObject(const Value& callee) {
633 if (!callee.isObject() || !callee.toObject().is<JSFunction>()) {
634 return true;
635 }
636 JSFunction& fun = callee.toObject().as<JSFunction>();
637 if (!fun.isNativeFun() || !fun.hasJitInfo()) {
638 return true;
639 }
640 return fun.jitInfo()->needsOuterizedThisObject();
641 }
642
643 static bool InternalCall(JSContext* cx, const AnyInvokeArgs& args,
644 CallReason reason) {
645 MOZ_ASSERT(args.array() + args.length() == args.end(),
646 "must pass calling arguments to a calling attempt");
647
648 #ifdef DEBUG
649 // The caller is responsible for calling GetThisObject if needed.
650 if (args.thisv().isObject()) {
651 JSObject* thisObj = &args.thisv().toObject();
652 MOZ_ASSERT_IF(CalleeNeedsOuterizedThisObject(args.calleev()),
653 GetThisObject(thisObj) == thisObj);
654 }
655 #endif
656
657 return InternalCallOrConstruct(cx, args, NO_CONSTRUCT, reason);
658 }
659
660 bool js::CallFromStack(JSContext* cx, const CallArgs& args,
661 CallReason reason /* = CallReason::Call */) {
662 return InternalCall(cx, static_cast<const AnyInvokeArgs&>(args), reason);
663 }
664
665 // ES7 rev 0c1bd3004329336774cbc90de727cd0cf5f11e93
666 // 7.3.12 Call.
667 bool js::Call(JSContext* cx, HandleValue fval, HandleValue thisv,
668 const AnyInvokeArgs& args, MutableHandleValue rval,
669 CallReason reason) {
670 // Explicitly qualify these methods to bypass AnyInvokeArgs's deliberate
671 // shadowing.
672 args.CallArgs::setCallee(fval);
673 args.CallArgs::setThis(thisv);
674
675 if (thisv.isObject()) {
676 // If |this| is a global object, it might be a Window and in that case we
677 // usually have to pass the WindowProxy instead.
678 JSObject* thisObj = &thisv.toObject();
679 if (thisObj->is<GlobalObject>()) {
680 if (CalleeNeedsOuterizedThisObject(fval)) {
681 args.mutableThisv().setObject(*GetThisObject(thisObj));
682 }
683 } else {
684 // Fast path: we don't have to do anything if the object isn't a global.
685 MOZ_ASSERT(GetThisObject(thisObj) == thisObj);
686 }
687 }
688
689 if (!InternalCall(cx, args, reason)) {
690 return false;
691 }
692
693 rval.set(args.rval());
694 return true;
695 }
696
697 static bool InternalConstruct(JSContext* cx, const AnyConstructArgs& args,
698 CallReason reason = CallReason::Call) {
699 MOZ_ASSERT(args.array() + args.length() + 1 == args.end(),
700 "must pass constructing arguments to a construction attempt");
701 MOZ_ASSERT(!FunctionClass.getConstruct());
702 MOZ_ASSERT(!ExtendedFunctionClass.getConstruct());
703
704 // Callers are responsible for enforcing these preconditions.
705 MOZ_ASSERT(IsConstructor(args.calleev()),
706 "trying to construct a value that isn't a constructor");
707 MOZ_ASSERT(IsConstructor(args.CallArgs::newTarget()),
708 "provided new.target value must be a constructor");
709
710 MOZ_ASSERT(args.thisv().isMagic(JS_IS_CONSTRUCTING) ||
711 args.thisv().isObject());
712
713 JSObject& callee = args.callee();
714 if (callee.is<JSFunction>()) {
715 RootedFunction fun(cx, &callee.as<JSFunction>());
716
717 if (fun->isNativeFun()) {
718 return CallJSNativeConstructor(cx, fun->native(), args);
719 }
720
721 if (!InternalCallOrConstruct(cx, args, CONSTRUCT, reason)) {
722 return false;
723 }
724
725 MOZ_ASSERT(args.CallArgs::rval().isObject());
726 return true;
727 }
728
729 if (callee.is<ProxyObject>()) {
730 RootedObject proxy(cx, &callee);
731 return Proxy::construct(cx, proxy, args);
732 }
733
734 JSNative construct = callee.constructHook();
735 MOZ_ASSERT(construct != nullptr, "IsConstructor without a construct hook?");
736
737 return CallJSNativeConstructor(cx, construct, args);
738 }
739
740 // Check that |callee|, the callee in a |new| expression, is a constructor.
741 static bool StackCheckIsConstructorCalleeNewTarget(JSContext* cx,
742 HandleValue callee,
743 HandleValue newTarget) {
744 // Calls from the stack could have any old non-constructor callee.
745 if (!IsConstructor(callee)) {
746 ReportValueError(cx, JSMSG_NOT_CONSTRUCTOR, JSDVG_SEARCH_STACK, callee,
747 nullptr);
748 return false;
749 }
750
751 // The new.target has already been vetted by previous calls, or is the callee.
752 // We can just assert that it's a constructor.
753 MOZ_ASSERT(IsConstructor(newTarget));
754
755 return true;
756 }
757
758 bool js::ConstructFromStack(JSContext* cx, const CallArgs& args,
759 CallReason reason /* CallReason::Call */) {
760 if (!StackCheckIsConstructorCalleeNewTarget(cx, args.calleev(),
761 args.newTarget())) {
762 return false;
763 }
764
765 return InternalConstruct(cx, static_cast<const AnyConstructArgs&>(args),
766 reason);
767 }
768
769 bool js::Construct(JSContext* cx, HandleValue fval,
770 const AnyConstructArgs& args, HandleValue newTarget,
771 MutableHandleObject objp) {
772 MOZ_ASSERT(args.thisv().isMagic(JS_IS_CONSTRUCTING));
773
774 // Explicitly qualify to bypass AnyConstructArgs's deliberate shadowing.
775 args.CallArgs::setCallee(fval);
776 args.CallArgs::newTarget().set(newTarget);
777
778 if (!InternalConstruct(cx, args)) {
779 return false;
780 }
781
782 MOZ_ASSERT(args.CallArgs::rval().isObject());
783 objp.set(&args.CallArgs::rval().toObject());
784 return true;
785 }
786
787 bool js::InternalConstructWithProvidedThis(JSContext* cx, HandleValue fval,
788 HandleValue thisv,
789 const AnyConstructArgs& args,
790 HandleValue newTarget,
791 MutableHandleValue rval) {
792 args.CallArgs::setCallee(fval);
793
794 MOZ_ASSERT(thisv.isObject());
795 args.CallArgs::setThis(thisv);
796
797 args.CallArgs::newTarget().set(newTarget);
798
799 if (!InternalConstruct(cx, args)) {
800 return false;
801 }
802
803 rval.set(args.CallArgs::rval());
804 return true;
805 }
806
807 bool js::CallGetter(JSContext* cx, HandleValue thisv, HandleValue getter,
808 MutableHandleValue rval) {
809 FixedInvokeArgs<0> args(cx);
810
811 return Call(cx, getter, thisv, args, rval, CallReason::Getter);
812 }
813
814 bool js::CallSetter(JSContext* cx, HandleValue thisv, HandleValue setter,
815 HandleValue v) {
816 FixedInvokeArgs<1> args(cx);
817 args[0].set(v);
818
819 RootedValue ignored(cx);
820 return Call(cx, setter, thisv, args, &ignored, CallReason::Setter);
821 }
822
823 bool js::ExecuteKernel(JSContext* cx, HandleScript script,
824 HandleObject envChainArg, AbstractFramePtr evalInFrame,
825 MutableHandleValue result) {
826 MOZ_ASSERT_IF(script->isGlobalCode(),
827 envChainArg->is<GlobalLexicalEnvironmentObject>() ||
828 !IsSyntacticEnvironment(envChainArg));
829 #ifdef DEBUG
830 RootedObject terminatingEnv(cx, envChainArg);
831 while (IsSyntacticEnvironment(terminatingEnv)) {
832 terminatingEnv = terminatingEnv->enclosingEnvironment();
833 }
834 MOZ_ASSERT(terminatingEnv->is<GlobalObject>() ||
835 script->hasNonSyntacticScope());
836 #endif
837
838 if (script->treatAsRunOnce()) {
839 if (script->hasRunOnce()) {
840 JS_ReportErrorASCII(cx,
841 "Trying to execute a run-once script multiple times");
842 return false;
843 }
844
845 script->setHasRunOnce();
846 }
847
848 if (script->isEmpty()) {
849 result.setUndefined();
850 return true;
851 }
852
853 probes::StartExecution(script);
854 ExecuteState state(cx, script, envChainArg, evalInFrame, result);
855 bool ok = RunScript(cx, state);
856 probes::StopExecution(script);
857
858 return ok;
859 }
860
861 bool js::Execute(JSContext* cx, HandleScript script, HandleObject envChain,
862 MutableHandleValue rval) {
863 /* The env chain is something we control, so we know it can't
864 have any outer objects on it. */
865 MOZ_ASSERT(!IsWindowProxy(envChain));
866
867 if (script->isModule()) {
868 MOZ_RELEASE_ASSERT(
869 envChain == script->module()->environment(),
870 "Module scripts can only be executed in the module's environment");
871 } else {
872 MOZ_RELEASE_ASSERT(
873 envChain->is<GlobalLexicalEnvironmentObject>() ||
874 script->hasNonSyntacticScope(),
875 "Only global scripts with non-syntactic envs can be executed with "
876 "interesting envchains");
877 }
878
879 /* Ensure the env chain is all same-compartment and terminates in a global. */
880 #ifdef DEBUG
881 JSObject* s = envChain;
882 do {
883 cx->check(s);
884 MOZ_ASSERT_IF(!s->enclosingEnvironment(), s->is<GlobalObject>());
885 } while ((s = s->enclosingEnvironment()));
886 #endif
887
888 return ExecuteKernel(cx, script, envChain, NullFramePtr() /* evalInFrame */,
889 rval);
890 }
891
892 /*
893 * ES6 (4-25-16) 12.10.4 InstanceofOperator
894 */
895 bool js::InstanceofOperator(JSContext* cx, HandleObject obj, HandleValue v,
896 bool* bp) {
897 /* Step 1. is handled by caller. */
898
899 /* Step 2. */
900 RootedValue hasInstance(cx);
901 RootedId id(cx, PropertyKey::Symbol(cx->wellKnownSymbols().hasInstance));
902 if (!GetProperty(cx, obj, obj, id, &hasInstance)) {
903 return false;
904 }
905
906 if (!hasInstance.isNullOrUndefined()) {
907 if (!IsCallable(hasInstance)) {
908 return ReportIsNotFunction(cx, hasInstance);
909 }
910
911 /* Step 3. */
912 RootedValue rval(cx);
913 if (!Call(cx, hasInstance, obj, v, &rval)) {
914 return false;
915 }
916 *bp = ToBoolean(rval);
917 return true;
918 }
919
920 /* Step 4. */
921 if (!obj->isCallable()) {
922 RootedValue val(cx, ObjectValue(*obj));
923 return ReportIsNotFunction(cx, val);
924 }
925
926 /* Step 5. */
927 return OrdinaryHasInstance(cx, obj, v, bp);
928 }
929
930 JSType js::TypeOfObject(JSObject* obj) {
931 AutoUnsafeCallWithABI unsafe;
932 if (EmulatesUndefined(obj)) {
933 return JSTYPE_UNDEFINED;
934 }
935 if (obj->isCallable()) {
936 return JSTYPE_FUNCTION;
937 }
938 return JSTYPE_OBJECT;
939 }
940
941 JSType js::TypeOfValue(const Value& v) {
942 switch (v.type()) {
943 case ValueType::Double:
944 case ValueType::Int32:
945 return JSTYPE_NUMBER;
946 case ValueType::String:
947 return JSTYPE_STRING;
948 case ValueType::Null:
949 return JSTYPE_OBJECT;
950 case ValueType::Undefined:
951 return JSTYPE_UNDEFINED;
952 case ValueType::Object:
953 return TypeOfObject(&v.toObject());
954 case ValueType::Boolean:
955 return JSTYPE_BOOLEAN;
956 case ValueType::BigInt:
957 return JSTYPE_BIGINT;
958 case ValueType::Symbol:
959 return JSTYPE_SYMBOL;
960 case ValueType::Magic:
961 case ValueType::PrivateGCThing:
962 break;
963 }
964
965 ReportBadValueTypeAndCrash(v);
966 }
967
968 bool js::CheckClassHeritageOperation(JSContext* cx, HandleValue heritage) {
969 if (IsConstructor(heritage)) {
970 return true;
971 }
972
973 if (heritage.isNull()) {
974 return true;
975 }
976
977 if (heritage.isObject()) {
978 ReportIsNotFunction(cx, heritage, 0, CONSTRUCT);
979 return false;
980 }
981
982 ReportValueError(cx, JSMSG_BAD_HERITAGE, -1, heritage, nullptr,
983 "not an object or null");
984 return false;
985 }
986
987 PlainObject* js::ObjectWithProtoOperation(JSContext* cx, HandleValue val) {
988 if (!val.isObjectOrNull()) {
989 ReportValueError(cx, JSMSG_NOT_OBJORNULL, -1, val, nullptr);
990 return nullptr;
991 }
992
993 RootedObject proto(cx, val.toObjectOrNull());
994 return NewPlainObjectWithProto(cx, proto);
995 }
996
997 JSObject* js::FunWithProtoOperation(JSContext* cx, HandleFunction fun,
998 HandleObject parent, HandleObject proto) {
999 return CloneFunctionReuseScript(cx, fun, parent, proto);
1000 }
1001
1002 /*
1003 * Enter the new with environment using an object at sp[-1] and associate the
1004 * depth of the with block with sp + stackIndex.
1005 */
1006 bool js::EnterWithOperation(JSContext* cx, AbstractFramePtr frame,
1007 HandleValue val, Handle<WithScope*> scope) {
1008 RootedObject obj(cx);
1009 if (val.isObject()) {
1010 obj = &val.toObject();
1011 } else {
1012 obj = ToObject(cx, val);
1013 if (!obj) {
1014 return false;
1015 }
1016 }
1017
1018 RootedObject envChain(cx, frame.environmentChain());
1019 WithEnvironmentObject* withobj = WithEnvironmentObject::create(
1020 cx, obj, envChain, scope, JS::SupportUnscopables::Yes);
1021 if (!withobj) {
1022 return false;
1023 }
1024
1025 frame.pushOnEnvironmentChain(*withobj);
1026 return true;
1027 }
1028
1029 static void PopEnvironment(JSContext* cx, EnvironmentIter& ei) {
1030 switch (ei.scope().kind()) {
1031 case ScopeKind::Lexical:
1032 case ScopeKind::SimpleCatch:
1033 case ScopeKind::Catch:
1034 case ScopeKind::NamedLambda:
1035 case ScopeKind::StrictNamedLambda:
1036 case ScopeKind::FunctionLexical:
1037 case ScopeKind::ClassBody:
1038 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
1039 DebugEnvironments::onPopLexical(cx, ei);
1040 }
1041 if (ei.scope().hasEnvironment()) {
1042 ei.initialFrame()
1043 .popOffEnvironmentChain<ScopedLexicalEnvironmentObject>();
1044 }
1045 break;
1046 case ScopeKind::With:
1047 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
1048 DebugEnvironments::onPopWith(ei.initialFrame());
1049 }
1050 ei.initialFrame().popOffEnvironmentChain<WithEnvironmentObject>();
1051 break;
1052 case ScopeKind::Function:
1053 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
1054 DebugEnvironments::onPopCall(cx, ei.initialFrame());
1055 }
1056 if (ei.scope().hasEnvironment()) {
1057 ei.initialFrame().popOffEnvironmentChain<CallObject>();
1058 }
1059 break;
1060 case ScopeKind::FunctionBodyVar:
1061 case ScopeKind::StrictEval:
1062 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
1063 DebugEnvironments::onPopVar(cx, ei);
1064 }
1065 if (ei.scope().hasEnvironment()) {
1066 ei.initialFrame().popOffEnvironmentChain<VarEnvironmentObject>();
1067 }
1068 break;
1069 case ScopeKind::Module:
1070 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
1071 DebugEnvironments::onPopModule(cx, ei);
1072 }
1073 break;
1074 case ScopeKind::Eval:
1075 case ScopeKind::Global:
1076 case ScopeKind::NonSyntactic:
1077 break;
1078 case ScopeKind::WasmInstance:
1079 case ScopeKind::WasmFunction:
1080 MOZ_CRASH("wasm is not interpreted");
1081 break;
1082 }
1083 }
1084
1085 // Unwind environment chain and iterator to match the env corresponding to
1086 // the given bytecode position.
1087 void js::UnwindEnvironment(JSContext* cx, EnvironmentIter& ei, jsbytecode* pc) {
1088 if (!ei.withinInitialFrame()) {
1089 return;
1090 }
1091
1092 Rooted<Scope*> scope(cx, ei.initialFrame().script()->innermostScope(pc));
1093
1094 #ifdef DEBUG
1095 // A frame's environment chain cannot be unwound to anything enclosing the
1096 // body scope of a script. This includes the parameter defaults
1097 // environment and the decl env object. These environments, once pushed
1098 // onto the environment chain, are expected to be there for the duration
1099 // of the frame.
1100 //
1101 // Attempting to unwind to the parameter defaults code in a script is a
1102 // bug; that section of code has no try-catch blocks.
1103 JSScript* script = ei.initialFrame().script();
1104 for (uint32_t i = 0; i < script->bodyScopeIndex(); i++) {
1105 MOZ_ASSERT(scope != script->getScope(GCThingIndex(i)));
1106 }
1107 #endif
1108
1109 for (; ei.maybeScope() != scope; ei++) {
1110 PopEnvironment(cx, ei);
1111 }
1112 }
1113
1114 // Unwind all environments. This is needed because block scopes may cover the
1115 // first bytecode at a script's main(). e.g.,
1116 //
1117 // function f() { { let i = 0; } }
1118 //
1119 // will have no pc location distinguishing the first block scope from the
1120 // outermost function scope.
1121 void js::UnwindAllEnvironmentsInFrame(JSContext* cx, EnvironmentIter& ei) {
1122 for (; ei.withinInitialFrame(); ei++) {
1123 PopEnvironment(cx, ei);
1124 }
1125 }
1126
1127 // Compute the pc needed to unwind the environment to the beginning of a try
1128 // block. We cannot unwind to *after* the JSOp::Try, because that might be the
1129 // first opcode of an inner scope, with the same problem as above. e.g.,
1130 //
1131 // try { { let x; } }
1132 //
1133 // will have no pc location distinguishing the try block scope from the inner
1134 // let block scope.
1135 jsbytecode* js::UnwindEnvironmentToTryPc(JSScript* script, const TryNote* tn) {
1136 jsbytecode* pc = script->offsetToPC(tn->start);
1137 if (tn->kind() == TryNoteKind::Catch || tn->kind() == TryNoteKind::Finally) {
1138 pc -= JSOpLength_Try;
1139 MOZ_ASSERT(JSOp(*pc) == JSOp::Try);
1140 } else if (tn->kind() == TryNoteKind::Destructuring) {
1141 pc -= JSOpLength_TryDestructuring;
1142 MOZ_ASSERT(JSOp(*pc) == JSOp::TryDestructuring);
1143 }
1144 return pc;
1145 }
1146
1147 static void SettleOnTryNote(JSContext* cx, const TryNote* tn,
1148 EnvironmentIter& ei, InterpreterRegs& regs) {
1149 // Unwind the environment to the beginning of the JSOp::Try.
1150 UnwindEnvironment(cx, ei, UnwindEnvironmentToTryPc(regs.fp()->script(), tn));
1151
1152 // Set pc to the first bytecode after the the try note to point
1153 // to the beginning of catch or finally.
1154 regs.pc = regs.fp()->script()->offsetToPC(tn->start + tn->length);
1155 regs.sp = regs.spForStackDepth(tn->stackDepth);
1156 }
1157
1158 class InterpreterTryNoteFilter {
1159 const InterpreterRegs& regs_;
1160
1161 public:
1162 explicit InterpreterTryNoteFilter(const InterpreterRegs& regs)
1163 : regs_(regs) {}
1164 bool operator()(const TryNote* note) {
1165 return note->stackDepth <= regs_.stackDepth();
1166 }
1167 };
1168
1169 class TryNoteIterInterpreter : public TryNoteIter<InterpreterTryNoteFilter> {
1170 public:
1171 TryNoteIterInterpreter(JSContext* cx, const InterpreterRegs& regs)
1172 : TryNoteIter(cx, regs.fp()->script(), regs.pc,
1173 InterpreterTryNoteFilter(regs)) {}
1174 };
1175
1176 static void UnwindIteratorsForUncatchableException(
1177 JSContext* cx, const InterpreterRegs& regs) {
1178 // c.f. the regular (catchable) TryNoteIterInterpreter loop in
1179 // ProcessTryNotes.
1180 for (TryNoteIterInterpreter tni(cx, regs); !tni.done(); ++tni) {
1181 const TryNote* tn = *tni;
1182 switch (tn->kind()) {
1183 case TryNoteKind::ForIn: {
1184 Value* sp = regs.spForStackDepth(tn->stackDepth);
1185 UnwindIteratorForUncatchableException(&sp[-1].toObject());
1186 break;
1187 }
1188 default:
1189 break;
1190 }
1191 }
1192 }
1193
1194 enum HandleErrorContinuation {
1195 SuccessfulReturnContinuation,
1196 ErrorReturnContinuation,
1197 CatchContinuation,
1198 FinallyContinuation
1199 };
1200
1201 static HandleErrorContinuation ProcessTryNotes(JSContext* cx,
1202 EnvironmentIter& ei,
1203 InterpreterRegs& regs) {
1204 for (TryNoteIterInterpreter tni(cx, regs); !tni.done(); ++tni) {
1205 const TryNote* tn = *tni;
1206
1207 switch (tn->kind()) {
1208 case TryNoteKind::Catch:
1209 /* Catch cannot intercept the closing of a generator. */
1210 if (cx->isClosingGenerator()) {
1211 break;
1212 }
1213
1214 SettleOnTryNote(cx, tn, ei, regs);
1215 return CatchContinuation;
1216
1217 case TryNoteKind::Finally:
1218 SettleOnTryNote(cx, tn, ei, regs);
1219 return FinallyContinuation;
1220
1221 case TryNoteKind::ForIn: {
1222 /* This is similar to JSOp::EndIter in the interpreter loop. */
1223 MOZ_ASSERT(tn->stackDepth <= regs.stackDepth());
1224 Value* sp = regs.spForStackDepth(tn->stackDepth);
1225 JSObject* obj = &sp[-1].toObject();
1226 CloseIterator(obj);
1227 break;
1228 }
1229
1230 case TryNoteKind::Destructuring: {
1231 // Whether the destructuring iterator is done is at the top of the
1232 // stack. The iterator object is second from the top.
1233 MOZ_ASSERT(tn->stackDepth > 1);
1234 Value* sp = regs.spForStackDepth(tn->stackDepth);
1235 RootedValue doneValue(cx, sp[-1]);
1236 MOZ_RELEASE_ASSERT(!doneValue.isMagic());
1237 bool done = ToBoolean(doneValue);
1238 if (!done) {
1239 RootedObject iterObject(cx, &sp[-2].toObject());
1240 if (!IteratorCloseForException(cx, iterObject)) {
1241 SettleOnTryNote(cx, tn, ei, regs);
1242 return ErrorReturnContinuation;
1243 }
1244 }
1245 break;
1246 }
1247
1248 case TryNoteKind::ForOf:
1249 case TryNoteKind::Loop:
1250 break;
1251
1252 // TryNoteKind::ForOfIterClose is handled internally by the try note
1253 // iterator.
1254 default:
1255 MOZ_CRASH("Invalid try note");
1256 }
1257 }
1258
1259 return SuccessfulReturnContinuation;
1260 }
1261
1262 bool js::HandleClosingGeneratorReturn(JSContext* cx, AbstractFramePtr frame,
1263 bool ok) {
1264 /*
1265 * Propagate the exception or error to the caller unless the exception
1266 * is an asynchronous return from a generator.
1267 */
1268 if (cx->isClosingGenerator()) {
1269 cx->clearPendingException();
1270 ok = true;
1271 auto* genObj = GetGeneratorObjectForFrame(cx, frame);
1272 genObj->setClosed(cx);
1273 }
1274 return ok;
1275 }
1276
1277 static HandleErrorContinuation HandleError(JSContext* cx,
1278 InterpreterRegs& regs) {
1279 MOZ_ASSERT(regs.fp()->script()->containsPC(regs.pc));
1280 MOZ_ASSERT(cx->realm() == regs.fp()->script()->realm());
1281
1282 if (regs.fp()->script()->hasScriptCounts()) {
1283 PCCounts* counts = regs.fp()->script()->getThrowCounts(regs.pc);
1284 // If we failed to allocate, then skip the increment and continue to
1285 // handle the exception.
1286 if (counts) {
1287 counts->numExec()++;
1288 }
1289 }
1290
1291 EnvironmentIter ei(cx, regs.fp(), regs.pc);
1292 bool ok = false;
1293
1294 again:
1295 if (cx->isExceptionPending()) {
1296 /* Call debugger throw hooks. */
1297 if (!cx->isClosingGenerator()) {
1298 if (!DebugAPI::onExceptionUnwind(cx, regs.fp())) {
1299 if (!cx->isExceptionPending()) {
1300 goto again;
1301 }
1302 }
1303 // Ensure that the debugger hasn't returned 'true' while clearing the
1304 // exception state.
1305 MOZ_ASSERT(cx->isExceptionPending());
1306 }
1307
1308 HandleErrorContinuation res = ProcessTryNotes(cx, ei, regs);
1309 switch (res) {
1310 case SuccessfulReturnContinuation:
1311 break;
1312 case ErrorReturnContinuation:
1313 goto again;
1314 case CatchContinuation:
1315 case FinallyContinuation:
1316 // No need to increment the PCCounts number of execution here, as
1317 // the interpreter increments any PCCounts if present.
1318 MOZ_ASSERT_IF(regs.fp()->script()->hasScriptCounts(),
1319 regs.fp()->script()->maybeGetPCCounts(regs.pc));
1320 return res;
1321 }
1322
1323 ok = HandleClosingGeneratorReturn(cx, regs.fp(), ok);
1324 } else {
1325 UnwindIteratorsForUncatchableException(cx, regs);
1326
1327 // We may be propagating a forced return from a debugger hook function.
1328 if (MOZ_UNLIKELY(cx->isPropagatingForcedReturn())) {
1329 cx->clearPropagatingForcedReturn();
1330 ok = true;
1331 }
1332 }
1333
1334 ok = DebugAPI::onLeaveFrame(cx, regs.fp(), regs.pc, ok);
1335
1336 // After this point, we will pop the frame regardless. Settle the frame on
1337 // the end of the script.
1338 regs.setToEndOfScript();
1339
1340 return ok ? SuccessfulReturnContinuation : ErrorReturnContinuation;
1341 }
1342
1343 #define REGS (activation.regs())
1344 #define PUSH_COPY(v) \
1345 do { \
1346 *REGS.sp++ = (v); \
1347 cx->debugOnlyCheck(REGS.sp[-1]); \
1348 } while (0)
1349 #define PUSH_COPY_SKIP_CHECK(v) *REGS.sp++ = (v)
1350 #define PUSH_NULL() REGS.sp++->setNull()
1351 #define PUSH_UNDEFINED() REGS.sp++->setUndefined()
1352 #define PUSH_BOOLEAN(b) REGS.sp++->setBoolean(b)
1353 #define PUSH_DOUBLE(d) REGS.sp++->setDouble(d)
1354 #define PUSH_INT32(i) REGS.sp++->setInt32(i)
1355 #define PUSH_SYMBOL(s) REGS.sp++->setSymbol(s)
1356 #define PUSH_BIGINT(b) REGS.sp++->setBigInt(b)
1357 #define PUSH_STRING(s) \
1358 do { \
1359 REGS.sp++->setString(s); \
1360 cx->debugOnlyCheck(REGS.sp[-1]); \
1361 } while (0)
1362 #define PUSH_OBJECT(obj) \
1363 do { \
1364 REGS.sp++->setObject(obj); \
1365 cx->debugOnlyCheck(REGS.sp[-1]); \
1366 } while (0)
1367 #define PUSH_OBJECT_OR_NULL(obj) \
1368 do { \
1369 REGS.sp++->setObjectOrNull(obj); \
1370 cx->debugOnlyCheck(REGS.sp[-1]); \
1371 } while (0)
1372 #define PUSH_MAGIC(magic) REGS.sp++->setMagic(magic)
1373 #define POP_COPY_TO(v) (v) = *--REGS.sp
1374 #define POP_RETURN_VALUE() REGS.fp()->setReturnValue(*--REGS.sp)
1375
1376 /*
1377 * Same for JSOp::SetName and JSOp::SetProp, which differ only slightly but
1378 * remain distinct for the decompiler.
1379 */
1380 static_assert(JSOpLength_SetName == JSOpLength_SetProp);
1381
1382 /* See TRY_BRANCH_AFTER_COND. */
1383 static_assert(JSOpLength_JumpIfTrue == JSOpLength_JumpIfFalse);
1384 static_assert(uint8_t(JSOp::JumpIfTrue) == uint8_t(JSOp::JumpIfFalse) + 1);
1385
1386 /*
1387 * Compute the implicit |this| value used by a call expression with an
1388 * unqualified name reference. The environment the binding was found on is
1389 * passed as argument, env.
1390 *
1391 * The implicit |this| is |undefined| for all environment types except
1392 * WithEnvironmentObject. This is the case for |with(...) {...}| expressions or
1393 * if the embedding uses a non-syntactic WithEnvironmentObject.
1394 *
1395 * NOTE: A non-syntactic WithEnvironmentObject may have a corresponding
1396 * extensible LexicalEnviornmentObject, but it will not be considered as an
1397 * implicit |this|. This is for compatibility with the Gecko subscript loader.
1398 */
1399 static inline Value ComputeImplicitThis(JSObject* env) {
1400 // Fast-path for GlobalObject
1401 if (env->is<GlobalObject>()) {
1402 return UndefinedValue();
1403 }
1404
1405 // WithEnvironmentObjects have an actual implicit |this|
1406 if (env->is<WithEnvironmentObject>()) {
1407 auto* thisObject = env->as<WithEnvironmentObject>().withThis();
1408 return ObjectValue(*thisObject);
1409 }
1410
1411 // Debugger environments need special casing, as despite being
1412 // non-syntactic, they wrap syntactic environments and should not be
1413 // treated like other embedding-specific non-syntactic environments.
1414 if (env->is<DebugEnvironmentProxy>()) {
1415 return ComputeImplicitThis(&env->as<DebugEnvironmentProxy>().environment());
1416 }
1417
1418 MOZ_ASSERT(env->is<EnvironmentObject>());
1419 return UndefinedValue();
1420 }
1421
1422 // BigInt proposal 3.2.4 Abstract Relational Comparison
1423 // Returns Nothing when at least one operand is a NaN, or when
1424 // ToNumeric or StringToBigInt can't interpret a string as a numeric
1425 // value. (These cases correspond to a NaN result in the spec.)
1426 // Otherwise, return a boolean to indicate whether lhs is less than
1427 // rhs. The operands must be primitives; the caller is responsible for
1428 // evaluating them in the correct order.
1429 static MOZ_ALWAYS_INLINE bool LessThanImpl(JSContext* cx,
1430 MutableHandleValue lhs,
1431 MutableHandleValue rhs,
1432 mozilla::Maybe<bool>& res) {
1433 // Steps 1 and 2 are performed by the caller.
1434
1435 // Step 3.
1436 if (lhs.isString() && rhs.isString()) {
1437 JSString* l = lhs.toString();
1438 JSString* r = rhs.toString();
1439 int32_t result;
1440 if (!CompareStrings(cx, l, r, &result)) {
1441 return false;
1442 }
1443 res = mozilla::Some(result < 0);
1444 return true;
1445 }
1446
1447 // Step 4a.
1448 if (lhs.isBigInt() && rhs.isString()) {
1449 return BigInt::lessThan(cx, lhs, rhs, res);
1450 }
1451
1452 // Step 4b.
1453 if (lhs.isString() && rhs.isBigInt()) {
1454 return BigInt::lessThan(cx, lhs, rhs, res);
1455 }
1456
1457 // Steps 4c and 4d.
1458 if (!ToNumeric(cx, lhs) || !ToNumeric(cx, rhs)) {
1459 return false;
1460 }
1461
1462 // Steps 4e-j.
1463 if (lhs.isBigInt() || rhs.isBigInt()) {
1464 return BigInt::lessThan(cx, lhs, rhs, res);
1465 }
1466
1467 // Step 4e for Number operands.
1468 MOZ_ASSERT(lhs.isNumber() && rhs.isNumber());
1469 double lhsNum = lhs.toNumber();
1470 double rhsNum = rhs.toNumber();
1471
1472 if (std::isnan(lhsNum) || std::isnan(rhsNum)) {
1473 res = mozilla::Maybe<bool>(mozilla::Nothing());
1474 return true;
1475 }
1476
1477 res = mozilla::Some(lhsNum < rhsNum);
1478 return true;
1479 }
1480
1481 static MOZ_ALWAYS_INLINE bool LessThanOperation(JSContext* cx,
1482 MutableHandleValue lhs,
1483 MutableHandleValue rhs,
1484 bool* res) {
1485 if (lhs.isInt32() && rhs.isInt32()) {
1486 *res = lhs.toInt32() < rhs.toInt32();
1487 return true;
1488 }
1489
1490 if (!ToPrimitive(cx, JSTYPE_NUMBER, lhs)) {
1491 return false;
1492 }
1493
1494 if (!ToPrimitive(cx, JSTYPE_NUMBER, rhs)) {
1495 return false;
1496 }
1497
1498 mozilla::Maybe<bool> tmpResult;
1499 if (!LessThanImpl(cx, lhs, rhs, tmpResult)) {
1500 return false;
1501 }
1502 *res = tmpResult.valueOr(false);
1503 return true;
1504 }
1505
1506 static MOZ_ALWAYS_INLINE bool LessThanOrEqualOperation(JSContext* cx,
1507 MutableHandleValue lhs,
1508 MutableHandleValue rhs,
1509 bool* res) {
1510 if (lhs.isInt32() && rhs.isInt32()) {
1511 *res = lhs.toInt32() <= rhs.toInt32();
1512 return true;
1513 }
1514
1515 if (!ToPrimitive(cx, JSTYPE_NUMBER, lhs)) {
1516 return false;
1517 }
1518
1519 if (!ToPrimitive(cx, JSTYPE_NUMBER, rhs)) {
1520 return false;
1521 }
1522
1523 mozilla::Maybe<bool> tmpResult;
1524 if (!LessThanImpl(cx, rhs, lhs, tmpResult)) {
1525 return false;
1526 }
1527 *res = !tmpResult.valueOr(true);
1528 return true;
1529 }
1530
1531 static MOZ_ALWAYS_INLINE bool GreaterThanOperation(JSContext* cx,
1532 MutableHandleValue lhs,
1533 MutableHandleValue rhs,
1534 bool* res) {
1535 if (lhs.isInt32() && rhs.isInt32()) {
1536 *res = lhs.toInt32() > rhs.toInt32();
1537 return true;
1538 }
1539
1540 if (!ToPrimitive(cx, JSTYPE_NUMBER, lhs)) {
1541 return false;
1542 }
1543
1544 if (!ToPrimitive(cx, JSTYPE_NUMBER, rhs)) {
1545 return false;
1546 }
1547
1548 mozilla::Maybe<bool> tmpResult;
1549 if (!LessThanImpl(cx, rhs, lhs, tmpResult)) {
1550 return false;
1551 }
1552 *res = tmpResult.valueOr(false);
1553 return true;
1554 }
1555
1556 static MOZ_ALWAYS_INLINE bool GreaterThanOrEqualOperation(
1557 JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs, bool* res) {
1558 if (lhs.isInt32() && rhs.isInt32()) {
1559 *res = lhs.toInt32() >= rhs.toInt32();
1560 return true;
1561 }
1562
1563 if (!ToPrimitive(cx, JSTYPE_NUMBER, lhs)) {
1564 return false;
1565 }
1566
1567 if (!ToPrimitive(cx, JSTYPE_NUMBER, rhs)) {
1568 return false;
1569 }
1570
1571 mozilla::Maybe<bool> tmpResult;
1572 if (!LessThanImpl(cx, lhs, rhs, tmpResult)) {
1573 return false;
1574 }
1575 *res = !tmpResult.valueOr(true);
1576 return true;
1577 }
1578
1579 static MOZ_ALWAYS_INLINE bool SetObjectElementOperation(
1580 JSContext* cx, HandleObject obj, HandleId id, HandleValue value,
1581 HandleValue receiver, bool strict) {
1582 ObjectOpResult result;
1583 return SetProperty(cx, obj, id, value, receiver, result) &&
1584 result.checkStrictModeError(cx, obj, id, strict);
1585 }
1586
1587 void js::ReportInNotObjectError(JSContext* cx, HandleValue lref,
1588 HandleValue rref) {
1589 auto uniqueCharsFromString = [](JSContext* cx,
1590 HandleValue ref) -> UniqueChars {
1591 static const size_t MaxStringLength = 16;
1592 RootedString str(cx, ref.toString());
1593 if (str->length() > MaxStringLength) {
1594 JSStringBuilder buf(cx);
1595 if (!buf.appendSubstring(str, 0, MaxStringLength)) {
1596 return nullptr;
1597 }
1598 if (!buf.append("...")) {
1599 return nullptr;
1600 }
1601 str = buf.finishString();
1602 if (!str) {
1603 return nullptr;
1604 }
1605 }
1606 return QuoteString(cx, str, '"');
1607 };
1608
1609 if (lref.isString() && rref.isString()) {
1610 UniqueChars lbytes = uniqueCharsFromString(cx, lref);
1611 if (!lbytes) {
1612 return;
1613 }
1614 UniqueChars rbytes = uniqueCharsFromString(cx, rref);
1615 if (!rbytes) {
1616 return;
1617 }
1618 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, JSMSG_IN_STRING,
1619 lbytes.get(), rbytes.get());
1620 return;
1621 }
1622
1623 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_IN_NOT_OBJECT,
1624 InformalValueTypeName(rref));
1625 }
1626
1627 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1628 // Explicit Resource Management Proposal
1629 // 7.5.6 GetDisposeMethod ( V, hint )
1630 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-getdisposemethod
1631 // Steps 1.b.ii.1.a-f
1632 bool js::SyncDisposalClosure(JSContext* cx, unsigned argc, JS::Value* vp) {
1633 JS::CallArgs args = CallArgsFromVp(argc, vp);
1634
1635 JS::Rooted<JSFunction*> callee(cx, &args.callee().as<JSFunction>());
1636
1637 JS::Rooted<JS::Value> method(
1638 cx, callee->getExtendedSlot(uint8_t(SyncDisposalClosureSlots::Method)));
1639
1640 // Step 1.b.ii.1.a. Let O be the this value.
1641 JS::Rooted<JS::Value> O(cx, args.thisv());
1642
1643 // Step 1.b.ii.1.b. Let promiseCapability be !
1644 // NewPromiseCapability(%Promise%).
1645 JSObject* createPromise = JS::NewPromiseObject(cx, nullptr);
1646 if (!createPromise) {
1647 return false;
1648 }
1649 JS::Rooted<PromiseObject*> promiseCapability(
1650 cx, &createPromise->as<PromiseObject>());
1651
1652 // Step 1.b.ii.1.c. Let result be Completion(Call(method, O)).
1653 JS::Rooted<JS::Value> rval(cx);
1654 bool result = Call(cx, method, O, &rval);
1655
1656 // Step 1.b.ii.1.d. IfAbruptRejectPromise(result, promiseCapability).
1657 if (!result) {
1658 return AbruptRejectPromise(cx, args, promiseCapability, nullptr);
1659 }
1660
1661 // Step 1.b.ii.1.e. Perform ? Call(promiseCapability.[[Resolve]], undefined, «
1662 // undefined »).
1663 if (!JS::ResolvePromise(cx, promiseCapability, JS::UndefinedHandleValue)) {
1664 return false;
1665 }
1666
1667 // Step 1.b.ii.1.f. Return promiseCapability.[[Promise]].
1668 args.rval().set(JS::ObjectValue(*promiseCapability));
1669 return true;
1670 }
1671
1672 // Explicit Resource Management Proposal
1673 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-disposeresources
1674 // Steps 3.e.iii.1.c-e.
1675 ErrorObject* js::CreateSuppressedError(JSContext* cx,
1676 JS::Handle<JS::Value> error,
1677 JS::Handle<JS::Value> suppressed) {
1678 // Step 3.e.iii.1.c. Let error be a newly created SuppressedError object.
1679 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
1680 JSMSG_ERROR_WAS_SUPPRESSED);
1681
1682 if (cx->isThrowingOutOfMemory()) {
1683 return nullptr;
1684 }
1685
1686 JS::Rooted<JS::Value> thrownSuppressed(cx);
1687
1688 if (!cx->getPendingException(&thrownSuppressed)) {
1689 return nullptr;
1690 }
1691
1692 if (!thrownSuppressed.isObject() ||
1693 !thrownSuppressed.toObject().is<ErrorObject>()) {
1694 return nullptr;
1695 }
1696
1697 cx->clearPendingException();
1698
1699 JS::Rooted<ErrorObject*> errorObj(
1700 cx, &thrownSuppressed.toObject().as<ErrorObject>());
1701
1702 // Step 3.e.iii.1.d. Perform
1703 // CreateNonEnumerableDataPropertyOrThrow(error, "error", result).
1704 if (!NativeDefineDataProperty(cx, errorObj, cx->names().error, error, 0)) {
1705 return nullptr;
1706 }
1707
1708 // Step 3.e.iii.1.e. Perform
1709 // CreateNonEnumerableDataPropertyOrThrow(error, "suppressed",
1710 // suppressed).
1711 if (!NativeDefineDataProperty(cx, errorObj, cx->names().suppressed,
1712 suppressed, 0)) {
1713 return nullptr;
1714 }
1715
1716 // TODO: Improve the capturing of stack and error messages (Bug 1906150)
1717
1718 return errorObj;
1719 }
1720
1721 // Explicit Resource Management Proposal
1722 // 7.5.4 AddDisposableResource ( disposeCapability, V, hint [ , method ] )
1723 // https://arai-a.github.io/ecma262-compare/?pr=3000&id=sec-adddisposableresource
1724 // Step 3
1725 bool js::AddDisposableResourceToCapability(JSContext* cx,
1726 JS::Handle<JSObject*> env,
1727 JS::Handle<JS::Value> val,
1728 JS::Handle<JS::Value> method,
1729 bool needsClosure, UsingHint hint) {
1730 JS::Rooted<ArrayObject*> disposeCapability(
1731 cx,
1732 env->as<DisposableEnvironmentObject>().getOrCreateDisposeCapability(cx));
1733 if (!disposeCapability) {
1734 return false;
1735 }
1736
1737 JS::Rooted<JS::Value> disposeMethod(cx);
1738
1739 if (needsClosure) {
1740 JS::Handle<PropertyName*> funName = cx->names().empty_;
1741 JSFunction* asyncWrapper =
1742 NewNativeFunction(cx, SyncDisposalClosure, 0, funName,
1743 gc::AllocKind::FUNCTION_EXTENDED, GenericObject);
1744
1745 if (!asyncWrapper) {
1746 return false;
1747 }
1748 asyncWrapper->initExtendedSlot(uint8_t(SyncDisposalClosureSlots::Method),
1749 method);
1750 disposeMethod.set(JS::ObjectValue(*asyncWrapper));
1751 } else {
1752 disposeMethod.set(method);
1753 }
1754
1755 DisposableRecordObject* disposableRecord =
1756 DisposableRecordObject::create(cx, val, disposeMethod, hint);
1757 if (!disposableRecord) {
1758 return false;
1759 }
1760
1761 return NewbornArrayPush(cx, disposeCapability,
1762 JS::ObjectValue(*disposableRecord));
1763 }
1764 #endif
1765
1766 bool MOZ_NEVER_INLINE JS_HAZ_JSNATIVE_CALLER js::Interpret(JSContext* cx,
1767 RunState& state) {
1768 /*
1769 * Define macros for an interpreter loop. Opcode dispatch is done by
1770 * indirect goto (aka a threaded interpreter), which is technically
1771 * non-standard but is supported by all of our supported compilers.
1772 */
1773 #define INTERPRETER_LOOP()
1774 #define CASE(OP) label_##OP:
1775 #define DEFAULT() \
1776 label_default:
1777 #define DISPATCH_TO(OP) goto* addresses[(OP)]
1778
1779 #define LABEL(X) (&&label_##X)
1780
1781 // Use addresses instead of offsets to optimize for runtime speed over
1782 // load-time relocation overhead.
1783 static const void* const addresses[EnableInterruptsPseudoOpcode + 1] = {
1784 #define OPCODE_LABEL(op, ...) LABEL(op),
1785 FOR_EACH_OPCODE(OPCODE_LABEL)
1786 #undef OPCODE_LABEL
1787 #define TRAILING_LABEL(v) \
1788 ((v) == EnableInterruptsPseudoOpcode ? LABEL(EnableInterruptsPseudoOpcode) \
1789 : LABEL(default)),
1790 FOR_EACH_TRAILING_UNUSED_OPCODE(TRAILING_LABEL)
1791 #undef TRAILING_LABEL
1792 };
1793
1794 /*
1795 * Increment REGS.pc by N, load the opcode at that position,
1796 * and jump to the code to execute it.
1797 *
1798 * When Debugger puts a script in single-step mode, all js::Interpret
1799 * invocations that might be presently running that script must have
1800 * interrupts enabled. It's not practical to simply check
1801 * script->stepModeEnabled() at each point some callee could have changed
1802 * it, because there are so many places js::Interpret could possibly cause
1803 * JavaScript to run: each place an object might be coerced to a primitive
1804 * or a number, for example. So instead, we expose a simple mechanism to
1805 * let Debugger tweak the affected js::Interpret frames when an onStep
1806 * handler is added: calling activation.enableInterruptsUnconditionally()
1807 * will enable interrupts, and activation.opMask() is or'd with the opcode
1808 * to implement a simple alternate dispatch.
1809 */
1810 #define ADVANCE_AND_DISPATCH(N) \
1811 JS_BEGIN_MACRO \
1812 REGS.pc += (N); \
1813 SANITY_CHECKS(); \
1814 DISPATCH_TO(*REGS.pc | activation.opMask()); \
1815 JS_END_MACRO
1816
1817 /*
1818 * Shorthand for the common sequence at the end of a fixed-size opcode.
1819 */
1820 #define END_CASE(OP) ADVANCE_AND_DISPATCH(JSOpLength_##OP);
1821
1822 /*
1823 * Prepare to call a user-supplied branch handler, and abort the script
1824 * if it returns false.
1825 */
1826 #define CHECK_BRANCH() \
1827 JS_BEGIN_MACRO \
1828 if (!CheckForInterrupt(cx)) goto error; \
1829 JS_END_MACRO
1830
1831 /*
1832 * This is a simple wrapper around ADVANCE_AND_DISPATCH which also does
1833 * a CHECK_BRANCH() if n is not positive, which possibly indicates that it
1834 * is the backedge of a loop.
1835 */
1836 #define BRANCH(n) \
1837 JS_BEGIN_MACRO \
1838 int32_t nlen = (n); \
1839 if (nlen <= 0) CHECK_BRANCH(); \
1840 ADVANCE_AND_DISPATCH(nlen); \
1841 JS_END_MACRO
1842
1843 /*
1844 * Initialize code coverage vectors.
1845 */
1846 #define INIT_COVERAGE() \
1847 JS_BEGIN_MACRO \
1848 if (!script->hasScriptCounts()) { \
1849 if (cx->realm()->collectCoverageForDebug()) { \
1850 if (!script->initScriptCounts(cx)) goto error; \
1851 } \
1852 } \
1853 JS_END_MACRO
1854
1855 /*
1856 * Increment the code coverage counter associated with the given pc.
1857 */
1858 #define COUNT_COVERAGE_PC(PC) \
1859 JS_BEGIN_MACRO \
1860 if (script->hasScriptCounts()) { \
1861 PCCounts* counts = script->maybeGetPCCounts(PC); \
1862 MOZ_ASSERT(counts); \
1863 counts->numExec()++; \
1864 } \
1865 JS_END_MACRO
1866
1867 #define COUNT_COVERAGE_MAIN() \
1868 JS_BEGIN_MACRO \
1869 jsbytecode* main = script->main(); \
1870 if (!BytecodeIsJumpTarget(JSOp(*main))) COUNT_COVERAGE_PC(main); \
1871 JS_END_MACRO
1872
1873 #define COUNT_COVERAGE() \
1874 JS_BEGIN_MACRO \
1875 MOZ_ASSERT(BytecodeIsJumpTarget(JSOp(*REGS.pc))); \
1876 COUNT_COVERAGE_PC(REGS.pc); \
1877 JS_END_MACRO
1878
1879 #define SET_SCRIPT(s) \
1880 JS_BEGIN_MACRO \
1881 script = (s); \
1882 MOZ_ASSERT(cx->realm() == script->realm()); \
1883 if (DebugAPI::hasAnyBreakpointsOrStepMode(script) || \
1884 script->hasScriptCounts()) \
1885 activation.enableInterruptsUnconditionally(); \
1886 JS_END_MACRO
1887
1888 #define SANITY_CHECKS() \
1889 JS_BEGIN_MACRO \
1890 js::gc::MaybeVerifyBarriers(cx); \
1891 JS_END_MACRO
1892
1893 // Verify that an uninitialized lexical is followed by a correct check op.
1894 #ifdef DEBUG
1895 # define ASSERT_UNINITIALIZED_ALIASED_LEXICAL(val) \
1896 JS_BEGIN_MACRO \
1897 if (IsUninitializedLexical(val)) { \
1898 JSOp next = JSOp(*GetNextPc(REGS.pc)); \
1899 MOZ_ASSERT(next == JSOp::CheckThis || next == JSOp::CheckReturn || \
1900 next == JSOp::CheckThisReinit || \
1901 next == JSOp::CheckAliasedLexical); \
1902 } \
1903 JS_END_MACRO
1904 #else
1905 # define ASSERT_UNINITIALIZED_ALIASED_LEXICAL(val) \
1906 JS_BEGIN_MACRO \
1907 /* nothing */ \
1908 JS_END_MACRO
1909 #endif
1910
1911 gc::MaybeVerifyBarriers(cx, true);
1912
1913 InterpreterFrame* entryFrame = state.pushInterpreterFrame(cx);
1914 if (!entryFrame) {
1915 return false;
1916 }
1917
1918 InterpreterActivation activation(state, cx, entryFrame);
1919
1920 /* The script is used frequently, so keep a local copy. */
1921 RootedScript script(cx);
1922 SET_SCRIPT(REGS.fp()->script());
1923
1924 /*
1925 * Pool of rooters for use in this interpreter frame. References to these
1926 * are used for local variables within interpreter cases. This avoids
1927 * creating new rooters each time an interpreter case is entered, and also
1928 * correctness pitfalls due to incorrect compilation of destructor calls
1929 * around computed gotos.
1930 */
1931 RootedTuple<Value, Value, JSObject*, JSObject*, JSFunction*, JSAtom*,
1932 PropertyName*, PropertyKey, JSScript*, Scope*>
1933 roots(cx);
1934 RootedField<Value, 0> rootValue0(roots);
1935 RootedField<Value, 1> rootValue1(roots);
1936 RootedField<JSObject*, 2> rootObject0(roots);
1937 RootedField<JSObject*, 3> rootObject1(roots);
1938 RootedField<JSFunction*> rootFunction0(roots);
1939 RootedField<JSAtom*> rootAtom0(roots);
1940 RootedField<PropertyName*> rootName0(roots);
1941 RootedField<PropertyKey> rootId0(roots);
1942 RootedField<JSScript*> rootScript0(roots);
1943 RootedField<Scope*> rootScope0(roots);
1944
1945 DebugOnly<uint32_t> blockDepth;
1946
1947 /* State communicated between non-local jumps: */
1948 bool interpReturnOK;
1949 bool frameHalfInitialized;
1950
1951 if (!activation.entryFrame()->prologue(cx)) {
1952 goto prologue_error;
1953 }
1954
1955 if (!DebugAPI::onEnterFrame(cx, activation.entryFrame())) {
1956 goto error;
1957 }
1958
1959 // Increment the coverage for the main entry point.
1960 INIT_COVERAGE();
1961 COUNT_COVERAGE_MAIN();
1962
1963 // Enter the interpreter loop starting at the current pc.
1964 ADVANCE_AND_DISPATCH(0);
1965
1966 INTERPRETER_LOOP() {
1967 CASE(EnableInterruptsPseudoOpcode) {
1968 bool moreInterrupts = false;
1969 jsbytecode op = *REGS.pc;
1970
1971 if (!script->hasScriptCounts() &&
1972 cx->realm()->collectCoverageForDebug()) {
1973 if (!script->initScriptCounts(cx)) {
1974 goto error;
1975 }
1976 }
1977
1978 if (script->isDebuggee()) {
1979 if (DebugAPI::stepModeEnabled(script)) {
1980 if (!DebugAPI::onSingleStep(cx)) {
1981 goto error;
1982 }
1983 moreInterrupts = true;
1984 }
1985
1986 if (DebugAPI::hasAnyBreakpointsOrStepMode(script)) {
1987 moreInterrupts = true;
1988 }
1989
1990 if (DebugAPI::hasBreakpointsAt(script, REGS.pc)) {
1991 if (!DebugAPI::onTrap(cx)) {
1992 goto error;
1993 }
1994 }
1995 }
1996
1997 MOZ_ASSERT(activation.opMask() == EnableInterruptsPseudoOpcode);
1998 if (!moreInterrupts) {
1999 activation.clearInterruptsMask();
2000 }
2001
2002 /* Commence executing the actual opcode. */
2003 SANITY_CHECKS();
2004 DISPATCH_TO(op);
2005 }
2006
2007 /* Various 1-byte no-ops. */
2008 CASE(Nop)
2009 CASE(Try)
2010 CASE(NopDestructuring)
2011 CASE(NopIsAssignOp)
2012 CASE(TryDestructuring) {
2013 MOZ_ASSERT(GetBytecodeLength(REGS.pc) == 1);
2014 ADVANCE_AND_DISPATCH(1);
2015 }
2016
2017 CASE(JumpTarget)
2018 COUNT_COVERAGE();
2019 END_CASE(JumpTarget)
2020
2021 CASE(LoopHead) {
2022 COUNT_COVERAGE();
2023
2024 // Attempt on-stack replacement into the Baseline Interpreter.
2025 if (jit::IsBaselineInterpreterEnabled()) {
2026 script->incWarmUpCounter();
2027
2028 jit::MethodStatus status =
2029 jit::CanEnterBaselineInterpreterAtBranch(cx, REGS.fp());
2030 if (status == jit::Method_Error) {
2031 goto error;
2032 }
2033 if (status == jit::Method_Compiled) {
2034 bool wasProfiler = REGS.fp()->hasPushedGeckoProfilerFrame();
2035
2036 jit::JitExecStatus maybeOsr;
2037 {
2038 GeckoProfilerBaselineOSRMarker osr(cx, wasProfiler);
2039 maybeOsr =
2040 jit::EnterBaselineInterpreterAtBranch(cx, REGS.fp(), REGS.pc);
2041 }
2042
2043 // We failed to call into baseline at all, so treat as an error.
2044 if (maybeOsr == jit::JitExec_Aborted) {
2045 goto error;
2046 }
2047
2048 interpReturnOK = (maybeOsr == jit::JitExec_Ok);
2049
2050 // Pop the profiler frame pushed by the interpreter. (The compiled
2051 // version of the function popped a copy of the frame pushed by the
2052 // OSR trampoline.)
2053 if (wasProfiler) {
2054 cx->geckoProfiler().exit(cx, script);
2055 }
2056
2057 if (activation.entryFrame() != REGS.fp()) {
2058 goto jit_return_pop_frame;
2059 }
2060 goto leave_on_safe_point;
2061 }
2062 }
2063 }
2064 END_CASE(LoopHead)
2065
2066 CASE(Lineno)
2067 END_CASE(Lineno)
2068
2069 CASE(ForceInterpreter) {
2070 // Ensure pattern matching still works.
2071 MOZ_ASSERT(script->hasForceInterpreterOp());
2072 }
2073 END_CASE(ForceInterpreter)
2074
2075 CASE(Undefined) { PUSH_UNDEFINED(); }
2076 END_CASE(Undefined)
2077
2078 CASE(Pop) { REGS.sp--; }
2079 END_CASE(Pop)
2080
2081 CASE(PopN) {
2082 MOZ_ASSERT(GET_UINT16(REGS.pc) <= REGS.stackDepth());
2083 REGS.sp -= GET_UINT16(REGS.pc);
2084 }
2085 END_CASE(PopN)
2086
2087 CASE(DupAt) {
2088 MOZ_ASSERT(GET_UINT24(REGS.pc) < REGS.stackDepth());
2089 unsigned i = GET_UINT24(REGS.pc);
2090 const Value& rref = REGS.sp[-int(i + 1)];
2091 PUSH_COPY(rref);
2092 }
2093 END_CASE(DupAt)
2094
2095 CASE(SetRval) { POP_RETURN_VALUE(); }
2096 END_CASE(SetRval)
2097
2098 CASE(GetRval) { PUSH_COPY(REGS.fp()->returnValue()); }
2099 END_CASE(GetRval)
2100
2101 CASE(EnterWith) {
2102 ReservedRooted<Value> val(&rootValue0, REGS.sp[-1]);
2103 REGS.sp--;
2104 ReservedRooted<Scope*> scope(&rootScope0, script->getScope(REGS.pc));
2105
2106 if (!EnterWithOperation(cx, REGS.fp(), val, scope.as<WithScope>())) {
2107 goto error;
2108 }
2109 }
2110 END_CASE(EnterWith)
2111
2112 CASE(LeaveWith) {
2113 REGS.fp()->popOffEnvironmentChain<WithEnvironmentObject>();
2114 }
2115 END_CASE(LeaveWith)
2116
2117 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
2118 CASE(AddDisposable) {
2119 ReservedRooted<JSObject*> env(&rootObject0,
2120 REGS.fp()->environmentChain());
2121
2122 ReservedRooted<JS::Value> needsClosure(&rootValue0);
2123 POP_COPY_TO(needsClosure);
2124
2125 ReservedRooted<JS::Value> method(&rootValue1);
2126 POP_COPY_TO(method);
2127
2128 JS::Rooted<JS::Value> val(cx);
2129 POP_COPY_TO(val);
2130
2131 UsingHint hint = UsingHint(GET_UINT8(REGS.pc));
2132
2133 if (!AddDisposableResourceToCapability(cx, env, val, method,
2134 needsClosure.toBoolean(), hint)) {
2135 goto error;
2136 }
2137 }
2138 END_CASE(AddDisposable)
2139
2140 CASE(TakeDisposeCapability) {
2141 ReservedRooted<JSObject*> env(&rootObject0,
2142 REGS.fp()->environmentChain());
2143 JS::Value maybeDisposables =
2144 env->as<DisposableEnvironmentObject>().getDisposables();
2145
2146 MOZ_ASSERT(maybeDisposables.isObject() || maybeDisposables.isUndefined());
2147
2148 if (maybeDisposables.isUndefined()) {
2149 PUSH_UNDEFINED();
2150 } else {
2151 PUSH_OBJECT(maybeDisposables.toObject());
2152 env->as<DisposableEnvironmentObject>().clearDisposables();
2153 }
2154 }
2155 END_CASE(TakeDisposeCapability)
2156
2157 CASE(CreateSuppressedError) {
2158 ReservedRooted<JS::Value> error(&rootValue0);
2159 ReservedRooted<JS::Value> suppressed(&rootValue1);
2160 POP_COPY_TO(suppressed);
2161 POP_COPY_TO(error);
2162 ErrorObject* errorObj = CreateSuppressedError(cx, error, suppressed);
2163 if (!errorObj) {
2164 goto error;
2165 }
2166 PUSH_OBJECT(*errorObj);
2167 }
2168 END_CASE(CreateSuppressedError)
2169 #endif
2170
2171 CASE(Return) {
2172 POP_RETURN_VALUE();
2173 /* FALL THROUGH */
2174 }
2175 CASE(RetRval) {
2176 /*
2177 * When the inlined frame exits with an exception or an error, ok will be
2178 * false after the inline_return label.
2179 */
2180 CHECK_BRANCH();
2181
2182 successful_return_continuation:
2183 interpReturnOK = true;
2184
2185 return_continuation:
2186 frameHalfInitialized = false;
2187
2188 prologue_return_continuation:
2189
2190 if (activation.entryFrame() != REGS.fp()) {
2191 // Stop the engine. (No details about which engine exactly, could be
2192 // interpreter, Baseline or IonMonkey.)
2193 if (MOZ_LIKELY(!frameHalfInitialized)) {
2194 interpReturnOK =
2195 DebugAPI::onLeaveFrame(cx, REGS.fp(), REGS.pc, interpReturnOK);
2196
2197 REGS.fp()->epilogue(cx, REGS.pc);
2198 }
2199
2200 jit_return_pop_frame:
2201
2202 activation.popInlineFrame(REGS.fp());
2203 {
2204 JSScript* callerScript = REGS.fp()->script();
2205 if (cx->realm() != callerScript->realm()) {
2206 cx->leaveRealm(callerScript->realm());
2207 }
2208 SET_SCRIPT(callerScript);
2209 }
2210
2211 jit_return:
2212
2213 MOZ_ASSERT(IsInvokePC(REGS.pc));
2214 MOZ_ASSERT(cx->realm() == script->realm());
2215
2216 /* Resume execution in the calling frame. */
2217 if (MOZ_LIKELY(interpReturnOK)) {
2218 if (JSOp(*REGS.pc) == JSOp::Resume) {
2219 ADVANCE_AND_DISPATCH(JSOpLength_Resume);
2220 }
2221
2222 MOZ_ASSERT(GetBytecodeLength(REGS.pc) == JSOpLength_Call);
2223 ADVANCE_AND_DISPATCH(JSOpLength_Call);
2224 }
2225
2226 goto error;
2227 } else {
2228 // Stack should be empty for the outer frame, unless we executed the
2229 // first |await| expression in an async function.
2230 MOZ_ASSERT(REGS.stackDepth() == 0 ||
2231 (JSOp(*REGS.pc) == JSOp::Await &&
2232 !REGS.fp()->isResumedGenerator()));
2233 }
2234 goto exit;
2235 }
2236
2237 CASE(Default) {
2238 REGS.sp--;
2239 /* FALL THROUGH */
2240 }
2241 CASE(Goto) { BRANCH(GET_JUMP_OFFSET(REGS.pc)); }
2242
2243 CASE(JumpIfFalse) {
2244 bool cond = ToBoolean(REGS.stackHandleAt(-1));
2245 REGS.sp--;
2246 if (!cond) {
2247 BRANCH(GET_JUMP_OFFSET(REGS.pc));
2248 }
2249 }
2250 END_CASE(JumpIfFalse)
2251
2252 CASE(JumpIfTrue) {
2253 bool cond = ToBoolean(REGS.stackHandleAt(-1));
2254 REGS.sp--;
2255 if (cond) {
2256 BRANCH(GET_JUMP_OFFSET(REGS.pc));
2257 }
2258 }
2259 END_CASE(JumpIfTrue)
2260
2261 CASE(Or) {
2262 bool cond = ToBoolean(REGS.stackHandleAt(-1));
2263 if (cond) {
2264 ADVANCE_AND_DISPATCH(GET_JUMP_OFFSET(REGS.pc));
2265 }
2266 }
2267 END_CASE(Or)
2268
2269 CASE(Coalesce) {
2270 MutableHandleValue res = REGS.stackHandleAt(-1);
2271 bool cond = !res.isNullOrUndefined();
2272 if (cond) {
2273 ADVANCE_AND_DISPATCH(GET_JUMP_OFFSET(REGS.pc));
2274 }
2275 }
2276 END_CASE(Coalesce)
2277
2278 CASE(And) {
2279 bool cond = ToBoolean(REGS.stackHandleAt(-1));
2280 if (!cond) {
2281 ADVANCE_AND_DISPATCH(GET_JUMP_OFFSET(REGS.pc));
2282 }
2283 }
2284 END_CASE(And)
2285
2286 #define FETCH_ELEMENT_ID(n, id) \
2287 JS_BEGIN_MACRO \
2288 if (!ToPropertyKey(cx, REGS.stackHandleAt(n), &(id))) goto error; \
2289 JS_END_MACRO
2290
2291 #define TRY_BRANCH_AFTER_COND(cond, spdec) \
2292 JS_BEGIN_MACRO \
2293 MOZ_ASSERT(GetBytecodeLength(REGS.pc) == 1); \
2294 unsigned diff_ = \
2295 (unsigned)GET_UINT8(REGS.pc) - (unsigned)JSOp::JumpIfFalse; \
2296 if (diff_ <= 1) { \
2297 REGS.sp -= (spdec); \
2298 if ((cond) == (diff_ != 0)) { \
2299 ++REGS.pc; \
2300 BRANCH(GET_JUMP_OFFSET(REGS.pc)); \
2301 } \
2302 ADVANCE_AND_DISPATCH(1 + JSOpLength_JumpIfFalse); \
2303 } \
2304 JS_END_MACRO
2305
2306 CASE(In) {
2307 HandleValue rref = REGS.stackHandleAt(-1);
2308 if (!rref.isObject()) {
2309 HandleValue lref = REGS.stackHandleAt(-2);
2310 ReportInNotObjectError(cx, lref, rref);
2311 goto error;
2312 }
2313 bool found;
2314 {
2315 ReservedRooted<JSObject*> obj(&rootObject0, &rref.toObject());
2316 ReservedRooted<jsid> id(&rootId0);
2317 FETCH_ELEMENT_ID(-2, id);
2318 if (!HasProperty(cx, obj, id, &found)) {
2319 goto error;
2320 }
2321 }
2322 TRY_BRANCH_AFTER_COND(found, 2);
2323 REGS.sp--;
2324 REGS.sp[-1].setBoolean(found);
2325 }
2326 END_CASE(In)
2327
2328 CASE(HasOwn) {
2329 HandleValue val = REGS.stackHandleAt(-1);
2330 HandleValue idval = REGS.stackHandleAt(-2);
2331
2332 bool found;
2333 if (!HasOwnProperty(cx, val, idval, &found)) {
2334 goto error;
2335 }
2336
2337 REGS.sp--;
2338 REGS.sp[-1].setBoolean(found);
2339 }
2340 END_CASE(HasOwn)
2341
2342 CASE(CheckPrivateField) {
2343 /* Load the object being initialized into lval/val. */
2344 HandleValue val = REGS.stackHandleAt(-2);
2345 HandleValue idval = REGS.stackHandleAt(-1);
2346
2347 bool result = false;
2348 if (!CheckPrivateFieldOperation(cx, REGS.pc, val, idval, &result)) {
2349 goto error;
2350 }
2351
2352 PUSH_BOOLEAN(result);
2353 }
2354 END_CASE(CheckPrivateField)
2355
2356 CASE(NewPrivateName) {
2357 ReservedRooted<JSAtom*> name(&rootAtom0, script->getAtom(REGS.pc));
2358
2359 auto* symbol = NewPrivateName(cx, name);
2360 if (!symbol) {
2361 goto error;
2362 }
2363
2364 PUSH_SYMBOL(symbol);
2365 }
2366 END_CASE(NewPrivateName)
2367
2368 CASE(IsNullOrUndefined) {
2369 bool b = REGS.sp[-1].isNullOrUndefined();
2370 PUSH_BOOLEAN(b);
2371 }
2372 END_CASE(IsNullOrUndefined)
2373
2374 CASE(Iter) {
2375 MOZ_ASSERT(REGS.stackDepth() >= 1);
2376 HandleValue val = REGS.stackHandleAt(-1);
2377 JSObject* iter = ValueToIterator(cx, val);
2378 if (!iter) {
2379 goto error;
2380 }
2381 REGS.sp[-1].setObject(*iter);
2382 }
2383 END_CASE(Iter)
2384
2385 CASE(MoreIter) {
2386 MOZ_ASSERT(REGS.stackDepth() >= 1);
2387 MOZ_ASSERT(REGS.sp[-1].isObject());
2388 Value v = IteratorMore(&REGS.sp[-1].toObject());
2389 PUSH_COPY(v);
2390 }
2391 END_CASE(MoreIter)
2392
2393 CASE(IsNoIter) {
2394 bool b = REGS.sp[-1].isMagic(JS_NO_ITER_VALUE);
2395 PUSH_BOOLEAN(b);
2396 }
2397 END_CASE(IsNoIter)
2398
2399 CASE(EndIter) {
2400 MOZ_ASSERT(REGS.stackDepth() >= 2);
2401 CloseIterator(&REGS.sp[-2].toObject());
2402 REGS.sp -= 2;
2403 }
2404 END_CASE(EndIter)
2405
2406 CASE(CloseIter) {
2407 ReservedRooted<JSObject*> iter(&rootObject0, &REGS.sp[-1].toObject());
2408 CompletionKind kind = CompletionKind(GET_UINT8(REGS.pc));
2409 if (!CloseIterOperation(cx, iter, kind)) {
2410 goto error;
2411 }
2412 REGS.sp--;
2413 }
2414 END_CASE(CloseIter)
2415
2416 CASE(OptimizeGetIterator) {
2417 bool result = OptimizeGetIterator(REGS.sp[-1], cx);
2418 REGS.sp[-1].setBoolean(result);
2419 }
2420 END_CASE(OptimizeGetIterator)
2421
2422 CASE(IsGenClosing) {
2423 bool b = REGS.sp[-1].isMagic(JS_GENERATOR_CLOSING);
2424 PUSH_BOOLEAN(b);
2425 }
2426 END_CASE(IsGenClosing)
2427
2428 CASE(Dup) {
2429 MOZ_ASSERT(REGS.stackDepth() >= 1);
2430 const Value& rref = REGS.sp[-1];
2431 PUSH_COPY(rref);
2432 }
2433 END_CASE(Dup)
2434
2435 CASE(Dup2) {
2436 MOZ_ASSERT(REGS.stackDepth() >= 2);
2437 const Value& lref = REGS.sp[-2];
2438 const Value& rref = REGS.sp[-1];
2439 PUSH_COPY(lref);
2440 PUSH_COPY(rref);
2441 }
2442 END_CASE(Dup2)
2443
2444 CASE(Swap) {
2445 MOZ_ASSERT(REGS.stackDepth() >= 2);
2446 Value& lref = REGS.sp[-2];
2447 Value& rref = REGS.sp[-1];
2448 lref.swap(rref);
2449 }
2450 END_CASE(Swap)
2451
2452 CASE(Pick) {
2453 unsigned i = GET_UINT8(REGS.pc);
2454 MOZ_ASSERT(REGS.stackDepth() >= i + 1);
2455 Value lval = REGS.sp[-int(i + 1)];
2456 memmove(REGS.sp - (i + 1), REGS.sp - i, sizeof(Value) * i);
2457 REGS.sp[-1] = lval;
2458 }
2459 END_CASE(Pick)
2460
2461 CASE(Unpick) {
2462 int i = GET_UINT8(REGS.pc);
2463 MOZ_ASSERT(REGS.stackDepth() >= unsigned(i) + 1);
2464 Value lval = REGS.sp[-1];
2465 memmove(REGS.sp - i, REGS.sp - (i + 1), sizeof(Value) * i);
2466 REGS.sp[-(i + 1)] = lval;
2467 }
2468 END_CASE(Unpick)
2469
2470 CASE(BindUnqualifiedGName)
2471 CASE(BindUnqualifiedName) {
2472 JSOp op = JSOp(*REGS.pc);
2473 ReservedRooted<JSObject*> envChain(&rootObject0);
2474 if (op == JSOp::BindUnqualifiedName) {
2475 envChain.set(REGS.fp()->environmentChain());
2476 } else {
2477 MOZ_ASSERT(!script->hasNonSyntacticScope());
2478 envChain.set(&REGS.fp()->global().lexicalEnvironment());
2479 }
2480 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2481
2482 // Assigning to an undeclared name adds a property to the global object.
2483 JSObject* env = LookupNameUnqualified(cx, name, envChain);
2484 if (!env) {
2485 goto error;
2486 }
2487
2488 PUSH_OBJECT(*env);
2489
2490 static_assert(
2491 JSOpLength_BindUnqualifiedName == JSOpLength_BindUnqualifiedGName,
2492 "We're sharing the END_CASE so the lengths better match");
2493 }
2494 END_CASE(BindUnqualifiedName)
2495
2496 CASE(BindName) {
2497 auto envChain = REGS.fp()->environmentChain();
2498 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2499
2500 JSObject* env = LookupNameWithGlobalDefault(cx, name, envChain);
2501 if (!env) {
2502 goto error;
2503 }
2504
2505 PUSH_OBJECT(*env);
2506 }
2507 END_CASE(BindName)
2508
2509 CASE(BindVar) {
2510 JSObject* varObj = BindVarOperation(cx, REGS.fp()->environmentChain());
2511 PUSH_OBJECT(*varObj);
2512 }
2513 END_CASE(BindVar)
2514
2515 CASE(BitOr) {
2516 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2517 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2518 MutableHandleValue res = REGS.stackHandleAt(-2);
2519 if (!BitOrOperation(cx, lhs, rhs, res)) {
2520 goto error;
2521 }
2522 REGS.sp--;
2523 }
2524 END_CASE(BitOr)
2525
2526 CASE(BitXor) {
2527 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2528 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2529 MutableHandleValue res = REGS.stackHandleAt(-2);
2530 if (!BitXorOperation(cx, lhs, rhs, res)) {
2531 goto error;
2532 }
2533 REGS.sp--;
2534 }
2535 END_CASE(BitXor)
2536
2537 CASE(BitAnd) {
2538 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2539 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2540 MutableHandleValue res = REGS.stackHandleAt(-2);
2541 if (!BitAndOperation(cx, lhs, rhs, res)) {
2542 goto error;
2543 }
2544 REGS.sp--;
2545 }
2546 END_CASE(BitAnd)
2547
2548 CASE(Eq) {
2549 if (!LooseEqualityOp<true>(cx, REGS)) {
2550 goto error;
2551 }
2552 }
2553 END_CASE(Eq)
2554
2555 CASE(Ne) {
2556 if (!LooseEqualityOp<false>(cx, REGS)) {
2557 goto error;
2558 }
2559 }
2560 END_CASE(Ne)
2561
2562 #define STRICT_EQUALITY_OP(OP, COND) \
2563 JS_BEGIN_MACRO \
2564 HandleValue lval = REGS.stackHandleAt(-2); \
2565 HandleValue rval = REGS.stackHandleAt(-1); \
2566 bool equal; \
2567 if (!js::StrictlyEqual(cx, lval, rval, &equal)) { \
2568 goto error; \
2569 } \
2570 (COND) = equal OP true; \
2571 REGS.sp--; \
2572 JS_END_MACRO
2573
2574 CASE(StrictEq) {
2575 bool cond;
2576 STRICT_EQUALITY_OP(==, cond);
2577 REGS.sp[-1].setBoolean(cond);
2578 }
2579 END_CASE(StrictEq)
2580
2581 CASE(StrictNe) {
2582 bool cond;
2583 STRICT_EQUALITY_OP(!=, cond);
2584 REGS.sp[-1].setBoolean(cond);
2585 }
2586 END_CASE(StrictNe)
2587
2588 #undef STRICT_EQUALITY_OP
2589
2590 CASE(StrictConstantEq) {
2591 JS::Handle<JS::Value> value = REGS.stackHandleAt(-1);
2592 bool equal;
2593 if (!js::ConstantStrictEqual(cx, value, GET_UINT16(REGS.pc), &equal)) {
2594 goto error;
2595 }
2596 REGS.sp[-1].setBoolean(equal);
2597 }
2598 END_CASE(StrictConstantEq)
2599
2600 CASE(StrictConstantNe) {
2601 JS::Handle<JS::Value> value = REGS.stackHandleAt(-1);
2602 bool equal;
2603 if (!js::ConstantStrictEqual(cx, value, GET_UINT16(REGS.pc), &equal)) {
2604 goto error;
2605 }
2606 REGS.sp[-1].setBoolean(!equal);
2607 }
2608 END_CASE(StrictConstantNe)
2609
2610 CASE(Case) {
2611 bool cond = REGS.sp[-1].toBoolean();
2612 REGS.sp--;
2613 if (cond) {
2614 REGS.sp--;
2615 BRANCH(GET_JUMP_OFFSET(REGS.pc));
2616 }
2617 }
2618 END_CASE(Case)
2619
2620 CASE(Lt) {
2621 bool cond;
2622 MutableHandleValue lval = REGS.stackHandleAt(-2);
2623 MutableHandleValue rval = REGS.stackHandleAt(-1);
2624 if (!LessThanOperation(cx, lval, rval, &cond)) {
2625 goto error;
2626 }
2627 TRY_BRANCH_AFTER_COND(cond, 2);
2628 REGS.sp[-2].setBoolean(cond);
2629 REGS.sp--;
2630 }
2631 END_CASE(Lt)
2632
2633 CASE(Le) {
2634 bool cond;
2635 MutableHandleValue lval = REGS.stackHandleAt(-2);
2636 MutableHandleValue rval = REGS.stackHandleAt(-1);
2637 if (!LessThanOrEqualOperation(cx, lval, rval, &cond)) {
2638 goto error;
2639 }
2640 TRY_BRANCH_AFTER_COND(cond, 2);
2641 REGS.sp[-2].setBoolean(cond);
2642 REGS.sp--;
2643 }
2644 END_CASE(Le)
2645
2646 CASE(Gt) {
2647 bool cond;
2648 MutableHandleValue lval = REGS.stackHandleAt(-2);
2649 MutableHandleValue rval = REGS.stackHandleAt(-1);
2650 if (!GreaterThanOperation(cx, lval, rval, &cond)) {
2651 goto error;
2652 }
2653 TRY_BRANCH_AFTER_COND(cond, 2);
2654 REGS.sp[-2].setBoolean(cond);
2655 REGS.sp--;
2656 }
2657 END_CASE(Gt)
2658
2659 CASE(Ge) {
2660 bool cond;
2661 MutableHandleValue lval = REGS.stackHandleAt(-2);
2662 MutableHandleValue rval = REGS.stackHandleAt(-1);
2663 if (!GreaterThanOrEqualOperation(cx, lval, rval, &cond)) {
2664 goto error;
2665 }
2666 TRY_BRANCH_AFTER_COND(cond, 2);
2667 REGS.sp[-2].setBoolean(cond);
2668 REGS.sp--;
2669 }
2670 END_CASE(Ge)
2671
2672 CASE(Lsh) {
2673 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2674 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2675 MutableHandleValue res = REGS.stackHandleAt(-2);
2676 if (!BitLshOperation(cx, lhs, rhs, res)) {
2677 goto error;
2678 }
2679 REGS.sp--;
2680 }
2681 END_CASE(Lsh)
2682
2683 CASE(Rsh) {
2684 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2685 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2686 MutableHandleValue res = REGS.stackHandleAt(-2);
2687 if (!BitRshOperation(cx, lhs, rhs, res)) {
2688 goto error;
2689 }
2690 REGS.sp--;
2691 }
2692 END_CASE(Rsh)
2693
2694 CASE(Ursh) {
2695 MutableHandleValue lhs = REGS.stackHandleAt(-2);
2696 MutableHandleValue rhs = REGS.stackHandleAt(-1);
2697 MutableHandleValue res = REGS.stackHandleAt(-2);
2698 if (!UrshOperation(cx, lhs, rhs, res)) {
2699 goto error;
2700 }
2701 REGS.sp--;
2702 }
2703 END_CASE(Ursh)
2704
2705 CASE(Add) {
2706 MutableHandleValue lval = REGS.stackHandleAt(-2);
2707 MutableHandleValue rval = REGS.stackHandleAt(-1);
2708 MutableHandleValue res = REGS.stackHandleAt(-2);
2709 if (!AddOperation(cx, lval, rval, res)) {
2710 goto error;
2711 }
2712 REGS.sp--;
2713 }
2714 END_CASE(Add)
2715
2716 CASE(Sub) {
2717 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-2]);
2718 ReservedRooted<Value> rval(&rootValue1, REGS.sp[-1]);
2719 MutableHandleValue res = REGS.stackHandleAt(-2);
2720 if (!SubOperation(cx, &lval, &rval, res)) {
2721 goto error;
2722 }
2723 REGS.sp--;
2724 }
2725 END_CASE(Sub)
2726
2727 CASE(Mul) {
2728 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-2]);
2729 ReservedRooted<Value> rval(&rootValue1, REGS.sp[-1]);
2730 MutableHandleValue res = REGS.stackHandleAt(-2);
2731 if (!MulOperation(cx, &lval, &rval, res)) {
2732 goto error;
2733 }
2734 REGS.sp--;
2735 }
2736 END_CASE(Mul)
2737
2738 CASE(Div) {
2739 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-2]);
2740 ReservedRooted<Value> rval(&rootValue1, REGS.sp[-1]);
2741 MutableHandleValue res = REGS.stackHandleAt(-2);
2742 if (!DivOperation(cx, &lval, &rval, res)) {
2743 goto error;
2744 }
2745 REGS.sp--;
2746 }
2747 END_CASE(Div)
2748
2749 CASE(Mod) {
2750 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-2]);
2751 ReservedRooted<Value> rval(&rootValue1, REGS.sp[-1]);
2752 MutableHandleValue res = REGS.stackHandleAt(-2);
2753 if (!ModOperation(cx, &lval, &rval, res)) {
2754 goto error;
2755 }
2756 REGS.sp--;
2757 }
2758 END_CASE(Mod)
2759
2760 CASE(Pow) {
2761 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-2]);
2762 ReservedRooted<Value> rval(&rootValue1, REGS.sp[-1]);
2763 MutableHandleValue res = REGS.stackHandleAt(-2);
2764 if (!PowOperation(cx, &lval, &rval, res)) {
2765 goto error;
2766 }
2767 REGS.sp--;
2768 }
2769 END_CASE(Pow)
2770
2771 CASE(Not) {
2772 bool cond = ToBoolean(REGS.stackHandleAt(-1));
2773 REGS.sp--;
2774 PUSH_BOOLEAN(!cond);
2775 }
2776 END_CASE(Not)
2777
2778 CASE(BitNot) {
2779 MutableHandleValue val = REGS.stackHandleAt(-1);
2780 if (!BitNotOperation(cx, val, val)) {
2781 goto error;
2782 }
2783 }
2784 END_CASE(BitNot)
2785
2786 CASE(Neg) {
2787 MutableHandleValue val = REGS.stackHandleAt(-1);
2788 if (!NegOperation(cx, val, val)) {
2789 goto error;
2790 }
2791 }
2792 END_CASE(Neg)
2793
2794 CASE(Pos) {
2795 if (!ToNumber(cx, REGS.stackHandleAt(-1))) {
2796 goto error;
2797 }
2798 }
2799 END_CASE(Pos)
2800
2801 CASE(DelName) {
2802 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2803 HandleObject envChain = REGS.fp()->environmentChain();
2804
2805 PUSH_BOOLEAN(true);
2806 MutableHandleValue res = REGS.stackHandleAt(-1);
2807 if (!DeleteNameOperation(cx, name, envChain, res)) {
2808 goto error;
2809 }
2810 }
2811 END_CASE(DelName)
2812
2813 CASE(DelProp)
2814 CASE(StrictDelProp) {
2815 static_assert(JSOpLength_DelProp == JSOpLength_StrictDelProp,
2816 "delprop and strictdelprop must be the same size");
2817 HandleValue val = REGS.stackHandleAt(-1);
2818 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2819 bool res = false;
2820 if (JSOp(*REGS.pc) == JSOp::StrictDelProp) {
2821 if (!DelPropOperation<true>(cx, val, name, &res)) {
2822 goto error;
2823 }
2824 } else {
2825 if (!DelPropOperation<false>(cx, val, name, &res)) {
2826 goto error;
2827 }
2828 }
2829 REGS.sp[-1].setBoolean(res);
2830 }
2831 END_CASE(DelProp)
2832
2833 CASE(DelElem)
2834 CASE(StrictDelElem) {
2835 static_assert(JSOpLength_DelElem == JSOpLength_StrictDelElem,
2836 "delelem and strictdelelem must be the same size");
2837 HandleValue val = REGS.stackHandleAt(-2);
2838 HandleValue propval = REGS.stackHandleAt(-1);
2839 bool res = false;
2840 if (JSOp(*REGS.pc) == JSOp::StrictDelElem) {
2841 if (!DelElemOperation<true>(cx, val, propval, &res)) {
2842 goto error;
2843 }
2844 } else {
2845 if (!DelElemOperation<false>(cx, val, propval, &res)) {
2846 goto error;
2847 }
2848 }
2849 REGS.sp[-2].setBoolean(res);
2850 REGS.sp--;
2851 }
2852 END_CASE(DelElem)
2853
2854 CASE(ToPropertyKey) {
2855 ReservedRooted<Value> idval(&rootValue1, REGS.sp[-1]);
2856 MutableHandleValue res = REGS.stackHandleAt(-1);
2857 if (!ToPropertyKeyOperation(cx, idval, res)) {
2858 goto error;
2859 }
2860 }
2861 END_CASE(ToPropertyKey)
2862
2863 CASE(TypeofExpr)
2864 CASE(Typeof) {
2865 REGS.sp[-1].setString(TypeOfOperation(REGS.sp[-1], cx->runtime()));
2866 }
2867 END_CASE(Typeof)
2868
2869 CASE(TypeofEq) {
2870 auto operand = TypeofEqOperand::fromRawValue(GET_UINT8(REGS.pc));
2871 bool result = js::TypeOfValue(REGS.sp[-1]) == operand.type();
2872 if (operand.compareOp() == JSOp::Ne) {
2873 result = !result;
2874 }
2875 REGS.sp[-1].setBoolean(result);
2876 }
2877 END_CASE(TypeofEq)
2878
2879 CASE(Void) { REGS.sp[-1].setUndefined(); }
2880 END_CASE(Void)
2881
2882 CASE(FunctionThis) {
2883 PUSH_NULL();
2884 if (!GetFunctionThis(cx, REGS.fp(), REGS.stackHandleAt(-1))) {
2885 goto error;
2886 }
2887 }
2888 END_CASE(FunctionThis)
2889
2890 CASE(GlobalThis) {
2891 MOZ_ASSERT(!script->hasNonSyntacticScope());
2892 PUSH_OBJECT(*cx->global()->lexicalEnvironment().thisObject());
2893 }
2894 END_CASE(GlobalThis)
2895
2896 CASE(NonSyntacticGlobalThis) {
2897 PUSH_NULL();
2898 GetNonSyntacticGlobalThis(cx, REGS.fp()->environmentChain(),
2899 REGS.stackHandleAt(-1));
2900 }
2901 END_CASE(NonSyntacticGlobalThis)
2902
2903 CASE(CheckIsObj) {
2904 if (!REGS.sp[-1].isObject()) {
2905 MOZ_ALWAYS_FALSE(
2906 ThrowCheckIsObject(cx, CheckIsObjectKind(GET_UINT8(REGS.pc))));
2907 goto error;
2908 }
2909 }
2910 END_CASE(CheckIsObj)
2911
2912 CASE(CheckThis) {
2913 if (REGS.sp[-1].isMagic(JS_UNINITIALIZED_LEXICAL)) {
2914 MOZ_ALWAYS_FALSE(ThrowUninitializedThis(cx));
2915 goto error;
2916 }
2917 }
2918 END_CASE(CheckThis)
2919
2920 CASE(CheckThisReinit) {
2921 if (!REGS.sp[-1].isMagic(JS_UNINITIALIZED_LEXICAL)) {
2922 MOZ_ALWAYS_FALSE(ThrowInitializedThis(cx));
2923 goto error;
2924 }
2925 }
2926 END_CASE(CheckThisReinit)
2927
2928 CASE(CheckReturn) {
2929 ReservedRooted<Value> thisv(&rootValue0, REGS.sp[-1]);
2930 MutableHandleValue rval = REGS.stackHandleAt(-1);
2931 if (!REGS.fp()->checkReturn(cx, thisv, rval)) {
2932 goto error;
2933 }
2934 }
2935 END_CASE(CheckReturn)
2936
2937 CASE(GetProp) {
2938 ReservedRooted<Value> lval(&rootValue0, REGS.sp[-1]);
2939 MutableHandleValue res = REGS.stackHandleAt(-1);
2940 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2941 if (!GetPropertyOperation(cx, name, lval, res)) {
2942 goto error;
2943 }
2944 cx->debugOnlyCheck(res);
2945 }
2946 END_CASE(GetProp)
2947
2948 CASE(GetPropSuper) {
2949 ReservedRooted<Value> receiver(&rootValue0, REGS.sp[-2]);
2950 HandleValue lval = REGS.stackHandleAt(-1);
2951 MOZ_ASSERT(lval.isObjectOrNull());
2952 MutableHandleValue rref = REGS.stackHandleAt(-2);
2953 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
2954
2955 ReservedRooted<JSObject*> obj(&rootObject0);
2956 obj = ToObjectFromStackForPropertyAccess(cx, lval, -1, name);
2957 if (!obj) {
2958 goto error;
2959 }
2960
2961 if (!GetProperty(cx, obj, receiver, name, rref)) {
2962 goto error;
2963 }
2964
2965 cx->debugOnlyCheck(rref);
2966
2967 REGS.sp--;
2968 }
2969 END_CASE(GetPropSuper)
2970
2971 CASE(GetBoundName) {
2972 ReservedRooted<JSObject*> env(&rootObject0, &REGS.sp[-1].toObject());
2973 ReservedRooted<jsid> id(&rootId0, NameToId(script->getName(REGS.pc)));
2974 MutableHandleValue rval = REGS.stackHandleAt(-1);
2975 if (!GetNameBoundInEnvironment(cx, env, id, rval)) {
2976 goto error;
2977 }
2978 cx->debugOnlyCheck(rval);
2979 }
2980 END_CASE(GetBoundName)
2981
2982 CASE(SetIntrinsic) {
2983 HandleValue value = REGS.stackHandleAt(-1);
2984
2985 if (!SetIntrinsicOperation(cx, script, REGS.pc, value)) {
2986 goto error;
2987 }
2988 }
2989 END_CASE(SetIntrinsic)
2990
2991 CASE(SetGName)
2992 CASE(StrictSetGName)
2993 CASE(SetName)
2994 CASE(StrictSetName) {
2995 static_assert(JSOpLength_SetName == JSOpLength_StrictSetName,
2996 "setname and strictsetname must be the same size");
2997 static_assert(JSOpLength_SetGName == JSOpLength_StrictSetGName,
2998 "setgname and strictsetgname must be the same size");
2999 static_assert(JSOpLength_SetName == JSOpLength_SetGName,
3000 "We're sharing the END_CASE so the lengths better match");
3001
3002 ReservedRooted<JSObject*> env(&rootObject0, &REGS.sp[-2].toObject());
3003 HandleValue value = REGS.stackHandleAt(-1);
3004
3005 if (!SetNameOperation(cx, script, REGS.pc, env, value)) {
3006 goto error;
3007 }
3008
3009 REGS.sp[-2] = REGS.sp[-1];
3010 REGS.sp--;
3011 }
3012 END_CASE(SetName)
3013
3014 CASE(SetProp)
3015 CASE(StrictSetProp) {
3016 static_assert(JSOpLength_SetProp == JSOpLength_StrictSetProp,
3017 "setprop and strictsetprop must be the same size");
3018 int lvalIndex = -2;
3019 HandleValue lval = REGS.stackHandleAt(lvalIndex);
3020 HandleValue rval = REGS.stackHandleAt(-1);
3021
3022 ReservedRooted<jsid> id(&rootId0, NameToId(script->getName(REGS.pc)));
3023
3024 bool strict = JSOp(*REGS.pc) == JSOp::StrictSetProp;
3025
3026 ReservedRooted<JSObject*> obj(&rootObject0);
3027 obj = ToObjectFromStackForPropertyAccess(cx, lval, lvalIndex, id);
3028 if (!obj) {
3029 goto error;
3030 }
3031
3032 if (!SetObjectElementOperation(cx, obj, id, rval, lval, strict)) {
3033 goto error;
3034 }
3035
3036 REGS.sp[-2] = REGS.sp[-1];
3037 REGS.sp--;
3038 }
3039 END_CASE(SetProp)
3040
3041 CASE(SetPropSuper)
3042 CASE(StrictSetPropSuper) {
3043 static_assert(
3044 JSOpLength_SetPropSuper == JSOpLength_StrictSetPropSuper,
3045 "setprop-super and strictsetprop-super must be the same size");
3046
3047 HandleValue receiver = REGS.stackHandleAt(-3);
3048 HandleValue lval = REGS.stackHandleAt(-2);
3049 MOZ_ASSERT(lval.isObjectOrNull());
3050 HandleValue rval = REGS.stackHandleAt(-1);
3051 ReservedRooted<jsid> id(&rootId0, NameToId(script->getName(REGS.pc)));
3052
3053 bool strict = JSOp(*REGS.pc) == JSOp::StrictSetPropSuper;
3054
3055 ReservedRooted<JSObject*> obj(&rootObject0);
3056 obj = ToObjectFromStackForPropertyAccess(cx, lval, -2, id);
3057 if (!obj) {
3058 goto error;
3059 }
3060
3061 if (!SetObjectElementOperation(cx, obj, id, rval, receiver, strict)) {
3062 goto error;
3063 }
3064
3065 REGS.sp[-3] = REGS.sp[-1];
3066 REGS.sp -= 2;
3067 }
3068 END_CASE(SetPropSuper)
3069
3070 CASE(GetElem) {
3071 int lvalIndex = -2;
3072 ReservedRooted<Value> lval(&rootValue0, REGS.sp[lvalIndex]);
3073 HandleValue rval = REGS.stackHandleAt(-1);
3074 MutableHandleValue res = REGS.stackHandleAt(-2);
3075
3076 if (!GetElementOperationWithStackIndex(cx, lval, lvalIndex, rval, res)) {
3077 goto error;
3078 }
3079
3080 REGS.sp--;
3081 }
3082 END_CASE(GetElem)
3083
3084 CASE(GetElemSuper) {
3085 ReservedRooted<Value> receiver(&rootValue0, REGS.sp[-3]);
3086 HandleValue index = REGS.stackHandleAt(-2);
3087 HandleValue lval = REGS.stackHandleAt(-1);
3088 MOZ_ASSERT(lval.isObjectOrNull());
3089
3090 MutableHandleValue res = REGS.stackHandleAt(-3);
3091
3092 ReservedRooted<JSObject*> obj(&rootObject0);
3093 obj = ToObjectFromStackForPropertyAccess(cx, lval, -1, index);
3094 if (!obj) {
3095 goto error;
3096 }
3097
3098 if (!GetObjectElementOperation(cx, JSOp(*REGS.pc), obj, receiver, index,
3099 res)) {
3100 goto error;
3101 }
3102
3103 REGS.sp -= 2;
3104 }
3105 END_CASE(GetElemSuper)
3106
3107 CASE(SetElem)
3108 CASE(StrictSetElem) {
3109 static_assert(JSOpLength_SetElem == JSOpLength_StrictSetElem,
3110 "setelem and strictsetelem must be the same size");
3111 int receiverIndex = -3;
3112 HandleValue receiver = REGS.stackHandleAt(receiverIndex);
3113 HandleValue value = REGS.stackHandleAt(-1);
3114
3115 ReservedRooted<JSObject*> obj(&rootObject0);
3116 obj = ToObjectFromStackForPropertyAccess(cx, receiver, receiverIndex,
3117 REGS.stackHandleAt(-2));
3118 if (!obj) {
3119 goto error;
3120 }
3121
3122 ReservedRooted<jsid> id(&rootId0);
3123 FETCH_ELEMENT_ID(-2, id);
3124
3125 if (!SetObjectElementOperation(cx, obj, id, value, receiver,
3126 JSOp(*REGS.pc) == JSOp::StrictSetElem)) {
3127 goto error;
3128 }
3129 REGS.sp[-3] = value;
3130 REGS.sp -= 2;
3131 }
3132 END_CASE(SetElem)
3133
3134 CASE(SetElemSuper)
3135 CASE(StrictSetElemSuper) {
3136 static_assert(
3137 JSOpLength_SetElemSuper == JSOpLength_StrictSetElemSuper,
3138 "setelem-super and strictsetelem-super must be the same size");
3139
3140 HandleValue receiver = REGS.stackHandleAt(-4);
3141 HandleValue lval = REGS.stackHandleAt(-2);
3142 MOZ_ASSERT(lval.isObjectOrNull());
3143 HandleValue value = REGS.stackHandleAt(-1);
3144
3145 ReservedRooted<JSObject*> obj(&rootObject0);
3146 obj = ToObjectFromStackForPropertyAccess(cx, lval, -2,
3147 REGS.stackHandleAt(-3));
3148 if (!obj) {
3149 goto error;
3150 }
3151
3152 ReservedRooted<jsid> id(&rootId0);
3153 FETCH_ELEMENT_ID(-3, id);
3154
3155 bool strict = JSOp(*REGS.pc) == JSOp::StrictSetElemSuper;
3156 if (!SetObjectElementOperation(cx, obj, id, value, receiver, strict)) {
3157 goto error;
3158 }
3159 REGS.sp[-4] = value;
3160 REGS.sp -= 3;
3161 }
3162 END_CASE(SetElemSuper)
3163
3164 CASE(Eval)
3165 CASE(StrictEval) {
3166 static_assert(JSOpLength_Eval == JSOpLength_StrictEval,
3167 "eval and stricteval must be the same size");
3168
3169 CallArgs args = CallArgsFromSp(GET_ARGC(REGS.pc), REGS.sp);
3170 if (cx->global()->valueIsEval(args.calleev())) {
3171 if (!DirectEval(cx, args.get(0), args.rval())) {
3172 goto error;
3173 }
3174 } else {
3175 if (!CallFromStack(cx, args, CallReason::Call)) {
3176 goto error;
3177 }
3178 }
3179
3180 REGS.sp = args.spAfterCall();
3181 }
3182 END_CASE(Eval)
3183
3184 CASE(SpreadNew)
3185 CASE(SpreadCall)
3186 CASE(SpreadSuperCall) {
3187 if (REGS.fp()->hasPushedGeckoProfilerFrame()) {
3188 cx->geckoProfiler().updatePC(cx, script, REGS.pc);
3189 }
3190 /* FALL THROUGH */
3191 }
3192
3193 CASE(SpreadEval)
3194 CASE(StrictSpreadEval) {
3195 static_assert(JSOpLength_SpreadEval == JSOpLength_StrictSpreadEval,
3196 "spreadeval and strictspreadeval must be the same size");
3197 bool construct = JSOp(*REGS.pc) == JSOp::SpreadNew ||
3198 JSOp(*REGS.pc) == JSOp::SpreadSuperCall;
3199
3200 MOZ_ASSERT(REGS.stackDepth() >= 3u + construct);
3201
3202 HandleValue callee = REGS.stackHandleAt(-3 - construct);
3203 HandleValue thisv = REGS.stackHandleAt(-2 - construct);
3204 HandleValue arr = REGS.stackHandleAt(-1 - construct);
3205 MutableHandleValue ret = REGS.stackHandleAt(-3 - construct);
3206
3207 ReservedRooted<Value> newTarget(&rootValue0);
3208 if (construct) {
3209 newTarget = REGS.sp[-1];
3210 } else {
3211 newTarget = NullValue();
3212 }
3213
3214 if (!SpreadCallOperation(cx, script, REGS.pc, thisv, callee, arr,
3215 newTarget, ret)) {
3216 goto error;
3217 }
3218
3219 REGS.sp -= 2 + construct;
3220 }
3221 END_CASE(SpreadCall)
3222
3223 CASE(New)
3224 CASE(NewContent)
3225 CASE(Call)
3226 CASE(CallContent)
3227 CASE(CallIgnoresRv)
3228 CASE(CallIter)
3229 CASE(CallContentIter)
3230 CASE(SuperCall) {
3231 static_assert(JSOpLength_Call == JSOpLength_New,
3232 "call and new must be the same size");
3233 static_assert(JSOpLength_Call == JSOpLength_CallContent,
3234 "call and call-content must be the same size");
3235 static_assert(JSOpLength_Call == JSOpLength_CallIgnoresRv,
3236 "call and call-ignores-rv must be the same size");
3237 static_assert(JSOpLength_Call == JSOpLength_CallIter,
3238 "call and calliter must be the same size");
3239 static_assert(JSOpLength_Call == JSOpLength_CallContentIter,
3240 "call and call-content-iter must be the same size");
3241 static_assert(JSOpLength_Call == JSOpLength_SuperCall,
3242 "call and supercall must be the same size");
3243
3244 if (REGS.fp()->hasPushedGeckoProfilerFrame()) {
3245 cx->geckoProfiler().updatePC(cx, script, REGS.pc);
3246 }
3247
3248 JSOp op = JSOp(*REGS.pc);
3249 MaybeConstruct construct = MaybeConstruct(
3250 op == JSOp::New || op == JSOp::NewContent || op == JSOp::SuperCall);
3251 bool ignoresReturnValue = op == JSOp::CallIgnoresRv;
3252 unsigned argStackSlots = GET_ARGC(REGS.pc) + construct;
3253
3254 MOZ_ASSERT(REGS.stackDepth() >= 2u + GET_ARGC(REGS.pc));
3255 CallArgs args =
3256 CallArgsFromSp(argStackSlots, REGS.sp, construct, ignoresReturnValue);
3257
3258 JSFunction* maybeFun;
3259 bool isFunction = IsFunctionObject(args.calleev(), &maybeFun);
3260
3261 // Use the slow path if the callee is not an interpreted function, if we
3262 // have to throw an exception, or if we might have to invoke the
3263 // OnNativeCall hook for a self-hosted builtin.
3264 if (!isFunction || !maybeFun->isInterpreted() ||
3265 (construct && !maybeFun->isConstructor()) ||
3266 (!construct && maybeFun->isClassConstructor()) ||
3267 cx->realm()->debuggerObservesNativeCall()) {
3268 if (construct) {
3269 CallReason reason = op == JSOp::NewContent ? CallReason::CallContent
3270 : CallReason::Call;
3271 if (!ConstructFromStack(cx, args, reason)) {
3272 goto error;
3273 }
3274 } else {
3275 if ((op == JSOp::CallIter || op == JSOp::CallContentIter) &&
3276 args.calleev().isPrimitive()) {
3277 MOZ_ASSERT(args.length() == 0, "thisv must be on top of the stack");
3278 ReportValueError(cx, JSMSG_NOT_ITERABLE, -1, args.thisv(), nullptr);
3279 goto error;
3280 }
3281
3282 CallReason reason =
3283 (op == JSOp::CallContent || op == JSOp::CallContentIter)
3284 ? CallReason::CallContent
3285 : CallReason::Call;
3286 if (!CallFromStack(cx, args, reason)) {
3287 goto error;
3288 }
3289 }
3290 Value* newsp = args.spAfterCall();
3291 REGS.sp = newsp;
3292 ADVANCE_AND_DISPATCH(JSOpLength_Call);
3293 }
3294
3295 {
3296 MOZ_ASSERT(maybeFun);
3297 ReservedRooted<JSFunction*> fun(&rootFunction0, maybeFun);
3298 ReservedRooted<JSScript*> funScript(
3299 &rootScript0, JSFunction::getOrCreateScript(cx, fun));
3300 if (!funScript) {
3301 goto error;
3302 }
3303
3304 // Enter the callee's realm if this is a cross-realm call. Use
3305 // MakeScopeExit to leave this realm on all error/JIT-return paths
3306 // below.
3307 const bool isCrossRealm = cx->realm() != funScript->realm();
3308 if (isCrossRealm) {
3309 cx->enterRealmOf(funScript);
3310 }
3311 auto leaveRealmGuard =
3312 mozilla::MakeScopeExit([isCrossRealm, cx, &script] {
3313 if (isCrossRealm) {
3314 cx->leaveRealm(script->realm());
3315 }
3316 });
3317
3318 if (construct && !MaybeCreateThisForConstructor(cx, args)) {
3319 goto error;
3320 }
3321
3322 {
3323 InvokeState state(cx, args, construct);
3324
3325 jit::EnterJitStatus status = jit::MaybeEnterJit(cx, state);
3326 switch (status) {
3327 case jit::EnterJitStatus::Error:
3328 goto error;
3329 case jit::EnterJitStatus::Ok:
3330 interpReturnOK = true;
3331 CHECK_BRANCH();
3332 REGS.sp = args.spAfterCall();
3333 goto jit_return;
3334 case jit::EnterJitStatus::NotEntered:
3335 break;
3336 }
3337
3338 #ifdef NIGHTLY_BUILD
3339 // If entry trampolines are enabled, call back into
3340 // MaybeEnterInterpreterTrampoline so we can generate an
3341 // entry trampoline for the new frame.
3342 if (jit::JitOptions.emitInterpreterEntryTrampoline) {
3343 if (MaybeEnterInterpreterTrampoline(cx, state)) {
3344 interpReturnOK = true;
3345 CHECK_BRANCH();
3346 REGS.sp = args.spAfterCall();
3347 goto jit_return;
3348 }
3349 goto error;
3350 }
3351 #endif
3352 }
3353
3354 funScript = fun->nonLazyScript();
3355
3356 if (!activation.pushInlineFrame(args, funScript, construct)) {
3357 goto error;
3358 }
3359 leaveRealmGuard.release(); // We leave the callee's realm when we
3360 // call popInlineFrame.
3361 }
3362
3363 SET_SCRIPT(REGS.fp()->script());
3364
3365 if (!REGS.fp()->prologue(cx)) {
3366 goto prologue_error;
3367 }
3368
3369 if (!DebugAPI::onEnterFrame(cx, REGS.fp())) {
3370 goto error;
3371 }
3372
3373 // Increment the coverage for the main entry point.
3374 INIT_COVERAGE();
3375 COUNT_COVERAGE_MAIN();
3376
3377 /* Load first op and dispatch it (safe since JSOp::RetRval). */
3378 ADVANCE_AND_DISPATCH(0);
3379 }
3380
3381 CASE(OptimizeSpreadCall) {
3382 ReservedRooted<Value> val(&rootValue0, REGS.sp[-1]);
3383 MutableHandleValue rval = REGS.stackHandleAt(-1);
3384
3385 if (!OptimizeSpreadCall(cx, val, rval)) {
3386 goto error;
3387 }
3388 }
3389 END_CASE(OptimizeSpreadCall)
3390
3391 CASE(ThrowMsg) {
3392 MOZ_ALWAYS_FALSE(ThrowMsgOperation(cx, GET_UINT8(REGS.pc)));
3393 goto error;
3394 }
3395 END_CASE(ThrowMsg)
3396
3397 CASE(ImplicitThis) {
3398 Value thisv = ComputeImplicitThis(&REGS.sp[-1].toObject());
3399 REGS.sp[-1] = thisv;
3400 }
3401 END_CASE(ImplicitThis)
3402
3403 CASE(GetGName) {
3404 ReservedRooted<Value> rval(&rootValue0);
3405 ReservedRooted<JSObject*> env(&rootObject0,
3406 &cx->global()->lexicalEnvironment());
3407 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
3408 MOZ_ASSERT(!script->hasNonSyntacticScope());
3409 if (!GetNameOperation(cx, env, name, JSOp(REGS.pc[JSOpLength_GetGName]),
3410 &rval)) {
3411 goto error;
3412 }
3413
3414 PUSH_COPY(rval);
3415 }
3416 END_CASE(GetGName)
3417
3418 CASE(GetName) {
3419 ReservedRooted<Value> rval(&rootValue0);
3420 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
3421 if (!GetNameOperation(cx, REGS.fp()->environmentChain(), name,
3422 JSOp(REGS.pc[JSOpLength_GetName]), &rval)) {
3423 goto error;
3424 }
3425
3426 PUSH_COPY(rval);
3427 }
3428 END_CASE(GetName)
3429
3430 CASE(GetImport) {
3431 PUSH_NULL();
3432 MutableHandleValue rval = REGS.stackHandleAt(-1);
3433 HandleObject envChain = REGS.fp()->environmentChain();
3434 if (!GetImportOperation(cx, envChain, script, REGS.pc, rval)) {
3435 goto error;
3436 }
3437 }
3438 END_CASE(GetImport)
3439
3440 CASE(GetIntrinsic) {
3441 ReservedRooted<Value> rval(&rootValue0);
3442 if (!GetIntrinsicOperation(cx, script, REGS.pc, &rval)) {
3443 goto error;
3444 }
3445
3446 PUSH_COPY(rval);
3447 }
3448 END_CASE(GetIntrinsic)
3449
3450 CASE(Uint16) { PUSH_INT32((int32_t)GET_UINT16(REGS.pc)); }
3451 END_CASE(Uint16)
3452
3453 CASE(Uint24) { PUSH_INT32((int32_t)GET_UINT24(REGS.pc)); }
3454 END_CASE(Uint24)
3455
3456 CASE(Int8) { PUSH_INT32(GET_INT8(REGS.pc)); }
3457 END_CASE(Int8)
3458
3459 CASE(Int32) { PUSH_INT32(GET_INT32(REGS.pc)); }
3460 END_CASE(Int32)
3461
3462 CASE(Double) { PUSH_COPY(GET_INLINE_VALUE(REGS.pc)); }
3463 END_CASE(Double)
3464
3465 CASE(String) { PUSH_STRING(script->getString(REGS.pc)); }
3466 END_CASE(String)
3467
3468 CASE(ToString) {
3469 MutableHandleValue oper = REGS.stackHandleAt(-1);
3470
3471 if (!oper.isString()) {
3472 JSString* operString = ToString<CanGC>(cx, oper);
3473 if (!operString) {
3474 goto error;
3475 }
3476 oper.setString(operString);
3477 }
3478 }
3479 END_CASE(ToString)
3480
3481 CASE(Symbol) {
3482 PUSH_SYMBOL(cx->wellKnownSymbols().get(GET_UINT8(REGS.pc)));
3483 }
3484 END_CASE(Symbol)
3485
3486 CASE(Object) {
3487 MOZ_ASSERT(script->treatAsRunOnce());
3488 PUSH_OBJECT(*script->getObject(REGS.pc));
3489 }
3490 END_CASE(Object)
3491
3492 CASE(CallSiteObj) {
3493 JSObject* cso = script->getObject(REGS.pc);
3494 MOZ_ASSERT(!cso->as<ArrayObject>().isExtensible());
3495 MOZ_ASSERT(cso->as<ArrayObject>().containsPure(cx->names().raw));
3496 PUSH_OBJECT(*cso);
3497 }
3498 END_CASE(CallSiteObj)
3499
3500 CASE(RegExp) {
3501 /*
3502 * Push a regexp object cloned from the regexp literal object mapped by
3503 * the bytecode at pc.
3504 */
3505 ReservedRooted<JSObject*> re(&rootObject0, script->getRegExp(REGS.pc));
3506 JSObject* obj = CloneRegExpObject(cx, re.as<RegExpObject>());
3507 if (!obj) {
3508 goto error;
3509 }
3510 PUSH_OBJECT(*obj);
3511 }
3512 END_CASE(RegExp)
3513
3514 CASE(Zero) { PUSH_INT32(0); }
3515 END_CASE(Zero)
3516
3517 CASE(One) { PUSH_INT32(1); }
3518 END_CASE(One)
3519
3520 CASE(Null) { PUSH_NULL(); }
3521 END_CASE(Null)
3522
3523 CASE(False) { PUSH_BOOLEAN(false); }
3524 END_CASE(False)
3525
3526 CASE(True) { PUSH_BOOLEAN(true); }
3527 END_CASE(True)
3528
3529 CASE(TableSwitch) {
3530 jsbytecode* pc2 = REGS.pc;
3531 int32_t len = GET_JUMP_OFFSET(pc2);
3532
3533 /*
3534 * ECMAv2+ forbids conversion of discriminant, so we will skip to the
3535 * default case if the discriminant isn't already an int jsval. (This
3536 * opcode is emitted only for dense int-domain switches.)
3537 */
3538 const Value& rref = *--REGS.sp;
3539 int32_t i;
3540 if (rref.isInt32()) {
3541 i = rref.toInt32();
3542 } else {
3543 /* Use mozilla::NumberEqualsInt32 to treat -0 (double) as 0. */
3544 if (!rref.isDouble() || !NumberEqualsInt32(rref.toDouble(), &i)) {
3545 ADVANCE_AND_DISPATCH(len);
3546 }
3547 }
3548
3549 pc2 += JUMP_OFFSET_LEN;
3550 int32_t low = GET_JUMP_OFFSET(pc2);
3551 pc2 += JUMP_OFFSET_LEN;
3552 int32_t high = GET_JUMP_OFFSET(pc2);
3553
3554 i = uint32_t(i) - uint32_t(low);
3555 if (uint32_t(i) < uint32_t(high - low + 1)) {
3556 len = script->tableSwitchCaseOffset(REGS.pc, uint32_t(i)) -
3557 script->pcToOffset(REGS.pc);
3558 }
3559 ADVANCE_AND_DISPATCH(len);
3560 }
3561
3562 CASE(Arguments) {
3563 MOZ_ASSERT(script->needsArgsObj());
3564 ArgumentsObject* obj = ArgumentsObject::createExpected(cx, REGS.fp());
3565 if (!obj) {
3566 goto error;
3567 }
3568 PUSH_COPY(ObjectValue(*obj));
3569 }
3570 END_CASE(Arguments)
3571
3572 CASE(Rest) {
3573 ReservedRooted<JSObject*> rest(&rootObject0,
3574 REGS.fp()->createRestParameter(cx));
3575 if (!rest) {
3576 goto error;
3577 }
3578 PUSH_COPY(ObjectValue(*rest));
3579 }
3580 END_CASE(Rest)
3581
3582 CASE(GetAliasedVar) {
3583 EnvironmentCoordinate ec = EnvironmentCoordinate(REGS.pc);
3584 ReservedRooted<Value> val(
3585 &rootValue0, REGS.fp()->aliasedEnvironment(ec).aliasedBinding(ec));
3586
3587 ASSERT_UNINITIALIZED_ALIASED_LEXICAL(val);
3588
3589 PUSH_COPY(val);
3590 }
3591 END_CASE(GetAliasedVar)
3592
3593 CASE(GetAliasedDebugVar) {
3594 EnvironmentCoordinate ec = EnvironmentCoordinate(REGS.pc);
3595 ReservedRooted<Value> val(
3596 &rootValue0,
3597 REGS.fp()->aliasedEnvironmentMaybeDebug(ec).aliasedBinding(ec));
3598
3599 ASSERT_UNINITIALIZED_ALIASED_LEXICAL(val);
3600
3601 PUSH_COPY(val);
3602 }
3603 END_CASE(GetAliasedVar)
3604
3605 CASE(SetAliasedVar) {
3606 EnvironmentCoordinate ec = EnvironmentCoordinate(REGS.pc);
3607 EnvironmentObject& obj = REGS.fp()->aliasedEnvironment(ec);
3608 MOZ_ASSERT(!IsUninitializedLexical(obj.aliasedBinding(ec)));
3609 obj.setAliasedBinding(ec, REGS.sp[-1]);
3610 }
3611 END_CASE(SetAliasedVar)
3612
3613 CASE(ThrowSetConst) {
3614 ReportRuntimeLexicalError(cx, JSMSG_BAD_CONST_ASSIGN, script, REGS.pc);
3615 goto error;
3616 }
3617 END_CASE(ThrowSetConst)
3618
3619 CASE(CheckLexical) {
3620 if (REGS.sp[-1].isMagic(JS_UNINITIALIZED_LEXICAL)) {
3621 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, script,
3622 REGS.pc);
3623 goto error;
3624 }
3625 }
3626 END_CASE(CheckLexical)
3627
3628 CASE(CheckAliasedLexical) {
3629 if (REGS.sp[-1].isMagic(JS_UNINITIALIZED_LEXICAL)) {
3630 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, script,
3631 REGS.pc);
3632 goto error;
3633 }
3634 }
3635 END_CASE(CheckAliasedLexical)
3636
3637 CASE(InitLexical) {
3638 uint32_t i = GET_LOCALNO(REGS.pc);
3639 REGS.fp()->unaliasedLocal(i) = REGS.sp[-1];
3640 }
3641 END_CASE(InitLexical)
3642
3643 CASE(InitAliasedLexical) {
3644 EnvironmentCoordinate ec = EnvironmentCoordinate(REGS.pc);
3645 EnvironmentObject& obj = REGS.fp()->aliasedEnvironment(ec);
3646 obj.setAliasedBinding(ec, REGS.sp[-1]);
3647 }
3648 END_CASE(InitAliasedLexical)
3649
3650 CASE(InitGLexical) {
3651 ExtensibleLexicalEnvironmentObject* lexicalEnv;
3652 if (script->hasNonSyntacticScope()) {
3653 lexicalEnv = &REGS.fp()->extensibleLexicalEnvironment();
3654 } else {
3655 lexicalEnv = &cx->global()->lexicalEnvironment();
3656 }
3657 HandleValue value = REGS.stackHandleAt(-1);
3658 InitGlobalLexicalOperation(cx, lexicalEnv, script, REGS.pc, value);
3659 }
3660 END_CASE(InitGLexical)
3661
3662 CASE(Uninitialized) { PUSH_MAGIC(JS_UNINITIALIZED_LEXICAL); }
3663 END_CASE(Uninitialized)
3664
3665 CASE(GetArg) {
3666 unsigned i = GET_ARGNO(REGS.pc);
3667 if (script->argsObjAliasesFormals()) {
3668 PUSH_COPY(REGS.fp()->argsObj().arg(i));
3669 } else {
3670 PUSH_COPY(REGS.fp()->unaliasedFormal(i));
3671 }
3672 }
3673 END_CASE(GetArg)
3674
3675 CASE(GetFrameArg) {
3676 uint32_t i = GET_ARGNO(REGS.pc);
3677 PUSH_COPY(REGS.fp()->unaliasedFormal(i, DONT_CHECK_ALIASING));
3678 }
3679 END_CASE(GetFrameArg)
3680
3681 CASE(SetArg) {
3682 unsigned i = GET_ARGNO(REGS.pc);
3683 if (script->argsObjAliasesFormals()) {
3684 REGS.fp()->argsObj().setArg(i, REGS.sp[-1]);
3685 } else {
3686 REGS.fp()->unaliasedFormal(i) = REGS.sp[-1];
3687 }
3688 }
3689 END_CASE(SetArg)
3690
3691 CASE(GetLocal) {
3692 uint32_t i = GET_LOCALNO(REGS.pc);
3693 PUSH_COPY_SKIP_CHECK(REGS.fp()->unaliasedLocal(i));
3694
3695 #ifdef DEBUG
3696 if (IsUninitializedLexical(REGS.sp[-1])) {
3697 JSOp next = JSOp(*GetNextPc(REGS.pc));
3698 MOZ_ASSERT(next == JSOp::CheckThis || next == JSOp::CheckReturn ||
3699 next == JSOp::CheckThisReinit || next == JSOp::CheckLexical);
3700 }
3701
3702 /*
3703 * Skip the same-compartment assertion if the local will be immediately
3704 * popped. We do not guarantee sync for dead locals when coming in from
3705 * the method JIT, and a GetLocal followed by Pop is not considered to
3706 * be a use of the variable.
3707 */
3708 if (JSOp(REGS.pc[JSOpLength_GetLocal]) != JSOp::Pop) {
3709 cx->debugOnlyCheck(REGS.sp[-1]);
3710 }
3711 #endif
3712 }
3713 END_CASE(GetLocal)
3714
3715 CASE(SetLocal) {
3716 uint32_t i = GET_LOCALNO(REGS.pc);
3717
3718 MOZ_ASSERT(!IsUninitializedLexical(REGS.fp()->unaliasedLocal(i)));
3719
3720 REGS.fp()->unaliasedLocal(i) = REGS.sp[-1];
3721 }
3722 END_CASE(SetLocal)
3723
3724 CASE(ArgumentsLength) {
3725 MOZ_ASSERT(!script->needsArgsObj());
3726 PUSH_INT32(REGS.fp()->numActualArgs());
3727 }
3728 END_CASE(ArgumentsLength)
3729
3730 CASE(GetActualArg) {
3731 MOZ_ASSERT(!script->needsArgsObj());
3732 uint32_t index = REGS.sp[-1].toInt32();
3733 REGS.sp[-1] = REGS.fp()->unaliasedActual(index);
3734 }
3735 END_CASE(GetActualArg)
3736
3737 CASE(GlobalOrEvalDeclInstantiation) {
3738 GCThingIndex lastFun = GET_GCTHING_INDEX(REGS.pc);
3739 HandleObject env = REGS.fp()->environmentChain();
3740 if (!GlobalOrEvalDeclInstantiation(cx, env, script, lastFun)) {
3741 goto error;
3742 }
3743 }
3744 END_CASE(GlobalOrEvalDeclInstantiation)
3745
3746 CASE(Lambda) {
3747 /* Load the specified function object literal. */
3748 ReservedRooted<JSFunction*> fun(&rootFunction0,
3749 script->getFunction(REGS.pc));
3750 JSObject* obj = Lambda(cx, fun, REGS.fp()->environmentChain());
3751 if (!obj) {
3752 goto error;
3753 }
3754
3755 MOZ_ASSERT(obj->staticPrototype());
3756 PUSH_OBJECT(*obj);
3757 }
3758 END_CASE(Lambda)
3759
3760 CASE(ToAsyncIter) {
3761 ReservedRooted<Value> nextMethod(&rootValue0, REGS.sp[-1]);
3762 ReservedRooted<JSObject*> iter(&rootObject1, &REGS.sp[-2].toObject());
3763 JSObject* asyncIter = CreateAsyncFromSyncIterator(cx, iter, nextMethod);
3764 if (!asyncIter) {
3765 goto error;
3766 }
3767
3768 REGS.sp--;
3769 REGS.sp[-1].setObject(*asyncIter);
3770 }
3771 END_CASE(ToAsyncIter)
3772
3773 CASE(CanSkipAwait) {
3774 ReservedRooted<Value> val(&rootValue0, REGS.sp[-1]);
3775 bool canSkip;
3776 if (!CanSkipAwait(cx, val, &canSkip)) {
3777 goto error;
3778 }
3779
3780 PUSH_BOOLEAN(canSkip);
3781 }
3782 END_CASE(CanSkipAwait)
3783
3784 CASE(MaybeExtractAwaitValue) {
3785 MutableHandleValue val = REGS.stackHandleAt(-2);
3786 ReservedRooted<Value> canSkip(&rootValue0, REGS.sp[-1]);
3787
3788 if (canSkip.toBoolean()) {
3789 if (!ExtractAwaitValue(cx, val, val)) {
3790 goto error;
3791 }
3792 }
3793 }
3794 END_CASE(MaybeExtractAwaitValue)
3795
3796 CASE(AsyncAwait) {
3797 MOZ_ASSERT(REGS.stackDepth() >= 2);
3798 ReservedRooted<JSObject*> gen(&rootObject1, &REGS.sp[-1].toObject());
3799 ReservedRooted<Value> value(&rootValue0, REGS.sp[-2]);
3800 JSObject* promise =
3801 AsyncFunctionAwait(cx, gen.as<AsyncFunctionGeneratorObject>(), value);
3802 if (!promise) {
3803 goto error;
3804 }
3805
3806 REGS.sp--;
3807 REGS.sp[-1].setObject(*promise);
3808 }
3809 END_CASE(AsyncAwait)
3810
3811 CASE(AsyncResolve) {
3812 MOZ_ASSERT(REGS.stackDepth() >= 2);
3813 ReservedRooted<JSObject*> gen(&rootObject1, &REGS.sp[-1].toObject());
3814 ReservedRooted<Value> value(&rootValue0, REGS.sp[-2]);
3815 JSObject* promise = AsyncFunctionResolve(
3816 cx, gen.as<AsyncFunctionGeneratorObject>(), value);
3817 if (!promise) {
3818 goto error;
3819 }
3820
3821 REGS.sp--;
3822 REGS.sp[-1].setObject(*promise);
3823 }
3824 END_CASE(AsyncResolve)
3825
3826 CASE(AsyncReject) {
3827 MOZ_ASSERT(REGS.stackDepth() >= 3);
3828 ReservedRooted<JSObject*> gen(&rootObject1, &REGS.sp[-1].toObject());
3829 ReservedRooted<Value> stack(&rootValue0, REGS.sp[-2]);
3830 ReservedRooted<Value> reason(&rootValue1, REGS.sp[-3]);
3831 JSObject* promise = AsyncFunctionReject(
3832 cx, gen.as<AsyncFunctionGeneratorObject>(), reason, stack);
3833 if (!promise) {
3834 goto error;
3835 }
3836
3837 REGS.sp -= 2;
3838 REGS.sp[-1].setObject(*promise);
3839 }
3840 END_CASE(AsyncReject)
3841
3842 CASE(SetFunName) {
3843 MOZ_ASSERT(REGS.stackDepth() >= 2);
3844 FunctionPrefixKind prefixKind = FunctionPrefixKind(GET_UINT8(REGS.pc));
3845 ReservedRooted<Value> name(&rootValue0, REGS.sp[-1]);
3846 ReservedRooted<JSFunction*> fun(&rootFunction0,
3847 &REGS.sp[-2].toObject().as<JSFunction>());
3848 if (!SetFunctionName(cx, fun, name, prefixKind)) {
3849 goto error;
3850 }
3851
3852 REGS.sp--;
3853 }
3854 END_CASE(SetFunName)
3855
3856 CASE(Callee) {
3857 MOZ_ASSERT(REGS.fp()->isFunctionFrame());
3858 PUSH_COPY(REGS.fp()->calleev());
3859 }
3860 END_CASE(Callee)
3861
3862 CASE(InitPropGetter)
3863 CASE(InitHiddenPropGetter)
3864 CASE(InitPropSetter)
3865 CASE(InitHiddenPropSetter) {
3866 MOZ_ASSERT(REGS.stackDepth() >= 2);
3867
3868 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-2].toObject());
3869 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
3870 ReservedRooted<JSObject*> val(&rootObject1, &REGS.sp[-1].toObject());
3871
3872 if (!InitPropGetterSetterOperation(cx, REGS.pc, obj, name, val)) {
3873 goto error;
3874 }
3875
3876 REGS.sp--;
3877 }
3878 END_CASE(InitPropGetter)
3879
3880 CASE(InitElemGetter)
3881 CASE(InitHiddenElemGetter)
3882 CASE(InitElemSetter)
3883 CASE(InitHiddenElemSetter) {
3884 MOZ_ASSERT(REGS.stackDepth() >= 3);
3885
3886 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-3].toObject());
3887 ReservedRooted<Value> idval(&rootValue0, REGS.sp[-2]);
3888 ReservedRooted<JSObject*> val(&rootObject1, &REGS.sp[-1].toObject());
3889
3890 if (!InitElemGetterSetterOperation(cx, REGS.pc, obj, idval, val)) {
3891 goto error;
3892 }
3893
3894 REGS.sp -= 2;
3895 }
3896 END_CASE(InitElemGetter)
3897
3898 CASE(Hole) { PUSH_MAGIC(JS_ELEMENTS_HOLE); }
3899 END_CASE(Hole)
3900
3901 CASE(NewInit) {
3902 JSObject* obj = NewObjectOperation(cx, script, REGS.pc);
3903
3904 if (!obj) {
3905 goto error;
3906 }
3907 PUSH_OBJECT(*obj);
3908 }
3909 END_CASE(NewInit)
3910
3911 CASE(NewArray) {
3912 uint32_t length = GET_UINT32(REGS.pc);
3913 ArrayObject* obj = NewArrayOperation(cx, length);
3914 if (!obj) {
3915 goto error;
3916 }
3917 PUSH_OBJECT(*obj);
3918 }
3919 END_CASE(NewArray)
3920
3921 CASE(NewObject) {
3922 JSObject* obj = NewObjectOperation(cx, script, REGS.pc);
3923 if (!obj) {
3924 goto error;
3925 }
3926 PUSH_OBJECT(*obj);
3927 }
3928 END_CASE(NewObject)
3929
3930 CASE(MutateProto) {
3931 MOZ_ASSERT(REGS.stackDepth() >= 2);
3932
3933 if (REGS.sp[-1].isObjectOrNull()) {
3934 ReservedRooted<JSObject*> newProto(&rootObject1,
3935 REGS.sp[-1].toObjectOrNull());
3936 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-2].toObject());
3937 MOZ_ASSERT(obj->is<PlainObject>());
3938
3939 if (!SetPrototype(cx, obj, newProto)) {
3940 goto error;
3941 }
3942 }
3943
3944 REGS.sp--;
3945 }
3946 END_CASE(MutateProto)
3947
3948 CASE(InitProp)
3949 CASE(InitLockedProp)
3950 CASE(InitHiddenProp) {
3951 static_assert(JSOpLength_InitProp == JSOpLength_InitLockedProp,
3952 "initprop and initlockedprop must be the same size");
3953 static_assert(JSOpLength_InitProp == JSOpLength_InitHiddenProp,
3954 "initprop and inithiddenprop must be the same size");
3955 /* Load the property's initial value into rval. */
3956 MOZ_ASSERT(REGS.stackDepth() >= 2);
3957 ReservedRooted<Value> rval(&rootValue0, REGS.sp[-1]);
3958
3959 /* Load the object being initialized into lval/obj. */
3960 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-2].toObject());
3961
3962 ReservedRooted<PropertyName*> name(&rootName0, script->getName(REGS.pc));
3963
3964 if (!InitPropertyOperation(cx, REGS.pc, obj, name, rval)) {
3965 goto error;
3966 }
3967
3968 REGS.sp--;
3969 }
3970 END_CASE(InitProp)
3971
3972 CASE(InitElem)
3973 CASE(InitHiddenElem)
3974 CASE(InitLockedElem) {
3975 MOZ_ASSERT(REGS.stackDepth() >= 3);
3976 HandleValue val = REGS.stackHandleAt(-1);
3977 HandleValue id = REGS.stackHandleAt(-2);
3978
3979 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-3].toObject());
3980
3981 if (!InitElemOperation(cx, REGS.pc, obj, id, val)) {
3982 goto error;
3983 }
3984
3985 REGS.sp -= 2;
3986 }
3987 END_CASE(InitElem)
3988
3989 CASE(InitElemArray) {
3990 MOZ_ASSERT(REGS.stackDepth() >= 2);
3991 HandleValue val = REGS.stackHandleAt(-1);
3992 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-2].toObject());
3993
3994 InitElemArrayOperation(cx, REGS.pc, obj.as<ArrayObject>(), val);
3995 REGS.sp--;
3996 }
3997 END_CASE(InitElemArray)
3998
3999 CASE(InitElemInc) {
4000 MOZ_ASSERT(REGS.stackDepth() >= 3);
4001 HandleValue val = REGS.stackHandleAt(-1);
4002
4003 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-3].toObject());
4004
4005 uint32_t index = REGS.sp[-2].toInt32();
4006 if (!InitElemIncOperation(cx, obj.as<ArrayObject>(), index, val)) {
4007 goto error;
4008 }
4009
4010 REGS.sp[-2].setInt32(index + 1);
4011 REGS.sp--;
4012 }
4013 END_CASE(InitElemInc)
4014
4015 CASE(Exception) {
4016 PUSH_NULL();
4017 MutableHandleValue res = REGS.stackHandleAt(-1);
4018 if (!GetAndClearException(cx, res)) {
4019 goto error;
4020 }
4021 }
4022 END_CASE(Exception)
4023
4024 CASE(ExceptionAndStack) {
4025 ReservedRooted<Value> stack(&rootValue0);
4026 if (!cx->getPendingExceptionStack(&stack)) {
4027 goto error;
4028 }
4029 PUSH_NULL();
4030 MutableHandleValue res = REGS.stackHandleAt(-1);
4031 if (!GetAndClearException(cx, res)) {
4032 goto error;
4033 }
4034 PUSH_COPY(stack);
4035 }
4036 END_CASE(ExceptionAndStack)
4037
4038 CASE(Finally) { CHECK_BRANCH(); }
4039 END_CASE(Finally)
4040
4041 CASE(Throw) {
4042 CHECK_BRANCH();
4043 ReservedRooted<Value> v(&rootValue0);
4044 POP_COPY_TO(v);
4045 MOZ_ALWAYS_FALSE(ThrowOperation(cx, v));
4046 /* let the code at error try to catch the exception. */
4047 goto error;
4048 }
4049
4050 CASE(ThrowWithStack) {
4051 CHECK_BRANCH();
4052 ReservedRooted<Value> v(&rootValue0);
4053 ReservedRooted<Value> stack(&rootValue1);
4054 POP_COPY_TO(stack);
4055 POP_COPY_TO(v);
4056 MOZ_ALWAYS_FALSE(ThrowWithStackOperation(cx, v, stack));
4057 /* let the code at error try to catch the exception. */
4058 goto error;
4059 }
4060
4061 CASE(Instanceof) {
4062 ReservedRooted<Value> rref(&rootValue0, REGS.sp[-1]);
4063 if (HandleValue(rref).isPrimitive()) {
4064 ReportValueError(cx, JSMSG_BAD_INSTANCEOF_RHS, -1, rref, nullptr);
4065 goto error;
4066 }
4067 ReservedRooted<JSObject*> obj(&rootObject0, &rref.toObject());
4068 bool cond = false;
4069 if (!InstanceofOperator(cx, obj, REGS.stackHandleAt(-2), &cond)) {
4070 goto error;
4071 }
4072 REGS.sp--;
4073 REGS.sp[-1].setBoolean(cond);
4074 }
4075 END_CASE(Instanceof)
4076
4077 CASE(Debugger) {
4078 if (!DebugAPI::onDebuggerStatement(cx, REGS.fp())) {
4079 goto error;
4080 }
4081 }
4082 END_CASE(Debugger)
4083
4084 CASE(PushLexicalEnv) {
4085 ReservedRooted<Scope*> scope(&rootScope0, script->getScope(REGS.pc));
4086
4087 // Create block environment and push on scope chain.
4088 if (!REGS.fp()->pushLexicalEnvironment(cx, scope.as<LexicalScope>())) {
4089 goto error;
4090 }
4091 }
4092 END_CASE(PushLexicalEnv)
4093
4094 CASE(PopLexicalEnv) {
4095 #ifdef DEBUG
4096 Scope* scope = script->lookupScope(REGS.pc);
4097 MOZ_ASSERT(scope);
4098 MOZ_ASSERT(scope->is<LexicalScope>() || scope->is<ClassBodyScope>());
4099 MOZ_ASSERT_IF(scope->is<LexicalScope>(),
4100 scope->as<LexicalScope>().hasEnvironment());
4101 MOZ_ASSERT_IF(scope->is<ClassBodyScope>(),
4102 scope->as<ClassBodyScope>().hasEnvironment());
4103 #endif
4104
4105 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
4106 DebugEnvironments::onPopLexical(cx, REGS.fp(), REGS.pc);
4107 }
4108
4109 // Pop block from scope chain.
4110 REGS.fp()->popOffEnvironmentChain<LexicalEnvironmentObject>();
4111 }
4112 END_CASE(PopLexicalEnv)
4113
4114 CASE(DebugLeaveLexicalEnv) {
4115 #ifdef DEBUG
4116 Scope* scope = script->lookupScope(REGS.pc);
4117 MOZ_ASSERT(scope);
4118 MOZ_ASSERT(scope->is<LexicalScope>() || scope->is<ClassBodyScope>());
4119 MOZ_ASSERT_IF(scope->is<LexicalScope>(),
4120 !scope->as<LexicalScope>().hasEnvironment());
4121 MOZ_ASSERT_IF(scope->is<ClassBodyScope>(),
4122 !scope->as<ClassBodyScope>().hasEnvironment());
4123 #endif
4124 // FIXME: This opcode should not be necessary. The debugger shouldn't
4125 // need help from bytecode to do its job. See bug 927782.
4126
4127 if (MOZ_UNLIKELY(cx->realm()->isDebuggee())) {
4128 DebugEnvironments::onPopLexical(cx, REGS.fp(), REGS.pc);
4129 }
4130 }
4131 END_CASE(DebugLeaveLexicalEnv)
4132
4133 CASE(FreshenLexicalEnv) {
4134 #ifdef DEBUG
4135 Scope* scope = script->getScope(REGS.pc);
4136 auto envChain = REGS.fp()->environmentChain();
4137 auto* envScope = &envChain->as<BlockLexicalEnvironmentObject>().scope();
4138 MOZ_ASSERT(scope == envScope);
4139 #endif
4140
4141 if (!REGS.fp()->freshenLexicalEnvironment(cx, REGS.pc)) {
4142 goto error;
4143 }
4144 }
4145 END_CASE(FreshenLexicalEnv)
4146
4147 CASE(RecreateLexicalEnv) {
4148 #ifdef DEBUG
4149 Scope* scope = script->getScope(REGS.pc);
4150 auto envChain = REGS.fp()->environmentChain();
4151 auto* envScope = &envChain->as<BlockLexicalEnvironmentObject>().scope();
4152 MOZ_ASSERT(scope == envScope);
4153 #endif
4154
4155 if (!REGS.fp()->recreateLexicalEnvironment(cx, REGS.pc)) {
4156 goto error;
4157 }
4158 }
4159 END_CASE(RecreateLexicalEnv)
4160
4161 CASE(PushClassBodyEnv) {
4162 ReservedRooted<Scope*> scope(&rootScope0, script->getScope(REGS.pc));
4163
4164 if (!REGS.fp()->pushClassBodyEnvironment(cx,
4165 scope.as<ClassBodyScope>())) {
4166 goto error;
4167 }
4168 }
4169 END_CASE(PushClassBodyEnv)
4170
4171 CASE(PushVarEnv) {
4172 ReservedRooted<Scope*> scope(&rootScope0, script->getScope(REGS.pc));
4173
4174 if (!REGS.fp()->pushVarEnvironment(cx, scope)) {
4175 goto error;
4176 }
4177 }
4178 END_CASE(PushVarEnv)
4179
4180 CASE(Generator) {
4181 MOZ_ASSERT(!cx->isExceptionPending());
4182 MOZ_ASSERT(REGS.stackDepth() == 0);
4183 JSObject* obj = AbstractGeneratorObject::createFromFrame(cx, REGS.fp());
4184 if (!obj) {
4185 goto error;
4186 }
4187 PUSH_OBJECT(*obj);
4188 }
4189 END_CASE(Generator)
4190
4191 CASE(InitialYield) {
4192 MOZ_ASSERT(!cx->isExceptionPending());
4193 MOZ_ASSERT_IF(script->isModule() && script->isAsync(),
4194 REGS.fp()->isModuleFrame());
4195 MOZ_ASSERT_IF(!script->isModule() && script->isAsync(),
4196 REGS.fp()->isFunctionFrame());
4197 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-1].toObject());
4198 POP_RETURN_VALUE();
4199 MOZ_ASSERT(REGS.stackDepth() == 0);
4200 if (!AbstractGeneratorObject::suspend(cx, obj, REGS.fp(), REGS.pc,
4201 script->nfixed())) {
4202 goto error;
4203 }
4204 goto successful_return_continuation;
4205 }
4206
4207 CASE(Yield)
4208 CASE(Await) {
4209 MOZ_ASSERT(!cx->isExceptionPending());
4210 MOZ_ASSERT_IF(script->isModule() && script->isAsync(),
4211 REGS.fp()->isModuleFrame());
4212 MOZ_ASSERT_IF(!script->isModule() && script->isAsync(),
4213 REGS.fp()->isFunctionFrame());
4214 ReservedRooted<JSObject*> obj(&rootObject0, &REGS.sp[-1].toObject());
4215 if (!AbstractGeneratorObject::suspend(
4216 cx, obj, REGS.fp(), REGS.pc,
4217 script->nfixed() + REGS.stackDepth() - 2)) {
4218 goto error;
4219 }
4220
4221 REGS.sp--;
4222 POP_RETURN_VALUE();
4223
4224 goto successful_return_continuation;
4225 }
4226
4227 CASE(ResumeKind) {
4228 GeneratorResumeKind resumeKind = ResumeKindFromPC(REGS.pc);
4229 PUSH_INT32(int32_t(resumeKind));
4230 }
4231 END_CASE(ResumeKind)
4232
4233 CASE(CheckResumeKind) {
4234 int32_t kindInt = REGS.sp[-1].toInt32();
4235 GeneratorResumeKind resumeKind = IntToResumeKind(kindInt);
4236 if (MOZ_UNLIKELY(resumeKind != GeneratorResumeKind::Next)) {
4237 ReservedRooted<Value> val(&rootValue0, REGS.sp[-3]);
4238 Rooted<AbstractGeneratorObject*> gen(
4239 cx, &REGS.sp[-2].toObject().as<AbstractGeneratorObject>());
4240 MOZ_ALWAYS_FALSE(GeneratorThrowOrReturn(cx, activation.regs().fp(), gen,
4241 val, resumeKind));
4242 goto error;
4243 }
4244 REGS.sp -= 2;
4245 }
4246 END_CASE(CheckResumeKind)
4247
4248 CASE(Resume) {
4249 {
4250 Rooted<AbstractGeneratorObject*> gen(
4251 cx, &REGS.sp[-3].toObject().as<AbstractGeneratorObject>());
4252 ReservedRooted<Value> val(&rootValue0, REGS.sp[-2]);
4253 ReservedRooted<Value> resumeKindVal(&rootValue1, REGS.sp[-1]);
4254
4255 // popInlineFrame expects there to be an additional value on the stack
4256 // to pop off, so leave "gen" on the stack.
4257 REGS.sp -= 1;
4258
4259 if (!AbstractGeneratorObject::resume(cx, activation, gen, val,
4260 resumeKindVal)) {
4261 goto error;
4262 }
4263
4264 JSScript* generatorScript = REGS.fp()->script();
4265 if (cx->realm() != generatorScript->realm()) {
4266 cx->enterRealmOf(generatorScript);
4267 }
4268 SET_SCRIPT(generatorScript);
4269
4270 if (!probes::EnterScript(cx, generatorScript,
4271 generatorScript->function(), REGS.fp())) {
4272 goto error;
4273 }
4274
4275 if (!DebugAPI::onResumeFrame(cx, REGS.fp())) {
4276 MOZ_ASSERT_IF(cx->isPropagatingForcedReturn(), gen->isClosed());
4277 goto error;
4278 }
4279 }
4280 ADVANCE_AND_DISPATCH(0);
4281 }
4282
4283 CASE(AfterYield) {
4284 // AbstractGeneratorObject::resume takes care of setting the frame's
4285 // debuggee flag.
4286 MOZ_ASSERT_IF(REGS.fp()->script()->isDebuggee(), REGS.fp()->isDebuggee());
4287 COUNT_COVERAGE();
4288 }
4289 END_CASE(AfterYield)
4290
4291 CASE(FinalYieldRval) {
4292 ReservedRooted<JSObject*> gen(&rootObject0, &REGS.sp[-1].toObject());
4293 REGS.sp--;
4294 AbstractGeneratorObject::finalSuspend(cx, gen);
4295 goto successful_return_continuation;
4296 }
4297
4298 CASE(CheckClassHeritage) {
4299 HandleValue heritage = REGS.stackHandleAt(-1);
4300
4301 if (!CheckClassHeritageOperation(cx, heritage)) {
4302 goto error;
4303 }
4304 }
4305 END_CASE(CheckClassHeritage)
4306
4307 CASE(BuiltinObject) {
4308 auto kind = BuiltinObjectKind(GET_UINT8(REGS.pc));
4309 JSObject* builtin = BuiltinObjectOperation(cx, kind);
4310 if (!builtin) {
4311 goto error;
4312 }
4313 PUSH_OBJECT(*builtin);
4314 }
4315 END_CASE(BuiltinObject)
4316
4317 CASE(FunWithProto) {
4318 ReservedRooted<JSObject*> proto(&rootObject1, &REGS.sp[-1].toObject());
4319
4320 /* Load the specified function object literal. */
4321 ReservedRooted<JSFunction*> fun(&rootFunction0,
4322 script->getFunction(REGS.pc));
4323
4324 JSObject* obj =
4325 FunWithProtoOperation(cx, fun, REGS.fp()->environmentChain(), proto);
4326 if (!obj) {
4327 goto error;
4328 }
4329
4330 REGS.sp[-1].setObject(*obj);
4331 }
4332 END_CASE(FunWithProto)
4333
4334 CASE(ObjWithProto) {
4335 JSObject* obj = ObjectWithProtoOperation(cx, REGS.stackHandleAt(-1));
4336 if (!obj) {
4337 goto error;
4338 }
4339
4340 REGS.sp[-1].setObject(*obj);
4341 }
4342 END_CASE(ObjWithProto)
4343
4344 CASE(InitHomeObject) {
4345 MOZ_ASSERT(REGS.stackDepth() >= 2);
4346
4347 /* Load the function to be initialized */
4348 JSFunction* func = &REGS.sp[-2].toObject().as<JSFunction>();
4349 MOZ_ASSERT(func->allowSuperProperty());
4350
4351 /* Load the home object */
4352 JSObject* obj = &REGS.sp[-1].toObject();
4353 MOZ_ASSERT(obj->is<PlainObject>() || obj->is<JSFunction>());
4354
4355 func->setExtendedSlot(FunctionExtended::METHOD_HOMEOBJECT_SLOT,
4356 ObjectValue(*obj));
4357 REGS.sp--;
4358 }
4359 END_CASE(InitHomeObject)
4360
4361 CASE(SuperBase) {
4362 JSFunction& superEnvFunc = REGS.sp[-1].toObject().as<JSFunction>();
4363 MOZ_ASSERT(superEnvFunc.allowSuperProperty());
4364 MOZ_ASSERT(superEnvFunc.baseScript()->needsHomeObject());
4365 const Value& homeObjVal = superEnvFunc.getExtendedSlot(
4366 FunctionExtended::METHOD_HOMEOBJECT_SLOT);
4367
4368 JSObject* homeObj = &homeObjVal.toObject();
4369 JSObject* superBase = HomeObjectSuperBase(homeObj);
4370
4371 REGS.sp[-1].setObjectOrNull(superBase);
4372 }
4373 END_CASE(SuperBase)
4374
4375 CASE(NewTarget) {
4376 PUSH_COPY(REGS.fp()->newTarget());
4377 MOZ_ASSERT(REGS.sp[-1].isObject() || REGS.sp[-1].isUndefined());
4378 }
4379 END_CASE(NewTarget)
4380
4381 CASE(ImportMeta) {
4382 JSObject* metaObject = ImportMetaOperation(cx, script);
4383 if (!metaObject) {
4384 goto error;
4385 }
4386
4387 PUSH_OBJECT(*metaObject);
4388 }
4389 END_CASE(ImportMeta)
4390
4391 CASE(DynamicImport) {
4392 ReservedRooted<Value> options(&rootValue0, REGS.sp[-1]);
4393 REGS.sp--;
4394
4395 ReservedRooted<Value> specifier(&rootValue1);
4396 POP_COPY_TO(specifier);
4397
4398 JSObject* promise =
4399 StartDynamicModuleImport(cx, script, specifier, options);
4400 if (!promise) goto error;
4401
4402 PUSH_OBJECT(*promise);
4403 }
4404 END_CASE(DynamicImport)
4405
4406 CASE(EnvCallee) {
4407 uint8_t numHops = GET_UINT8(REGS.pc);
4408 JSObject* env = &REGS.fp()->environmentChain()->as<EnvironmentObject>();
4409 for (unsigned i = 0; i < numHops; i++) {
4410 env = &env->as<EnvironmentObject>().enclosingEnvironment();
4411 }
4412 PUSH_OBJECT(env->as<CallObject>().callee());
4413 }
4414 END_CASE(EnvCallee)
4415
4416 CASE(SuperFun) {
4417 JSObject* superEnvFunc = &REGS.sp[-1].toObject();
4418 JSObject* superFun = SuperFunOperation(superEnvFunc);
4419 REGS.sp[-1].setObjectOrNull(superFun);
4420 }
4421 END_CASE(SuperFun)
4422
4423 CASE(CheckObjCoercible) {
4424 ReservedRooted<Value> checkVal(&rootValue0, REGS.sp[-1]);
4425 if (checkVal.isNullOrUndefined()) {
4426 MOZ_ALWAYS_FALSE(ThrowObjectCoercible(cx, checkVal));
4427 goto error;
4428 }
4429 }
4430 END_CASE(CheckObjCoercible)
4431
4432 CASE(DebugCheckSelfHosted) {
4433 #ifdef DEBUG
4434 ReservedRooted<Value> checkVal(&rootValue0, REGS.sp[-1]);
4435 if (!Debug_CheckSelfHosted(cx, checkVal)) {
4436 goto error;
4437 }
4438 #endif
4439 }
4440 END_CASE(DebugCheckSelfHosted)
4441
4442 CASE(IsConstructing) { PUSH_MAGIC(JS_IS_CONSTRUCTING); }
4443 END_CASE(IsConstructing)
4444
4445 CASE(Inc) {
4446 MutableHandleValue val = REGS.stackHandleAt(-1);
4447 if (!IncOperation(cx, val, val)) {
4448 goto error;
4449 }
4450 }
4451 END_CASE(Inc)
4452
4453 CASE(Dec) {
4454 MutableHandleValue val = REGS.stackHandleAt(-1);
4455 if (!DecOperation(cx, val, val)) {
4456 goto error;
4457 }
4458 }
4459 END_CASE(Dec)
4460
4461 CASE(ToNumeric) {
4462 if (!ToNumeric(cx, REGS.stackHandleAt(-1))) {
4463 goto error;
4464 }
4465 }
4466 END_CASE(ToNumeric)
4467
4468 CASE(BigInt) { PUSH_BIGINT(script->getBigInt(REGS.pc)); }
4469 END_CASE(BigInt)
4470
4471 DEFAULT() {
4472 char numBuf[12];
4473 SprintfLiteral(numBuf, "%d", *REGS.pc);
4474 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4475 JSMSG_BAD_BYTECODE, numBuf);
4476 goto error;
4477 }
4478
4479 } /* interpreter loop */
4480
4481 MOZ_CRASH("Interpreter loop exited via fallthrough");
4482
4483 error:
4484 switch (HandleError(cx, REGS)) {
4485 case SuccessfulReturnContinuation:
4486 goto successful_return_continuation;
4487
4488 case ErrorReturnContinuation:
4489 interpReturnOK = false;
4490 goto return_continuation;
4491
4492 case CatchContinuation:
4493 ADVANCE_AND_DISPATCH(0);
4494
4495 case FinallyContinuation: {
4496 /*
4497 * Push (exception, stack, true) triple for finally to indicate that we
4498 * should rethrow the exception.
4499 */
4500 ReservedRooted<Value> exception(&rootValue0);
4501 ReservedRooted<Value> exceptionStack(&rootValue1);
4502 if (!cx->getPendingException(&exception) ||
4503 !cx->getPendingExceptionStack(&exceptionStack)) {
4504 interpReturnOK = false;
4505 goto return_continuation;
4506 }
4507 PUSH_COPY(exception);
4508 PUSH_COPY(exceptionStack);
4509 PUSH_BOOLEAN(true);
4510 cx->clearPendingException();
4511 }
4512 ADVANCE_AND_DISPATCH(0);
4513 }
4514
4515 MOZ_CRASH("Invalid HandleError continuation");
4516
4517 exit:
4518 if (MOZ_LIKELY(!frameHalfInitialized)) {
4519 interpReturnOK =
4520 DebugAPI::onLeaveFrame(cx, REGS.fp(), REGS.pc, interpReturnOK);
4521
4522 REGS.fp()->epilogue(cx, REGS.pc);
4523 }
4524
4525 gc::MaybeVerifyBarriers(cx, true);
4526
4527 /*
4528 * This path is used when it's guaranteed the method can be finished
4529 * inside the JIT.
4530 */
4531 leave_on_safe_point:
4532
4533 if (interpReturnOK) {
4534 state.setReturnValue(activation.entryFrame()->returnValue());
4535 }
4536
4537 return interpReturnOK;
4538
4539 prologue_error:
4540 interpReturnOK = false;
4541 frameHalfInitialized = true;
4542 goto prologue_return_continuation;
4543 }
4544
4545 bool js::ThrowOperation(JSContext* cx, HandleValue v) {
4546 MOZ_ASSERT(!cx->isExceptionPending());
4547 cx->setPendingException(v, ShouldCaptureStack::Maybe);
4548 return false;
4549 }
4550
4551 bool js::ThrowWithStackOperation(JSContext* cx, HandleValue v,
4552 HandleValue stack) {
4553 MOZ_ASSERT(!cx->isExceptionPending());
4554 MOZ_ASSERT(stack.isObjectOrNull());
4555
4556 // Use a normal throw when no stack was recorded.
4557 if (!stack.isObject()) {
4558 return ThrowOperation(cx, v);
4559 }
4560
4561 MOZ_ASSERT(UncheckedUnwrap(&stack.toObject())->is<SavedFrame>() ||
4562 IsDeadProxyObject(&stack.toObject()));
4563
4564 Rooted<SavedFrame*> stackObj(cx,
4565 stack.toObject().maybeUnwrapIf<SavedFrame>());
4566 cx->setPendingException(v, stackObj);
4567 return false;
4568 }
4569
4570 bool js::GetPendingExceptionStack(JSContext* cx, MutableHandleValue vp) {
4571 MOZ_ASSERT(cx->isExceptionPending());
4572 return cx->getPendingExceptionStack(vp);
4573 }
4574
4575 bool js::GetProperty(JSContext* cx, HandleValue v, Handle<PropertyName*> name,
4576 MutableHandleValue vp) {
4577 if (name == cx->names().length) {
4578 // Fast path for strings, arrays and arguments.
4579 if (::GetLengthProperty(v, vp)) {
4580 return true;
4581 }
4582 }
4583
4584 // Optimize common cases like (2).toString() or "foo".valueOf() to not
4585 // create a wrapper object.
4586 if (v.isPrimitive() && !v.isNullOrUndefined()) {
4587 JSObject* proto;
4588
4589 switch (v.type()) {
4590 case ValueType::Double:
4591 case ValueType::Int32:
4592 proto = GlobalObject::getOrCreateNumberPrototype(cx, cx->global());
4593 break;
4594 case ValueType::Boolean:
4595 proto = GlobalObject::getOrCreateBooleanPrototype(cx, cx->global());
4596 break;
4597 case ValueType::String:
4598 proto = GlobalObject::getOrCreateStringPrototype(cx, cx->global());
4599 break;
4600 case ValueType::Symbol:
4601 proto = GlobalObject::getOrCreateSymbolPrototype(cx, cx->global());
4602 break;
4603 case ValueType::BigInt:
4604 proto = GlobalObject::getOrCreateBigIntPrototype(cx, cx->global());
4605 break;
4606 case ValueType::Undefined:
4607 case ValueType::Null:
4608 case ValueType::Magic:
4609 case ValueType::PrivateGCThing:
4610 case ValueType::Object:
4611 MOZ_CRASH("unexpected type");
4612 }
4613
4614 if (!proto) {
4615 return false;
4616 }
4617
4618 if (GetPropertyPure(cx, proto, NameToId(name), vp.address())) {
4619 return true;
4620 }
4621 }
4622
4623 RootedValue receiver(cx, v);
4624 RootedObject obj(
4625 cx, ToObjectFromStackForPropertyAccess(cx, v, JSDVG_SEARCH_STACK, name));
4626 if (!obj) {
4627 return false;
4628 }
4629
4630 return GetProperty(cx, obj, receiver, name, vp);
4631 }
4632
4633 JSObject* js::LambdaBaselineFallback(JSContext* cx, HandleFunction fun,
4634 HandleObject parent, gc::AllocSite* site) {
4635 MOZ_ASSERT(site);
4636 gc::Heap heap = site->initialHeap();
4637 JSObject* obj = Lambda(cx, fun, parent, heap, site);
4638 MOZ_ASSERT_IF(obj && heap == gc::Heap::Tenured, obj->isTenured());
4639 return obj;
4640 }
4641
4642 JSObject* js::LambdaOptimizedFallback(JSContext* cx, HandleFunction fun,
4643 HandleObject parent, gc::Heap heap) {
4644 // It's important to use the correct heap here so that tenured allocation
4645 // fallback will refill the appropriate free list allowing subsequent JIT
4646 // allocation in tenured heap to succeed.
4647 gc::AllocSite* site = cx->zone()->optimizedAllocSite();
4648 JSObject* obj = Lambda(cx, fun, parent, heap, site);
4649 MOZ_ASSERT_IF(obj && heap == gc::Heap::Tenured, obj->isTenured());
4650 return obj;
4651 }
4652
4653 JSObject* js::Lambda(JSContext* cx, HandleFunction fun, HandleObject parent,
4654 gc::Heap heap, gc::AllocSite* site) {
4655 JSFunction* clone;
4656 if (fun->isNativeFun()) {
4657 MOZ_ASSERT(IsAsmJSModule(fun));
4658 MOZ_ASSERT(heap == gc::Heap::Default); // Not supported.
4659 clone = CloneAsmJSModuleFunction(cx, fun);
4660 } else {
4661 RootedObject proto(cx, fun->staticPrototype());
4662 clone = CloneFunctionReuseScript(cx, fun, parent, proto, heap, site);
4663 }
4664 if (!clone) {
4665 return nullptr;
4666 }
4667
4668 MOZ_ASSERT(fun->global() == clone->global());
4669 return clone;
4670 }
4671
4672 JSObject* js::BindVarOperation(JSContext* cx, JSObject* envChain) {
4673 // Note: BindVarOperation has an unused cx argument because the JIT callVM
4674 // machinery requires this.
4675 return &GetVariablesObject(envChain);
4676 }
4677
4678 JSObject* js::ImportMetaOperation(JSContext* cx, HandleScript script) {
4679 RootedObject module(cx, GetModuleObjectForScript(script));
4680 return GetOrCreateModuleMetaObject(cx, module);
4681 }
4682
4683 JSObject* js::BuiltinObjectOperation(JSContext* cx, BuiltinObjectKind kind) {
4684 return GetOrCreateBuiltinObject(cx, kind);
4685 }
4686
4687 bool js::ThrowMsgOperation(JSContext* cx, const unsigned throwMsgKind) {
4688 auto errorNum = ThrowMsgKindToErrNum(ThrowMsgKind(throwMsgKind));
4689 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNum);
4690 return false;
4691 }
4692
4693 bool js::GetAndClearExceptionAndStack(JSContext* cx, MutableHandleValue res,
4694 MutableHandle<SavedFrame*> stack) {
4695 if (!cx->getPendingException(res)) {
4696 return false;
4697 }
4698 stack.set(cx->getPendingExceptionStack());
4699 cx->clearPendingException();
4700
4701 // Allow interrupting deeply nested exception handling.
4702 return CheckForInterrupt(cx);
4703 }
4704
4705 bool js::GetAndClearException(JSContext* cx, MutableHandleValue res) {
4706 Rooted<SavedFrame*> stack(cx);
4707 return GetAndClearExceptionAndStack(cx, res, &stack);
4708 }
4709
4710 template <bool strict>
4711 bool js::DelPropOperation(JSContext* cx, HandleValue val,
4712 Handle<PropertyName*> name, bool* res) {
4713 const int valIndex = -1;
4714 RootedObject obj(cx,
4715 ToObjectFromStackForPropertyAccess(cx, val, valIndex, name));
4716 if (!obj) {
4717 return false;
4718 }
4719
4720 RootedId id(cx, NameToId(name));
4721 ObjectOpResult result;
4722 if (!DeleteProperty(cx, obj, id, result)) {
4723 return false;
4724 }
4725
4726 if (strict) {
4727 if (!result) {
4728 return result.reportError(cx, obj, id);
4729 }
4730 *res = true;
4731 } else {
4732 *res = result.ok();
4733 }
4734 return true;
4735 }
4736
4737 template bool js::DelPropOperation<true>(JSContext* cx, HandleValue val,
4738 Handle<PropertyName*> name, bool* res);
4739 template bool js::DelPropOperation<false>(JSContext* cx, HandleValue val,
4740 Handle<PropertyName*> name,
4741 bool* res);
4742
4743 template <bool strict>
4744 bool js::DelElemOperation(JSContext* cx, HandleValue val, HandleValue index,
4745 bool* res) {
4746 const int valIndex = -2;
4747 RootedObject obj(
4748 cx, ToObjectFromStackForPropertyAccess(cx, val, valIndex, index));
4749 if (!obj) {
4750 return false;
4751 }
4752
4753 RootedId id(cx);
4754 if (!ToPropertyKey(cx, index, &id)) {
4755 return false;
4756 }
4757 ObjectOpResult result;
4758 if (!DeleteProperty(cx, obj, id, result)) {
4759 return false;
4760 }
4761
4762 if (strict) {
4763 if (!result) {
4764 return result.reportError(cx, obj, id);
4765 }
4766 *res = true;
4767 } else {
4768 *res = result.ok();
4769 }
4770 return true;
4771 }
4772
4773 template bool js::DelElemOperation<true>(JSContext*, HandleValue, HandleValue,
4774 bool*);
4775 template bool js::DelElemOperation<false>(JSContext*, HandleValue, HandleValue,
4776 bool*);
4777
4778 bool js::SetObjectElement(JSContext* cx, HandleObject obj, HandleValue index,
4779 HandleValue value, bool strict) {
4780 RootedId id(cx);
4781 if (!ToPropertyKey(cx, index, &id)) {
4782 return false;
4783 }
4784 RootedValue receiver(cx, ObjectValue(*obj));
4785 return SetObjectElementOperation(cx, obj, id, value, receiver, strict);
4786 }
4787
4788 bool js::SetObjectElementWithReceiver(JSContext* cx, HandleObject obj,
4789 HandleValue index, HandleValue value,
4790 HandleValue receiver, bool strict) {
4791 RootedId id(cx);
4792 if (!ToPropertyKey(cx, index, &id)) {
4793 return false;
4794 }
4795 return SetObjectElementOperation(cx, obj, id, value, receiver, strict);
4796 }
4797
4798 bool js::AddValues(JSContext* cx, MutableHandleValue lhs,
4799 MutableHandleValue rhs, MutableHandleValue res) {
4800 return AddOperation(cx, lhs, rhs, res);
4801 }
4802
4803 bool js::SubValues(JSContext* cx, MutableHandleValue lhs,
4804 MutableHandleValue rhs, MutableHandleValue res) {
4805 return SubOperation(cx, lhs, rhs, res);
4806 }
4807
4808 bool js::MulValues(JSContext* cx, MutableHandleValue lhs,
4809 MutableHandleValue rhs, MutableHandleValue res) {
4810 return MulOperation(cx, lhs, rhs, res);
4811 }
4812
4813 bool js::DivValues(JSContext* cx, MutableHandleValue lhs,
4814 MutableHandleValue rhs, MutableHandleValue res) {
4815 return DivOperation(cx, lhs, rhs, res);
4816 }
4817
4818 bool js::ModValues(JSContext* cx, MutableHandleValue lhs,
4819 MutableHandleValue rhs, MutableHandleValue res) {
4820 return ModOperation(cx, lhs, rhs, res);
4821 }
4822
4823 bool js::PowValues(JSContext* cx, MutableHandleValue lhs,
4824 MutableHandleValue rhs, MutableHandleValue res) {
4825 return PowOperation(cx, lhs, rhs, res);
4826 }
4827
4828 bool js::BitNot(JSContext* cx, MutableHandleValue in, MutableHandleValue res) {
4829 return BitNotOperation(cx, in, res);
4830 }
4831
4832 bool js::BitXor(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4833 MutableHandleValue res) {
4834 return BitXorOperation(cx, lhs, rhs, res);
4835 }
4836
4837 bool js::BitOr(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4838 MutableHandleValue res) {
4839 return BitOrOperation(cx, lhs, rhs, res);
4840 }
4841
4842 bool js::BitAnd(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4843 MutableHandleValue res) {
4844 return BitAndOperation(cx, lhs, rhs, res);
4845 }
4846
4847 bool js::BitLsh(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4848 MutableHandleValue res) {
4849 return BitLshOperation(cx, lhs, rhs, res);
4850 }
4851
4852 bool js::BitRsh(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4853 MutableHandleValue res) {
4854 return BitRshOperation(cx, lhs, rhs, res);
4855 }
4856
4857 bool js::UrshValues(JSContext* cx, MutableHandleValue lhs,
4858 MutableHandleValue rhs, MutableHandleValue res) {
4859 return UrshOperation(cx, lhs, rhs, res);
4860 }
4861
4862 bool js::LessThan(JSContext* cx, MutableHandleValue lhs, MutableHandleValue rhs,
4863 bool* res) {
4864 return LessThanOperation(cx, lhs, rhs, res);
4865 }
4866
4867 bool js::LessThanOrEqual(JSContext* cx, MutableHandleValue lhs,
4868 MutableHandleValue rhs, bool* res) {
4869 return LessThanOrEqualOperation(cx, lhs, rhs, res);
4870 }
4871
4872 bool js::GreaterThan(JSContext* cx, MutableHandleValue lhs,
4873 MutableHandleValue rhs, bool* res) {
4874 return GreaterThanOperation(cx, lhs, rhs, res);
4875 }
4876
4877 bool js::GreaterThanOrEqual(JSContext* cx, MutableHandleValue lhs,
4878 MutableHandleValue rhs, bool* res) {
4879 return GreaterThanOrEqualOperation(cx, lhs, rhs, res);
4880 }
4881
4882 bool js::DeleteNameOperation(JSContext* cx, Handle<PropertyName*> name,
4883 HandleObject envChain, MutableHandleValue res) {
4884 RootedObject env(cx), pobj(cx);
4885 PropertyResult prop;
4886 if (!LookupName(cx, name, envChain, &env, &pobj, &prop)) {
4887 return false;
4888 }
4889
4890 if (!env) {
4891 // Return true for non-existent names.
4892 res.setBoolean(true);
4893 return true;
4894 }
4895
4896 ObjectOpResult result;
4897 RootedId id(cx, NameToId(name));
4898 if (!DeleteProperty(cx, env, id, result)) {
4899 return false;
4900 }
4901
4902 bool status = result.ok();
4903 res.setBoolean(status);
4904
4905 return true;
4906 }
4907
4908 void js::ImplicitThisOperation(JSContext* cx, HandleObject env,
4909 MutableHandleValue res) {
4910 // Note: ImplicitThisOperation has an unused cx argument because the JIT
4911 // callVM machinery requires this.
4912 res.set(ComputeImplicitThis(env));
4913 }
4914
4915 unsigned js::GetInitDataPropAttrs(JSOp op) {
4916 switch (op) {
4917 case JSOp::InitProp:
4918 case JSOp::InitElem:
4919 return JSPROP_ENUMERATE;
4920 case JSOp::InitLockedProp:
4921 case JSOp::InitLockedElem:
4922 return JSPROP_PERMANENT | JSPROP_READONLY;
4923 case JSOp::InitHiddenProp:
4924 case JSOp::InitHiddenElem:
4925 // Non-enumerable, but writable and configurable
4926 return 0;
4927 default:;
4928 }
4929 MOZ_CRASH("Unknown data initprop");
4930 }
4931
4932 static bool InitGetterSetterOperation(JSContext* cx, jsbytecode* pc,
4933 HandleObject obj, HandleId id,
4934 HandleObject val) {
4935 MOZ_ASSERT(val->isCallable());
4936
4937 JSOp op = JSOp(*pc);
4938
4939 unsigned attrs = 0;
4940 if (!IsHiddenInitOp(op)) {
4941 attrs |= JSPROP_ENUMERATE;
4942 }
4943
4944 if (op == JSOp::InitPropGetter || op == JSOp::InitElemGetter ||
4945 op == JSOp::InitHiddenPropGetter || op == JSOp::InitHiddenElemGetter) {
4946 return DefineAccessorProperty(cx, obj, id, val, nullptr, attrs);
4947 }
4948
4949 MOZ_ASSERT(op == JSOp::InitPropSetter || op == JSOp::InitElemSetter ||
4950 op == JSOp::InitHiddenPropSetter ||
4951 op == JSOp::InitHiddenElemSetter);
4952 return DefineAccessorProperty(cx, obj, id, nullptr, val, attrs);
4953 }
4954
4955 bool js::InitPropGetterSetterOperation(JSContext* cx, jsbytecode* pc,
4956 HandleObject obj,
4957 Handle<PropertyName*> name,
4958 HandleObject val) {
4959 RootedId id(cx, NameToId(name));
4960 return InitGetterSetterOperation(cx, pc, obj, id, val);
4961 }
4962
4963 bool js::InitElemGetterSetterOperation(JSContext* cx, jsbytecode* pc,
4964 HandleObject obj, HandleValue idval,
4965 HandleObject val) {
4966 RootedId id(cx);
4967 if (!ToPropertyKey(cx, idval, &id)) {
4968 return false;
4969 }
4970
4971 return InitGetterSetterOperation(cx, pc, obj, id, val);
4972 }
4973
4974 bool js::SpreadCallOperation(JSContext* cx, HandleScript script, jsbytecode* pc,
4975 HandleValue thisv, HandleValue callee,
4976 HandleValue arr, HandleValue newTarget,
4977 MutableHandleValue res) {
4978 Rooted<ArrayObject*> aobj(cx, &arr.toObject().as<ArrayObject>());
4979 uint32_t length = aobj->length();
4980 JSOp op = JSOp(*pc);
4981 bool constructing = op == JSOp::SpreadNew || op == JSOp::SpreadSuperCall;
4982
4983 // {Construct,Invoke}Args::init does this too, but this gives us a better
4984 // error message.
4985 if (length > ARGS_LENGTH_MAX) {
4986 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4987 constructing ? JSMSG_TOO_MANY_CON_SPREADARGS
4988 : JSMSG_TOO_MANY_FUN_SPREADARGS);
4989 return false;
4990 }
4991
4992 // Do our own checks for the callee being a function, as Invoke uses the
4993 // expression decompiler to decompile the callee stack operand based on
4994 // the number of arguments. Spread operations have the callee at sp - 3
4995 // when not constructing, and sp - 4 when constructing.
4996 if (callee.isPrimitive()) {
4997 return ReportIsNotFunction(cx, callee, 2 + constructing,
4998 constructing ? CONSTRUCT : NO_CONSTRUCT);
4999 }
5000
5001 if (!callee.toObject().isCallable()) {
5002 return ReportIsNotFunction(cx, callee, 2 + constructing,
5003 constructing ? CONSTRUCT : NO_CONSTRUCT);
5004 }
5005
5006 // The object must be an array with dense elements and no holes. Baseline's
5007 // optimized spread call stubs rely on this.
5008 MOZ_ASSERT(IsPackedArray(aobj));
5009
5010 if (constructing) {
5011 if (!StackCheckIsConstructorCalleeNewTarget(cx, callee, newTarget)) {
5012 return false;
5013 }
5014
5015 ConstructArgs cargs(cx);
5016 if (!cargs.init(cx, length)) {
5017 return false;
5018 }
5019
5020 if (!GetElements(cx, aobj, length, cargs.array())) {
5021 return false;
5022 }
5023
5024 RootedObject obj(cx);
5025 if (!Construct(cx, callee, cargs, newTarget, &obj)) {
5026 return false;
5027 }
5028 res.setObject(*obj);
5029 } else {
5030 InvokeArgs args(cx);
5031 if (!args.init(cx, length)) {
5032 return false;
5033 }
5034
5035 if (!GetElements(cx, aobj, length, args.array())) {
5036 return false;
5037 }
5038
5039 if ((op == JSOp::SpreadEval || op == JSOp::StrictSpreadEval) &&
5040 cx->global()->valueIsEval(callee)) {
5041 if (!DirectEval(cx, args.get(0), res)) {
5042 return false;
5043 }
5044 } else {
5045 MOZ_ASSERT(op == JSOp::SpreadCall || op == JSOp::SpreadEval ||
5046 op == JSOp::StrictSpreadEval,
5047 "bad spread opcode");
5048
5049 if (!Call(cx, callee, thisv, args, res)) {
5050 return false;
5051 }
5052 }
5053 }
5054
5055 return true;
5056 }
5057
5058 static bool OptimizeArrayIteration(JSObject* obj, JSContext* cx) {
5059 // Optimize spread call by skipping spread operation when following
5060 // conditions are met:
5061 // * the argument is an array
5062 // * the array has no hole
5063 // * array[@@iterator] is not modified
5064 // * the array's prototype is Array.prototype
5065 // * Array.prototype[@@iterator] is not modified
5066 // * %ArrayIteratorPrototype%.next is not modified
5067 // * %ArrayIteratorPrototype%.return is not defined
5068 // * return is nowhere on the proto chain
5069 return IsArrayWithDefaultIterator<MustBePacked::Yes>(obj, cx);
5070 }
5071
5072 static bool OptimizeArgumentsSpreadCall(JSContext* cx, HandleObject obj,
5073 MutableHandleValue result) {
5074 MOZ_ASSERT(result.isUndefined());
5075
5076 // Optimize spread call by skipping the spread operation when the following
5077 // conditions are met:
5078 // * the argument is an arguments object
5079 // * the arguments object has no deleted elements
5080 // * arguments.length is not overridden
5081 // * arguments[@@iterator] is not overridden
5082 // * the arguments object belongs to the current realm (affects which
5083 // %ArrayIteratorPrototype% is used)
5084 // * %ArrayIteratorPrototype%.next is not modified
5085
5086 if (!obj->is<ArgumentsObject>()) {
5087 return true;
5088 }
5089
5090 Handle<ArgumentsObject*> args = obj.as<ArgumentsObject>();
5091 if (args->hasOverriddenElement() || args->hasOverriddenLength() ||
5092 args->hasOverriddenIterator()) {
5093 return true;
5094 }
5095 if (cx->realm() != args->realm()) {
5096 return true;
5097 }
5098
5099 if (!HasOptimizableArrayIteratorPrototype(cx)) {
5100 return true;
5101 }
5102
5103 auto* array = ArrayFromArgumentsObject(cx, args);
5104 if (!array) {
5105 return false;
5106 }
5107
5108 result.setObject(*array);
5109 return true;
5110 }
5111
5112 bool js::OptimizeSpreadCall(JSContext* cx, HandleValue arg,
5113 MutableHandleValue result) {
5114 // This function returns |undefined| if the spread operation can't be
5115 // optimized.
5116 result.setUndefined();
5117
5118 if (!arg.isObject()) {
5119 return true;
5120 }
5121
5122 RootedObject obj(cx, &arg.toObject());
5123 if (OptimizeArrayIteration(obj, cx)) {
5124 result.setObject(*obj);
5125 return true;
5126 }
5127
5128 if (!OptimizeArgumentsSpreadCall(cx, obj, result)) {
5129 return false;
5130 }
5131 if (result.isObject()) {
5132 return true;
5133 }
5134
5135 MOZ_ASSERT(result.isUndefined());
5136 return true;
5137 }
5138
5139 bool js::OptimizeGetIterator(const Value& arg, JSContext* cx) {
5140 if (!arg.isObject()) {
5141 return false;
5142 }
5143 return OptimizeArrayIteration(&arg.toObject(), cx);
5144 }
5145
5146 ArrayObject* js::ArrayFromArgumentsObject(JSContext* cx,
5147 Handle<ArgumentsObject*> args) {
5148 MOZ_ASSERT(!args->hasOverriddenLength());
5149 MOZ_ASSERT(!args->hasOverriddenElement());
5150
5151 uint32_t length = args->initialLength();
5152 auto* array = NewDenseFullyAllocatedArray(cx, length);
5153 if (!array) {
5154 return nullptr;
5155 }
5156 array->setDenseInitializedLength(length);
5157
5158 for (uint32_t index = 0; index < length; index++) {
5159 const Value& v = args->element(index);
5160 array->initDenseElement(index, v);
5161 }
5162
5163 return array;
5164 }
5165
5166 JSObject* js::NewObjectOperation(JSContext* cx, HandleScript script,
5167 const jsbytecode* pc) {
5168 if (JSOp(*pc) == JSOp::NewObject) {
5169 Rooted<SharedShape*> shape(cx, script->getShape(pc));
5170 return PlainObject::createWithShape(cx, shape);
5171 }
5172
5173 MOZ_ASSERT(JSOp(*pc) == JSOp::NewInit);
5174 uint8_t propCount = GET_UINT8(pc);
5175 if (propCount > 0) {
5176 gc::AllocKind allocKind = gc::GetGCObjectKind(propCount);
5177 return NewPlainObjectWithAllocKind(cx, allocKind);
5178 }
5179 return NewPlainObject(cx);
5180 }
5181
5182 JSObject* js::NewPlainObjectBaselineFallback(JSContext* cx,
5183 Handle<SharedShape*> shape,
5184 gc::AllocKind allocKind,
5185 gc::AllocSite* site) {
5186 MOZ_ASSERT(shape->getObjectClass() == &PlainObject::class_);
5187
5188 mozilla::Maybe<AutoRealm> ar;
5189 if (cx->realm() != shape->realm()) {
5190 MOZ_ASSERT(cx->compartment() == shape->compartment());
5191 ar.emplace(cx, shape);
5192 }
5193
5194 gc::Heap initialHeap = site->initialHeap();
5195 return NativeObject::create<PlainObject>(cx, allocKind, initialHeap, shape,
5196 site);
5197 }
5198
5199 JSObject* js::NewPlainObjectOptimizedFallback(JSContext* cx,
5200 Handle<SharedShape*> shape,
5201 gc::AllocKind allocKind,
5202 gc::Heap initialHeap) {
5203 MOZ_ASSERT(shape->getObjectClass() == &PlainObject::class_);
5204
5205 mozilla::Maybe<AutoRealm> ar;
5206 if (cx->realm() != shape->realm()) {
5207 MOZ_ASSERT(cx->compartment() == shape->compartment());
5208 ar.emplace(cx, shape);
5209 }
5210
5211 gc::AllocSite* site = cx->zone()->optimizedAllocSite();
5212 return NativeObject::create<PlainObject>(cx, allocKind, initialHeap, shape,
5213 site);
5214 }
5215
5216 ArrayObject* js::NewArrayOperation(
5217 JSContext* cx, uint32_t length,
5218 NewObjectKind newKind /* = GenericObject */) {
5219 return NewDenseFullyAllocatedArray(cx, length, newKind);
5220 }
5221
5222 ArrayObject* js::NewArrayObjectBaselineFallback(JSContext* cx, uint32_t length,
5223 gc::AllocKind allocKind,
5224 gc::AllocSite* site) {
5225 NewObjectKind newKind =
5226 site->initialHeap() == gc::Heap::Tenured ? TenuredObject : GenericObject;
5227 ArrayObject* array = NewDenseFullyAllocatedArray(cx, length, newKind, site);
5228 // It's important that we allocate an object with the alloc kind we were
5229 // expecting so that a new arena gets allocated if the current arena for that
5230 // kind is full.
5231 MOZ_ASSERT_IF(array && array->isTenured(),
5232 array->asTenured().getAllocKind() == allocKind);
5233 return array;
5234 }
5235
5236 ArrayObject* js::NewArrayObjectOptimizedFallback(JSContext* cx, uint32_t length,
5237 gc::AllocKind allocKind,
5238 NewObjectKind newKind) {
5239 gc::AllocSite* site = cx->zone()->optimizedAllocSite();
5240 ArrayObject* array = NewDenseFullyAllocatedArray(cx, length, newKind, site);
5241 // It's important that we allocate an object with the alloc kind we were
5242 // expecting so that a new arena gets allocated if the current arena for that
5243 // kind is full.
5244 MOZ_ASSERT_IF(array && array->isTenured(),
5245 array->asTenured().getAllocKind() == allocKind);
5246 return array;
5247 }
5248
5249 void js::ReportRuntimeLexicalError(JSContext* cx, unsigned errorNumber,
5250 HandleId id) {
5251 MOZ_ASSERT(errorNumber == JSMSG_UNINITIALIZED_LEXICAL ||
5252 errorNumber == JSMSG_BAD_CONST_ASSIGN);
5253 if (UniqueChars printable =
5254 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsIdentifier)) {
5255 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr, errorNumber,
5256 printable.get());
5257 }
5258 }
5259
5260 void js::ReportRuntimeLexicalError(JSContext* cx, unsigned errorNumber,
5261 Handle<PropertyName*> name) {
5262 RootedId id(cx, NameToId(name));
5263 ReportRuntimeLexicalError(cx, errorNumber, id);
5264 }
5265
5266 void js::ReportRuntimeLexicalError(JSContext* cx, unsigned errorNumber,
5267 HandleScript script, jsbytecode* pc) {
5268 JSOp op = JSOp(*pc);
5269 MOZ_ASSERT(op == JSOp::CheckLexical || op == JSOp::CheckAliasedLexical ||
5270 op == JSOp::ThrowSetConst || op == JSOp::GetImport);
5271
5272 Rooted<PropertyName*> name(cx);
5273 if (IsLocalOp(op)) {
5274 name = FrameSlotName(script, pc)->asPropertyName();
5275 } else if (IsAliasedVarOp(op)) {
5276 name = EnvironmentCoordinateNameSlow(script, pc);
5277 } else {
5278 MOZ_ASSERT(IsAtomOp(op));
5279 name = script->getName(pc);
5280 }
5281
5282 ReportRuntimeLexicalError(cx, errorNumber, name);
5283 }
5284
5285 bool js::ThrowCheckIsObject(JSContext* cx, CheckIsObjectKind kind) {
5286 switch (kind) {
5287 case CheckIsObjectKind::IteratorNext:
5288 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5289 JSMSG_ITER_METHOD_RETURNED_PRIMITIVE, "next");
5290 break;
5291 case CheckIsObjectKind::IteratorReturn:
5292 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5293 JSMSG_ITER_METHOD_RETURNED_PRIMITIVE, "return");
5294 break;
5295 case CheckIsObjectKind::IteratorThrow:
5296 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5297 JSMSG_ITER_METHOD_RETURNED_PRIMITIVE, "throw");
5298 break;
5299 case CheckIsObjectKind::GetIterator:
5300 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5301 JSMSG_GET_ITER_RETURNED_PRIMITIVE);
5302 break;
5303 case CheckIsObjectKind::GetAsyncIterator:
5304 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5305 JSMSG_GET_ASYNC_ITER_RETURNED_PRIMITIVE);
5306 break;
5307 #ifdef ENABLE_DECORATORS
5308 case CheckIsObjectKind::DecoratorReturn:
5309 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5310 JSMSG_DECORATOR_INVALID_RETURN_TYPE);
5311 break;
5312 #endif
5313 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
5314 case CheckIsObjectKind::Disposable:
5315 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5316 JSMSG_DISPOSABLE_NOT_OBJ);
5317 break;
5318 #endif
5319 default:
5320 MOZ_CRASH("Unknown kind");
5321 }
5322 return false;
5323 }
5324
5325 bool js::ThrowUninitializedThis(JSContext* cx) {
5326 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5327 JSMSG_UNINITIALIZED_THIS);
5328 return false;
5329 }
5330
5331 bool js::ThrowInitializedThis(JSContext* cx) {
5332 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_REINIT_THIS);
5333 return false;
5334 }
5335
5336 bool js::ThrowObjectCoercible(JSContext* cx, HandleValue value) {
5337 MOZ_ASSERT(value.isNullOrUndefined());
5338 ReportIsNullOrUndefinedForPropertyAccess(cx, value, JSDVG_SEARCH_STACK);
5339 return false;
5340 }
5341
5342 bool js::SetPropertySuper(JSContext* cx, HandleValue lval, HandleValue receiver,
5343 Handle<PropertyName*> name, HandleValue rval,
5344 bool strict) {
5345 MOZ_ASSERT(lval.isObjectOrNull());
5346
5347 RootedObject obj(cx, ToObjectFromStackForPropertyAccess(
5348 cx, lval, JSDVG_SEARCH_STACK, name));
5349 if (!obj) {
5350 return false;
5351 }
5352
5353 RootedId id(cx, NameToId(name));
5354 return SetObjectElementOperation(cx, obj, id, rval, receiver, strict);
5355 }
5356
5357 bool js::SetElementSuper(JSContext* cx, HandleValue lval, HandleValue receiver,
5358 HandleValue index, HandleValue rval, bool strict) {
5359 MOZ_ASSERT(lval.isObjectOrNull());
5360
5361 RootedObject obj(cx, ToObjectFromStackForPropertyAccess(
5362 cx, lval, JSDVG_SEARCH_STACK, index));
5363 if (!obj) {
5364 return false;
5365 }
5366
5367 return SetObjectElementWithReceiver(cx, obj, index, rval, receiver, strict);
5368 }
5369
5370 bool js::LoadAliasedDebugVar(JSContext* cx, JSObject* env, jsbytecode* pc,
5371 MutableHandleValue result) {
5372 EnvironmentCoordinate ec(pc);
5373
5374 for (unsigned i = ec.hops(); i; i--) {
5375 if (env->is<EnvironmentObject>()) {
5376 env = &env->as<EnvironmentObject>().enclosingEnvironment();
5377 } else {
5378 MOZ_ASSERT(env->is<DebugEnvironmentProxy>());
5379 env = &env->as<DebugEnvironmentProxy>().enclosingEnvironment();
5380 }
5381 }
5382
5383 EnvironmentObject& finalEnv =
5384 env->is<EnvironmentObject>()
5385 ? env->as<EnvironmentObject>()
5386 : env->as<DebugEnvironmentProxy>().environment();
5387
5388 result.set(finalEnv.aliasedBinding(ec));
5389 return true;
5390 }
5391
5392 // https://tc39.es/ecma262/#sec-iteratorclose
5393 bool js::CloseIterOperation(JSContext* cx, HandleObject iter,
5394 CompletionKind kind) {
5395 // Steps 1-2 are implicit.
5396
5397 // Step 3
5398 RootedValue returnMethod(cx);
5399 bool innerResult =
5400 GetProperty(cx, iter, iter, cx->names().return_, &returnMethod);
5401
5402 // Step 4
5403 RootedValue result(cx);
5404 if (innerResult) {
5405 // Step 4b
5406 if (returnMethod.isNullOrUndefined()) {
5407 return true;
5408 }
5409 // Step 4c
5410 if (IsCallable(returnMethod)) {
5411 RootedValue thisVal(cx, ObjectValue(*iter));
5412 innerResult = Call(cx, returnMethod, thisVal, &result);
5413 } else {
5414 innerResult = ReportIsNotFunction(cx, returnMethod);
5415 }
5416 }
5417
5418 // Step 5
5419 if (kind == CompletionKind::Throw) {
5420 // If we close an iterator while unwinding for an exception,
5421 // the initial exception takes priority over any exception thrown
5422 // while closing the iterator.
5423 if (cx->isExceptionPending()) {
5424 cx->clearPendingException();
5425 }
5426 return true;
5427 }
5428
5429 // Step 6
5430 if (!innerResult) {
5431 return false;
5432 }
5433
5434 // Step 7
5435 if (!result.isObject()) {
5436 return ThrowCheckIsObject(cx, CheckIsObjectKind::IteratorReturn);
5437 }
5438
5439 // Step 8
5440 return true;
5441 }