Debian Codegraph @

js/src/vm/EnvironmentObject.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 #include "vm/EnvironmentObject-inl.h"
8
9 #include "mozilla/Maybe.h"
10
11 #include "builtin/Array.h"
12 #include "builtin/ModuleObject.h"
13 #include "js/EnvironmentChain.h" // JS::EnvironmentChain
14 #include "js/Exception.h"
15 #include "js/friend/ErrorMessages.h" // js::GetErrorMessage, JSMSG_*
16 #include "js/friend/StackLimits.h" // js::AutoCheckRecursionLimit
17 #include "js/friend/WindowProxy.h" // js::IsWindow, js::IsWindowProxy
18 #include "js/PropertyAndElement.h" // JS_DefineProperty, JS_DefinePropertyById, JS_HasProperty, JS_HasPropertyById
19 #include "vm/ArgumentsObject.h"
20 #include "vm/BytecodeIterator.h"
21 #include "vm/BytecodeLocation.h"
22 #include "vm/GeneratorObject.h" // js::GetGeneratorObjectForEnvironment
23 #include "vm/GlobalObject.h"
24 #include "vm/JSObject.h"
25 #include "vm/ProxyObject.h"
26 #include "vm/Realm.h"
27 #include "vm/Scope.h"
28 #include "vm/Shape.h"
29 #include "wasm/WasmDebug.h"
30 #include "wasm/WasmDebugFrame.h"
31 #include "wasm/WasmInstance.h"
32
33 #include "gc/Marking-inl.h"
34 #include "gc/StableCellHasher-inl.h"
35 #include "vm/BytecodeIterator-inl.h"
36 #include "vm/Stack-inl.h"
37
38 using namespace js;
39
40 /*****************************************************************************/
41
42 /*
43 * Return a shape representing the static scope containing the variable
44 * accessed by the ALIASEDVAR op at 'pc'.
45 */
46 static SharedShape* EnvironmentCoordinateToEnvironmentShape(JSScript* script,
47 jsbytecode* pc) {
48 MOZ_ASSERT(JOF_OPTYPE(JSOp(*pc)) == JOF_ENVCOORD);
49 ScopeIter si(script->innermostScope(pc));
50 uint32_t hops = EnvironmentCoordinate(pc).hops();
51 while (true) {
52 MOZ_ASSERT(!si.done());
53 if (si.hasSyntacticEnvironment()) {
54 if (!hops) {
55 break;
56 }
57 hops--;
58 }
59 si++;
60 }
61 return si.environmentShape();
62 }
63
64 PropertyName* js::EnvironmentCoordinateNameSlow(JSScript* script,
65 jsbytecode* pc) {
66 SharedShape* shape = EnvironmentCoordinateToEnvironmentShape(script, pc);
67 EnvironmentCoordinate ec(pc);
68
69 SharedShapePropertyIter<NoGC> iter(shape);
70 while (iter->slot() != ec.slot()) {
71 iter++;
72 }
73 jsid id = iter->key();
74
75 /* Beware nameless destructuring formal. */
76 if (!id.isAtom()) {
77 return script->runtimeFromAnyThread()->commonNames->empty_;
78 }
79 return id.toAtom()->asPropertyName();
80 }
81
82 /*****************************************************************************/
83
84 template <typename T>
85 static T* CreateEnvironmentObject(JSContext* cx, Handle<SharedShape*> shape,
86 gc::Heap heap,
87 gc::AllocSite* site = nullptr) {
88 static_assert(std::is_base_of_v<EnvironmentObject, T>,
89 "T must be an EnvironmentObject");
90
91 // Environment objects do not have finalizers.
92 gc::AllocKind allocKind = gc::GetGCObjectKind(shape->numFixedSlots());
93 MOZ_ASSERT(gc::GetObjectFinalizeKind(&T::class_) == gc::FinalizeKind::None);
94 MOZ_ASSERT(!gc::IsFinalizedKind(allocKind));
95
96 return NativeObject::create<T>(cx, allocKind, heap, shape, site);
97 }
98
99 // Helper function for simple environment objects that don't need the overloads
100 // above.
101 template <typename T>
102 static T* CreateEnvironmentObject(JSContext* cx, Handle<SharedShape*> shape,
103 NewObjectKind newKind = GenericObject) {
104 gc::Heap heap = GetInitialHeap(newKind, &T::class_);
105 return CreateEnvironmentObject<T>(cx, shape, heap);
106 }
107
108 CallObject* CallObject::createWithShape(JSContext* cx,
109 Handle<SharedShape*> shape,
110 gc::Heap heap) {
111 return CreateEnvironmentObject<CallObject>(cx, shape, heap);
112 }
113
114 /*
115 * Create a CallObject for a JSScript that is not initialized to any particular
116 * callsite. This object can either be initialized (with an enclosing scope and
117 * callee) or used as a template for jit compilation.
118 */
119 CallObject* CallObject::create(JSContext* cx, HandleScript script,
120 HandleObject enclosing, gc::Heap heap,
121 gc::AllocSite* site) {
122 Rooted<SharedShape*> shape(
123 cx, script->bodyScope()->as<FunctionScope>().environmentShape());
124 MOZ_ASSERT(shape->getObjectClass() == &class_);
125
126 // The JITs assume the result is nursery allocated unless we collected the
127 // nursery, so don't change |heap| here.
128
129 auto* callObj = CreateEnvironmentObject<CallObject>(cx, shape, heap, site);
130 if (!callObj) {
131 return nullptr;
132 }
133
134 if (enclosing) {
135 callObj->initEnclosingEnvironment(enclosing);
136 }
137
138 return callObj;
139 }
140
141 CallObject* CallObject::createTemplateObject(JSContext* cx, HandleScript script,
142 HandleObject enclosing) {
143 return create(cx, script, enclosing, gc::Heap::Tenured);
144 }
145
146 CallObject* CallObject::createForFrame(JSContext* cx, AbstractFramePtr frame,
147 gc::AllocSite* site) {
148 MOZ_ASSERT(frame.isFunctionFrame());
149 cx->check(frame);
150
151 RootedObject envChain(cx, frame.environmentChain());
152 RootedFunction callee(cx, frame.callee());
153 RootedScript script(cx, callee->nonLazyScript());
154 gc::Heap heap = site ? site->initialHeap() : gc::Heap::Default;
155
156 CallObject* callobj = create(cx, script, envChain, heap, site);
157 if (!callobj) {
158 return nullptr;
159 }
160
161 callobj->initFixedSlot(CALLEE_SLOT, ObjectValue(*callee));
162
163 return callobj;
164 }
165
166 template <class EnvT>
167 EnvT* FindEnclosingEnv(JSObject* env) {
168 for (;;) {
169 if (env->is<EnvT>()) {
170 break;
171 } else if (env->is<EnvironmentObject>()) {
172 env = &env->as<EnvironmentObject>().enclosingEnvironment();
173 } else if (env->is<DebugEnvironmentProxy>()) {
174 EnvironmentObject& unwrapped =
175 env->as<DebugEnvironmentProxy>().environment();
176 if (unwrapped.is<EnvT>()) {
177 env = &unwrapped;
178 break;
179 }
180 env = &env->as<DebugEnvironmentProxy>().enclosingEnvironment();
181 } else {
182 MOZ_ASSERT(env->is<GlobalObject>());
183 return nullptr;
184 }
185 }
186 return &env->as<EnvT>();
187 }
188
189 CallObject* CallObject::find(JSObject* env) {
190 return FindEnclosingEnv<CallObject>(env);
191 }
192
193 ModuleEnvironmentObject* ModuleEnvironmentObject::find(JSObject* env) {
194 return FindEnclosingEnv<ModuleEnvironmentObject>(env);
195 }
196
197 CallObject* CallObject::createHollowForDebug(JSContext* cx,
198 HandleFunction callee) {
199 MOZ_ASSERT(!callee->needsCallObject());
200
201 RootedScript script(cx, callee->nonLazyScript());
202 Rooted<FunctionScope*> scope(cx, &script->bodyScope()->as<FunctionScope>());
203 Rooted<SharedShape*> shape(cx, EmptyEnvironmentShape<CallObject>(cx));
204 if (!shape) {
205 return nullptr;
206 }
207 Rooted<CallObject*> callobj(cx, createWithShape(cx, shape));
208 if (!callobj) {
209 return nullptr;
210 }
211
212 // This environment's enclosing link is never used: the
213 // DebugEnvironmentProxy that refers to this scope carries its own
214 // enclosing link, which is what Debugger uses to construct the tree of
215 // Debugger.Environment objects.
216 callobj->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
217 callobj->initFixedSlot(CALLEE_SLOT, ObjectValue(*callee));
218
219 RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
220 RootedId id(cx);
221 for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
222 id = NameToId(bi.name()->asPropertyName());
223 if (!SetProperty(cx, callobj, id, optimizedOut)) {
224 return nullptr;
225 }
226 }
227
228 return callobj;
229 }
230
231 const JSClass CallObject::class_ = {
232 "Call",
233 JSCLASS_HAS_RESERVED_SLOTS(CallObject::RESERVED_SLOTS),
234 };
235
236 /*****************************************************************************/
237
238 /* static */
239 VarEnvironmentObject* VarEnvironmentObject::createInternal(
240 JSContext* cx, Handle<SharedShape*> shape, HandleObject enclosing,
241 gc::Heap heap) {
242 MOZ_ASSERT(shape->getObjectClass() == &class_);
243
244 auto* env = CreateEnvironmentObject<VarEnvironmentObject>(cx, shape, heap);
245 if (!env) {
246 return nullptr;
247 }
248
249 MOZ_ASSERT(!env->inDictionaryMode());
250
251 if (enclosing) {
252 env->initEnclosingEnvironment(enclosing);
253 }
254
255 return env;
256 }
257
258 /* static */
259 VarEnvironmentObject* VarEnvironmentObject::create(JSContext* cx,
260 Handle<Scope*> scope,
261 HandleObject enclosing,
262 gc::Heap heap) {
263 MOZ_ASSERT(scope->is<EvalScope>() || scope->is<VarScope>());
264
265 Rooted<SharedShape*> shape(cx, scope->environmentShape());
266 auto* env = createInternal(cx, shape, enclosing, heap);
267 if (!env) {
268 return nullptr;
269 }
270 env->initScope(scope);
271 return env;
272 }
273
274 /* static */
275 VarEnvironmentObject* VarEnvironmentObject::createForFrame(
276 JSContext* cx, Handle<Scope*> scope, AbstractFramePtr frame) {
277 #ifdef DEBUG
278 if (frame.isEvalFrame()) {
279 MOZ_ASSERT(scope->is<EvalScope>() && scope == frame.script()->bodyScope());
280 MOZ_ASSERT_IF(frame.isInterpreterFrame(),
281 cx->interpreterFrame() == frame.asInterpreterFrame());
282 MOZ_ASSERT_IF(frame.isInterpreterFrame(),
283 cx->interpreterRegs().pc == frame.script()->code());
284 } else {
285 MOZ_ASSERT(frame.environmentChain());
286 MOZ_ASSERT_IF(
287 frame.callee()->needsCallObject(),
288 &frame.environmentChain()->as<CallObject>().callee() == frame.callee());
289 }
290 #endif
291
292 RootedObject envChain(cx, frame.environmentChain());
293 return create(cx, scope, envChain, gc::Heap::Default);
294 }
295
296 /* static */
297 VarEnvironmentObject* VarEnvironmentObject::createHollowForDebug(
298 JSContext* cx, Handle<Scope*> scope) {
299 MOZ_ASSERT(scope->is<VarScope>() || scope->kind() == ScopeKind::StrictEval);
300 MOZ_ASSERT(!scope->hasEnvironment());
301
302 Rooted<SharedShape*> shape(cx,
303 EmptyEnvironmentShape<VarEnvironmentObject>(cx));
304 if (!shape) {
305 return nullptr;
306 }
307
308 // This environment's enclosing link is never used: the
309 // DebugEnvironmentProxy that refers to this scope carries its own
310 // enclosing link, which is what Debugger uses to construct the tree of
311 // Debugger.Environment objects.
312 RootedObject enclosingEnv(cx, &cx->global()->lexicalEnvironment());
313 Rooted<VarEnvironmentObject*> env(
314 cx, createInternal(cx, shape, enclosingEnv, gc::Heap::Default));
315 if (!env) {
316 return nullptr;
317 }
318
319 RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
320 RootedId id(cx);
321 for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
322 id = NameToId(bi.name()->asPropertyName());
323 if (!SetProperty(cx, env, id, optimizedOut)) {
324 return nullptr;
325 }
326 }
327
328 env->initScope(scope);
329 return env;
330 }
331
332 /* static */
333 VarEnvironmentObject* VarEnvironmentObject::createTemplateObject(
334 JSContext* cx, Handle<VarScope*> scope) {
335 return create(cx, scope, nullptr, gc::Heap::Tenured);
336 }
337
338 /* static */
339 VarEnvironmentObject* VarEnvironmentObject::createWithoutEnclosing(
340 JSContext* cx, Handle<VarScope*> scope) {
341 return create(cx, scope, nullptr, gc::Heap::Default);
342 }
343
344 const JSClass VarEnvironmentObject::class_ = {
345 "Var",
346 JSCLASS_HAS_RESERVED_SLOTS(VarEnvironmentObject::RESERVED_SLOTS),
347 };
348
349 /*****************************************************************************/
350
351 const ObjectOps ModuleEnvironmentObject::objectOps_ = {
352 ModuleEnvironmentObject::lookupProperty, // lookupProperty
353 nullptr, // defineProperty
354 ModuleEnvironmentObject::hasProperty, // hasProperty
355 ModuleEnvironmentObject::getProperty, // getProperty
356 ModuleEnvironmentObject::setProperty, // setProperty
357 ModuleEnvironmentObject::
358 getOwnPropertyDescriptor, // getOwnPropertyDescriptor
359 ModuleEnvironmentObject::deleteProperty, // deleteProperty
360 nullptr, // getElements
361 nullptr, // funToString
362 };
363
364 const JSClassOps ModuleEnvironmentObject::classOps_ = {
365 nullptr, // addProperty
366 nullptr, // delProperty
367 nullptr, // enumerate
368 ModuleEnvironmentObject::newEnumerate, // newEnumerate
369 nullptr, // resolve
370 nullptr, // mayResolve
371 nullptr, // finalize
372 nullptr, // call
373 nullptr, // construct
374 nullptr, // trace
375 };
376
377 const JSClass ModuleEnvironmentObject::class_ = {
378 "ModuleEnvironmentObject",
379 JSCLASS_HAS_RESERVED_SLOTS(ModuleEnvironmentObject::RESERVED_SLOTS),
380 &ModuleEnvironmentObject::classOps_,
381 JS_NULL_CLASS_SPEC,
382 JS_NULL_CLASS_EXT,
383 &ModuleEnvironmentObject::objectOps_,
384 };
385
386 /* static */
387 ModuleEnvironmentObject* ModuleEnvironmentObject::create(
388 JSContext* cx, Handle<ModuleObject*> module) {
389 RootedScript script(cx, module->script());
390 Rooted<SharedShape*> shape(
391 cx, script->bodyScope()->as<ModuleScope>().environmentShape());
392 MOZ_ASSERT(shape->getObjectClass() == &class_);
393
394 Rooted<ModuleEnvironmentObject*> env(
395 cx, CreateEnvironmentObject<ModuleEnvironmentObject>(cx, shape,
396 TenuredObject));
397 if (!env) {
398 return nullptr;
399 }
400
401 env->initReservedSlot(MODULE_SLOT, ObjectValue(*module));
402
403 // Initialize this early so that we can manipulate the env object without
404 // causing assertions.
405 env->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
406
407 // Initialize all lexical bindings and imports as uninitialized. Imports
408 // get uninitialized because they have a special TDZ for cyclic imports.
409 for (BindingIter bi(script); bi; bi++) {
410 BindingLocation loc = bi.location();
411 if (loc.kind() == BindingLocation::Kind::Environment &&
412 BindingKindIsLexical(bi.kind())) {
413 env->initSlot(loc.slot(), MagicValue(JS_UNINITIALIZED_LEXICAL));
414 }
415 }
416
417 // It is not be possible to add or remove bindings from a module environment
418 // after this point as module code is always strict.
419 #ifdef DEBUG
420 for (ShapePropertyIter<NoGC> iter(env->shape()); !iter.done(); iter++) {
421 MOZ_ASSERT(!iter->configurable());
422 }
423 MOZ_ASSERT(env->hasFlag(ObjectFlag::NotExtensible));
424 MOZ_ASSERT(!env->inDictionaryMode());
425 #endif
426
427 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
428 env->initSlot(ModuleEnvironmentObject::DISPOSABLE_RESOURCE_STACK_SLOT,
429 UndefinedValue());
430 #endif
431
432 return env;
433 }
434
435 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
436 static ArrayObject* initialiseAndSetDisposeCapabilityHelper(
437 JSContext* cx, JS::Handle<EnvironmentObject*> env, uint32_t slot) {
438 JS::Value slotData = env->getReservedSlot(slot);
439 ArrayObject* disposablesList = nullptr;
440 if (slotData.isUndefined()) {
441 disposablesList = NewDenseEmptyArray(cx);
442 if (!disposablesList) {
443 return nullptr;
444 }
445 env->setReservedSlot(slot, ObjectValue(*disposablesList));
446 } else {
447 disposablesList = &slotData.toObject().as<ArrayObject>();
448 }
449 return disposablesList;
450 }
451
452 ArrayObject* DisposableEnvironmentObject::getOrCreateDisposeCapability(
453 JSContext* cx) {
454 Rooted<DisposableEnvironmentObject*> env(cx, this);
455 return initialiseAndSetDisposeCapabilityHelper(
456 cx, env, DISPOSABLE_RESOURCE_STACK_SLOT);
457 }
458
459 // TODO: The get & clear disposables function can be merged. (bug 1907736)
460 JS::Value DisposableEnvironmentObject::getDisposables() {
461 return getReservedSlot(DISPOSABLE_RESOURCE_STACK_SLOT);
462 }
463
464 void DisposableEnvironmentObject::clearDisposables() {
465 setReservedSlot(DISPOSABLE_RESOURCE_STACK_SLOT, UndefinedValue());
466 }
467 #endif
468
469 /* static */
470 ModuleEnvironmentObject* ModuleEnvironmentObject::createSynthetic(
471 JSContext* cx, Handle<ModuleObject*> module) {
472 Rooted<SharedShape*> shape(cx,
473 CreateEnvironmentShapeForSyntheticModule(
474 cx, &class_, JSSLOT_FREE(&class_), module));
475 if (!shape) {
476 return nullptr;
477 }
478
479 MOZ_ASSERT(shape->getObjectClass() == &class_);
480
481 Rooted<ModuleEnvironmentObject*> env(
482 cx, CreateEnvironmentObject<ModuleEnvironmentObject>(cx, shape,
483 TenuredObject));
484 if (!env) {
485 return nullptr;
486 }
487
488 env->initReservedSlot(MODULE_SLOT, ObjectValue(*module));
489
490 // Initialize this early so that we can manipulate the env object without
491 // causing assertions.
492 env->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
493
494 // It is not be possible to add or remove bindings from a module environment
495 // after this point as module code is always strict.
496 #ifdef DEBUG
497 for (ShapePropertyIter<NoGC> iter(env->shape()); !iter.done(); iter++) {
498 MOZ_ASSERT(!iter->configurable());
499 }
500 MOZ_ASSERT(env->hasFlag(ObjectFlag::NotExtensible));
501 MOZ_ASSERT(!env->inDictionaryMode());
502 #endif
503
504 return env;
505 }
506
507 ModuleObject& ModuleEnvironmentObject::module() const {
508 return getReservedSlot(MODULE_SLOT).toObject().as<ModuleObject>();
509 }
510
511 IndirectBindingMap& ModuleEnvironmentObject::importBindings() const {
512 return module().importBindings();
513 }
514
515 bool ModuleEnvironmentObject::createImportBinding(JSContext* cx,
516 Handle<JSAtom*> importName,
517 Handle<ModuleObject*> module,
518 Handle<JSAtom*> localName) {
519 RootedId importNameId(cx, AtomToId(importName));
520 RootedId localNameId(cx, AtomToId(localName));
521 Rooted<ModuleEnvironmentObject*> env(cx, &module->initialEnvironment());
522 if (!importBindings().put(cx, importNameId, env, localNameId)) {
523 return false;
524 }
525
526 return true;
527 }
528
529 bool ModuleEnvironmentObject::hasImportBinding(Handle<PropertyName*> name) {
530 return importBindings().has(NameToId(name));
531 }
532
533 bool ModuleEnvironmentObject::lookupImport(
534 jsid name, ModuleEnvironmentObject** envOut,
535 mozilla::Maybe<PropertyInfo>* propOut) {
536 return importBindings().lookup(name, envOut, propOut);
537 }
538
539 /* static */
540 bool ModuleEnvironmentObject::lookupProperty(JSContext* cx, HandleObject obj,
541 HandleId id,
542 MutableHandleObject objp,
543 PropertyResult* propp) {
544 const IndirectBindingMap& bindings =
545 obj->as<ModuleEnvironmentObject>().importBindings();
546 mozilla::Maybe<PropertyInfo> propInfo;
547 ModuleEnvironmentObject* env;
548 if (bindings.lookup(id, &env, &propInfo)) {
549 objp.set(env);
550 propp->setNativeProperty(*propInfo);
551 return true;
552 }
553
554 Rooted<NativeObject*> target(cx, &obj->as<NativeObject>());
555 if (!NativeLookupOwnProperty<CanGC>(cx, target, id, propp)) {
556 return false;
557 }
558
559 objp.set(obj);
560 return true;
561 }
562
563 /* static */
564 bool ModuleEnvironmentObject::hasProperty(JSContext* cx, HandleObject obj,
565 HandleId id, bool* foundp) {
566 if (obj->as<ModuleEnvironmentObject>().importBindings().has(id)) {
567 *foundp = true;
568 return true;
569 }
570
571 Rooted<NativeObject*> self(cx, &obj->as<NativeObject>());
572 return NativeHasProperty(cx, self, id, foundp);
573 }
574
575 /* static */
576 bool ModuleEnvironmentObject::getProperty(JSContext* cx, HandleObject obj,
577 HandleValue receiver, HandleId id,
578 MutableHandleValue vp) {
579 const IndirectBindingMap& bindings =
580 obj->as<ModuleEnvironmentObject>().importBindings();
581 mozilla::Maybe<PropertyInfo> prop;
582 ModuleEnvironmentObject* env;
583 if (bindings.lookup(id, &env, &prop)) {
584 vp.set(env->getSlot(prop->slot()));
585 return true;
586 }
587
588 Rooted<NativeObject*> self(cx, &obj->as<NativeObject>());
589 return NativeGetProperty(cx, self, receiver, id, vp);
590 }
591
592 /* static */
593 bool ModuleEnvironmentObject::setProperty(JSContext* cx, HandleObject obj,
594 HandleId id, HandleValue v,
595 HandleValue receiver,
596 JS::ObjectOpResult& result) {
597 Rooted<ModuleEnvironmentObject*> self(cx,
598 &obj->as<ModuleEnvironmentObject>());
599 if (self->importBindings().has(id)) {
600 return result.failReadOnly();
601 }
602
603 return NativeSetProperty<Qualified>(cx, self, id, v, receiver, result);
604 }
605
606 /* static */
607 bool ModuleEnvironmentObject::getOwnPropertyDescriptor(
608 JSContext* cx, HandleObject obj, HandleId id,
609 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
610 const IndirectBindingMap& bindings =
611 obj->as<ModuleEnvironmentObject>().importBindings();
612 mozilla::Maybe<PropertyInfo> prop;
613 ModuleEnvironmentObject* env;
614 if (bindings.lookup(id, &env, &prop)) {
615 desc.set(mozilla::Some(PropertyDescriptor::Data(
616 env->getSlot(prop->slot()),
617 {JS::PropertyAttribute::Enumerable, JS::PropertyAttribute::Writable})));
618 return true;
619 }
620
621 Rooted<NativeObject*> self(cx, &obj->as<NativeObject>());
622 return NativeGetOwnPropertyDescriptor(cx, self, id, desc);
623 }
624
625 /* static */
626 bool ModuleEnvironmentObject::deleteProperty(JSContext* cx, HandleObject obj,
627 HandleId id,
628 ObjectOpResult& result) {
629 return result.failCantDelete();
630 }
631
632 /* static */
633 bool ModuleEnvironmentObject::newEnumerate(JSContext* cx, HandleObject obj,
634 MutableHandleIdVector properties,
635 bool enumerableOnly) {
636 Rooted<ModuleEnvironmentObject*> self(cx,
637 &obj->as<ModuleEnvironmentObject>());
638 const IndirectBindingMap& bs(self->importBindings());
639
640 MOZ_ASSERT(properties.length() == 0);
641 size_t count = bs.count() + self->slotSpan() - RESERVED_SLOTS;
642 if (!properties.reserve(count)) {
643 ReportOutOfMemory(cx);
644 return false;
645 }
646
647 bs.forEachExportedName([&](jsid name) { properties.infallibleAppend(name); });
648
649 for (ShapePropertyIter<NoGC> iter(self->shape()); !iter.done(); iter++) {
650 properties.infallibleAppend(iter->key());
651 }
652
653 MOZ_ASSERT(properties.length() == count);
654 return true;
655 }
656
657 /*****************************************************************************/
658
659 const JSClass WasmInstanceEnvironmentObject::class_ = {
660 "WasmInstance",
661 JSCLASS_HAS_RESERVED_SLOTS(WasmInstanceEnvironmentObject::RESERVED_SLOTS),
662 };
663
664 /* static */
665 WasmInstanceEnvironmentObject*
666 WasmInstanceEnvironmentObject::createHollowForDebug(
667 JSContext* cx, Handle<WasmInstanceScope*> scope) {
668 Rooted<SharedShape*> shape(
669 cx, EmptyEnvironmentShape<WasmInstanceEnvironmentObject>(cx));
670 if (!shape) {
671 return nullptr;
672 }
673
674 auto* env = CreateEnvironmentObject<WasmInstanceEnvironmentObject>(cx, shape);
675 if (!env) {
676 return nullptr;
677 }
678
679 env->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
680 env->initReservedSlot(SCOPE_SLOT, PrivateGCThingValue(scope));
681
682 return env;
683 }
684
685 /*****************************************************************************/
686
687 const JSClass WasmFunctionCallObject::class_ = {
688 "WasmCall",
689 JSCLASS_HAS_RESERVED_SLOTS(WasmFunctionCallObject::RESERVED_SLOTS),
690 };
691
692 /* static */
693 WasmFunctionCallObject* WasmFunctionCallObject::createHollowForDebug(
694 JSContext* cx, HandleObject enclosing, Handle<WasmFunctionScope*> scope) {
695 Rooted<SharedShape*> shape(cx,
696 EmptyEnvironmentShape<WasmFunctionCallObject>(cx));
697 if (!shape) {
698 return nullptr;
699 }
700
701 auto* callobj = CreateEnvironmentObject<WasmFunctionCallObject>(cx, shape);
702 if (!callobj) {
703 return nullptr;
704 }
705
706 callobj->initEnclosingEnvironment(enclosing);
707 callobj->initReservedSlot(SCOPE_SLOT, PrivateGCThingValue(scope));
708
709 return callobj;
710 }
711
712 /*****************************************************************************/
713
714 JSObject* js::GetThisObject(JSObject* obj) {
715 // Use the WindowProxy if the global is a Window, as Window must never be
716 // exposed to script.
717 if (obj->is<GlobalObject>()) {
718 return ToWindowProxyIfWindow(obj);
719 }
720
721 // We should not expose any environments except NSVOs to script. The NSVO is
722 // pretending to be the global object in this case.
723 MOZ_ASSERT_IF(obj->is<EnvironmentObject>(),
724 obj->is<NonSyntacticVariablesObject>());
725
726 return obj;
727 }
728
729 WithEnvironmentObject* WithEnvironmentObject::create(
730 JSContext* cx, HandleObject object, HandleObject enclosing,
731 Handle<WithScope*> scope, JS::SupportUnscopables supportUnscopables) {
732 Rooted<SharedShape*> shape(cx,
733 EmptyEnvironmentShape<WithEnvironmentObject>(cx));
734 if (!shape) {
735 return nullptr;
736 }
737
738 auto* obj = CreateEnvironmentObject<WithEnvironmentObject>(cx, shape);
739 if (!obj) {
740 return nullptr;
741 }
742
743 JSObject* thisObj = GetThisObject(object);
744
745 obj->initEnclosingEnvironment(enclosing);
746 obj->initReservedSlot(OBJECT_SLOT, ObjectValue(*object));
747 obj->initReservedSlot(THIS_SLOT, ObjectValue(*thisObj));
748 if (scope) {
749 MOZ_ASSERT(supportUnscopables == JS::SupportUnscopables::Yes,
750 "with-statements must support Symbol.unscopables");
751 obj->initReservedSlot(SCOPE_OR_SUPPORT_UNSCOPABLES_SLOT,
752 PrivateGCThingValue(scope));
753 } else {
754 Value v = BooleanValue(supportUnscopables == JS::SupportUnscopables::Yes);
755 obj->initReservedSlot(SCOPE_OR_SUPPORT_UNSCOPABLES_SLOT, v);
756 }
757
758 return obj;
759 }
760
761 WithEnvironmentObject* WithEnvironmentObject::createNonSyntactic(
762 JSContext* cx, HandleObject object, HandleObject enclosing,
763 JS::SupportUnscopables supportUnscopables) {
764 return create(cx, object, enclosing, nullptr, supportUnscopables);
765 }
766
767 static inline bool IsUnscopableDotName(JSContext* cx, HandleId id) {
768 return id.isAtom(cx->names().dot_this_) ||
769 id.isAtom(cx->names().dot_newTarget_);
770 }
771
772 #ifdef DEBUG
773 static bool IsInternalDotName(JSContext* cx, HandleId id) {
774 return id.isAtom(cx->names().dot_this_) ||
775 id.isAtom(cx->names().dot_generator_) ||
776 id.isAtom(cx->names().dot_initializers_) ||
777 id.isAtom(cx->names().dot_fieldKeys_) ||
778 id.isAtom(cx->names().dot_staticInitializers_) ||
779 id.isAtom(cx->names().dot_staticFieldKeys_) ||
780 id.isAtom(cx->names().dot_args_) ||
781 id.isAtom(cx->names().dot_newTarget_) ||
782 id.isAtom(cx->names().star_namespace_star_);
783 }
784 #endif
785
786 /* Implements ES6 8.1.1.2.1 HasBinding steps 7-9. */
787 static bool CheckUnscopables(JSContext* cx, HandleObject obj, HandleId id,
788 bool* scopable) {
789 RootedId unscopablesId(
790 cx, PropertyKey::Symbol(cx->wellKnownSymbols().unscopables));
791 RootedValue v(cx);
792 if (!GetProperty(cx, obj, obj, unscopablesId, &v)) {
793 return false;
794 }
795 if (v.isObject()) {
796 RootedObject unscopablesObj(cx, &v.toObject());
797 if (!GetProperty(cx, unscopablesObj, unscopablesObj, id, &v)) {
798 return false;
799 }
800 *scopable = !ToBoolean(v);
801 } else {
802 *scopable = true;
803 }
804 return true;
805 }
806
807 static bool with_LookupProperty(JSContext* cx, HandleObject obj, HandleId id,
808 MutableHandleObject objp,
809 PropertyResult* propp) {
810 // SpiderMonkey-specific: consider the internal '.this' and '.newTarget' names
811 // to be unscopable.
812 if (IsUnscopableDotName(cx, id)) {
813 objp.set(nullptr);
814 propp->setNotFound();
815 return true;
816 }
817
818 // Other internal dot-names shouldn't even end up in with-environments.
819 MOZ_ASSERT(!IsInternalDotName(cx, id));
820
821 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
822 if (!LookupProperty(cx, actual, id, objp, propp)) {
823 return false;
824 }
825
826 if (propp->isFound()) {
827 bool scopable = true;
828 if (obj->as<WithEnvironmentObject>().supportUnscopables() &&
829 !CheckUnscopables(cx, actual, id, &scopable)) {
830 return false;
831 }
832 if (!scopable) {
833 objp.set(nullptr);
834 propp->setNotFound();
835 }
836 }
837 return true;
838 }
839
840 static bool with_DefineProperty(JSContext* cx, HandleObject obj, HandleId id,
841 Handle<PropertyDescriptor> desc,
842 ObjectOpResult& result) {
843 MOZ_ASSERT(!IsInternalDotName(cx, id));
844 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
845 return DefineProperty(cx, actual, id, desc, result);
846 }
847
848 static bool with_HasProperty(JSContext* cx, HandleObject obj, HandleId id,
849 bool* foundp) {
850 MOZ_ASSERT(!IsInternalDotName(cx, id));
851 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
852
853 // ES 8.1.1.2.1 step 3-5.
854 if (!HasProperty(cx, actual, id, foundp)) {
855 return false;
856 }
857 if (!*foundp || !obj->as<WithEnvironmentObject>().supportUnscopables()) {
858 return true;
859 }
860
861 // Steps 7-10. (Step 6 is a no-op.)
862 return CheckUnscopables(cx, actual, id, foundp);
863 }
864
865 static bool with_GetProperty(JSContext* cx, HandleObject obj,
866 HandleValue receiver, HandleId id,
867 MutableHandleValue vp) {
868 MOZ_ASSERT(!IsInternalDotName(cx, id));
869 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
870 RootedValue actualReceiver(cx, receiver);
871 if (receiver.isObject() && &receiver.toObject() == obj) {
872 actualReceiver.setObject(*actual);
873 }
874 return GetProperty(cx, actual, actualReceiver, id, vp);
875 }
876
877 static bool with_SetProperty(JSContext* cx, HandleObject obj, HandleId id,
878 HandleValue v, HandleValue receiver,
879 ObjectOpResult& result) {
880 MOZ_ASSERT(!IsInternalDotName(cx, id));
881 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
882 RootedValue actualReceiver(cx, receiver);
883 if (receiver.isObject() && &receiver.toObject() == obj) {
884 actualReceiver.setObject(*actual);
885 }
886 return SetProperty(cx, actual, id, v, actualReceiver, result);
887 }
888
889 static bool with_GetOwnPropertyDescriptor(
890 JSContext* cx, HandleObject obj, HandleId id,
891 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
892 MOZ_ASSERT(!IsInternalDotName(cx, id));
893 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
894 return GetOwnPropertyDescriptor(cx, actual, id, desc);
895 }
896
897 static bool with_DeleteProperty(JSContext* cx, HandleObject obj, HandleId id,
898 ObjectOpResult& result) {
899 MOZ_ASSERT(!IsInternalDotName(cx, id));
900 RootedObject actual(cx, &obj->as<WithEnvironmentObject>().object());
901 return DeleteProperty(cx, actual, id, result);
902 }
903
904 static const ObjectOps WithEnvironmentObjectOps = {
905 with_LookupProperty, // lookupProperty
906 with_DefineProperty, // defineProperty
907 with_HasProperty, // hasProperty
908 with_GetProperty, // getProperty
909 with_SetProperty, // setProperty
910 with_GetOwnPropertyDescriptor, // getOwnPropertyDescriptor
911 with_DeleteProperty, // deleteProperty
912 nullptr, // getElements
913 nullptr, // funToString
914 };
915
916 const JSClass WithEnvironmentObject::class_ = {
917 "With",
918 JSCLASS_HAS_RESERVED_SLOTS(WithEnvironmentObject::RESERVED_SLOTS),
919 JS_NULL_CLASS_OPS,
920 JS_NULL_CLASS_SPEC,
921 JS_NULL_CLASS_EXT,
922 &WithEnvironmentObjectOps,
923 };
924
925 /* static */
926 NonSyntacticVariablesObject* NonSyntacticVariablesObject::create(
927 JSContext* cx) {
928 Rooted<SharedShape*> shape(
929 cx, EmptyEnvironmentShape<NonSyntacticVariablesObject>(cx));
930 if (!shape) {
931 return nullptr;
932 }
933
934 Rooted<NonSyntacticVariablesObject*> obj(
935 cx, CreateEnvironmentObject<NonSyntacticVariablesObject>(cx, shape,
936 TenuredObject));
937 if (!obj) {
938 return nullptr;
939 }
940
941 // An NVSO holds both variables qualified with `var` and those that are not.
942 MOZ_ASSERT(obj->isUnqualifiedVarObj());
943 MOZ_ASSERT(obj->isQualifiedVarObj());
944
945 obj->initEnclosingEnvironment(&cx->global()->lexicalEnvironment());
946 return obj;
947 }
948
949 const JSClass NonSyntacticVariablesObject::class_ = {
950 "NonSyntacticVariablesObject",
951 JSCLASS_HAS_RESERVED_SLOTS(NonSyntacticVariablesObject::RESERVED_SLOTS),
952 };
953
954 NonSyntacticLexicalEnvironmentObject* js::CreateNonSyntacticEnvironmentChain(
955 JSContext* cx, const JS::EnvironmentChain& envChain) {
956 // Callers are responsible for segregating the NonSyntactic case from simple
957 // compilation cases.
958 MOZ_RELEASE_ASSERT(!envChain.empty());
959
960 RootedObject globalLexical(cx, &cx->global()->lexicalEnvironment());
961 Rooted<WithEnvironmentObject*> env(
962 cx, CreateObjectsForEnvironmentChain(cx, envChain, globalLexical));
963 if (!env) {
964 return nullptr;
965 }
966
967 // The XPConnect subscript loader, which may pass in its own
968 // environments to load scripts in, expects the environment chain to
969 // be the holder of "var" declarations. In SpiderMonkey, such objects
970 // are called "qualified varobjs", the "qualified" part meaning the
971 // declaration was qualified by "var". There is only sadness.
972 //
973 // See JSObject::isQualifiedVarObj.
974 if (!JSObject::setQualifiedVarObj(cx, env)) {
975 return nullptr;
976 }
977
978 // Also get a non-syntactic lexical environment to capture 'let' and
979 // 'const' bindings. To persist lexical bindings, we have a 1-1
980 // mapping with the final unwrapped environment object (the
981 // environment that stores the 'var' bindings) and the lexical
982 // environment.
983 //
984 // TODOshu: disallow the subscript loader from using non-distinguished
985 // objects as dynamic scopes.
986 return ObjectRealm::get(env).getOrCreateNonSyntacticLexicalEnvironment(cx,
987 env);
988 }
989
990 /*****************************************************************************/
991
992 const JSClass LexicalEnvironmentObject::class_ = {
993 "LexicalEnvironment",
994 JSCLASS_HAS_RESERVED_SLOTS(LexicalEnvironmentObject::RESERVED_SLOTS),
995 JS_NULL_CLASS_OPS,
996 JS_NULL_CLASS_SPEC,
997 JS_NULL_CLASS_EXT,
998 JS_NULL_OBJECT_OPS,
999 };
1000
1001 /* static */
1002 LexicalEnvironmentObject* LexicalEnvironmentObject::create(
1003 JSContext* cx, Handle<SharedShape*> shape, HandleObject enclosing,
1004 gc::Heap heap, gc::AllocSite* site) {
1005 MOZ_ASSERT(shape->getObjectClass() == &LexicalEnvironmentObject::class_);
1006
1007 // The JITs assume the result is nursery allocated unless we collected the
1008 // nursery, so don't change |heap| here.
1009
1010 auto* env =
1011 CreateEnvironmentObject<LexicalEnvironmentObject>(cx, shape, heap, site);
1012 if (!env) {
1013 return nullptr;
1014 }
1015
1016 MOZ_ASSERT(!env->inDictionaryMode());
1017
1018 if (enclosing) {
1019 env->initEnclosingEnvironment(enclosing);
1020 }
1021
1022 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1023 env->initSlot(LexicalEnvironmentObject::DISPOSABLE_RESOURCE_STACK_SLOT,
1024 UndefinedValue());
1025 #endif
1026
1027 return env;
1028 }
1029
1030 bool LexicalEnvironmentObject::isExtensible() const {
1031 return NativeObject::isExtensible();
1032 }
1033
1034 /* static */
1035 BlockLexicalEnvironmentObject* BlockLexicalEnvironmentObject::create(
1036 JSContext* cx, Handle<LexicalScope*> scope, HandleObject enclosing,
1037 gc::Heap heap, gc::AllocSite* site) {
1038 cx->check(enclosing);
1039 MOZ_ASSERT(scope->hasEnvironment());
1040
1041 Rooted<SharedShape*> shape(cx, scope->environmentShape());
1042 auto* env = static_cast<BlockLexicalEnvironmentObject*>(
1043 LexicalEnvironmentObject::create(cx, shape, enclosing, heap, site));
1044 if (!env) {
1045 return nullptr;
1046 }
1047
1048 // All lexical bindings start off uninitialized for TDZ.
1049 uint32_t lastSlot = env->getLastProperty().slot();
1050 for (uint32_t slot = JSSLOT_FREE(&class_); slot <= lastSlot; slot++) {
1051 env->initSlot(slot, MagicValue(JS_UNINITIALIZED_LEXICAL));
1052 }
1053
1054 env->initScope(scope);
1055 return env;
1056 }
1057
1058 /* static */
1059 BlockLexicalEnvironmentObject* BlockLexicalEnvironmentObject::createForFrame(
1060 JSContext* cx, Handle<LexicalScope*> scope, AbstractFramePtr frame) {
1061 RootedObject enclosing(cx, frame.environmentChain());
1062 return create(cx, scope, enclosing, gc::Heap::Default);
1063 }
1064
1065 /* static */
1066 BlockLexicalEnvironmentObject*
1067 BlockLexicalEnvironmentObject::createHollowForDebug(
1068 JSContext* cx, Handle<LexicalScope*> scope) {
1069 MOZ_ASSERT(!scope->hasEnvironment());
1070
1071 Rooted<SharedShape*> shape(
1072 cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
1073 if (!shape) {
1074 return nullptr;
1075 }
1076
1077 // This environment's enclosing link is never used: the
1078 // DebugEnvironmentProxy that refers to this scope carries its own
1079 // enclosing link, which is what Debugger uses to construct the tree of
1080 // Debugger.Environment objects.
1081 RootedObject enclosingEnv(cx, &cx->global()->lexicalEnvironment());
1082 Rooted<LexicalEnvironmentObject*> env(
1083 cx, LexicalEnvironmentObject::create(cx, shape, enclosingEnv,
1084 gc::Heap::Tenured));
1085 if (!env) {
1086 return nullptr;
1087 }
1088
1089 RootedValue optimizedOut(cx, MagicValue(JS_OPTIMIZED_OUT));
1090 RootedId id(cx);
1091 for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
1092 id = NameToId(bi.name()->asPropertyName());
1093 if (!SetProperty(cx, env, id, optimizedOut)) {
1094 return nullptr;
1095 }
1096 }
1097
1098 if (!JSObject::setFlag(cx, env, ObjectFlag::NotExtensible)) {
1099 return nullptr;
1100 }
1101
1102 env->as<ScopedLexicalEnvironmentObject>().initScope(scope);
1103 return &env->as<BlockLexicalEnvironmentObject>();
1104 }
1105
1106 /* static */
1107 BlockLexicalEnvironmentObject*
1108 BlockLexicalEnvironmentObject::createTemplateObject(
1109 JSContext* cx, Handle<LexicalScope*> scope) {
1110 return create(cx, scope, nullptr, gc::Heap::Tenured);
1111 }
1112
1113 /* static */
1114 BlockLexicalEnvironmentObject*
1115 BlockLexicalEnvironmentObject::createWithoutEnclosing(
1116 JSContext* cx, Handle<LexicalScope*> scope) {
1117 return create(cx, scope, nullptr, gc::Heap::Default);
1118 }
1119
1120 /* static */
1121 BlockLexicalEnvironmentObject* BlockLexicalEnvironmentObject::clone(
1122 JSContext* cx, Handle<BlockLexicalEnvironmentObject*> env) {
1123 Rooted<LexicalScope*> scope(cx, &env->scope());
1124 RootedObject enclosing(cx, &env->enclosingEnvironment());
1125 Rooted<BlockLexicalEnvironmentObject*> copy(
1126 cx, create(cx, scope, enclosing, gc::Heap::Default));
1127 if (!copy) {
1128 return nullptr;
1129 }
1130
1131 MOZ_ASSERT(env->shape() == copy->shape());
1132 for (uint32_t i = JSSLOT_FREE(&class_); i < copy->slotSpan(); i++) {
1133 copy->setSlot(i, env->getSlot(i));
1134 }
1135
1136 return copy;
1137 }
1138
1139 /* static */
1140 BlockLexicalEnvironmentObject* BlockLexicalEnvironmentObject::recreate(
1141 JSContext* cx, Handle<BlockLexicalEnvironmentObject*> env) {
1142 Rooted<LexicalScope*> scope(cx, &env->scope());
1143 RootedObject enclosing(cx, &env->enclosingEnvironment());
1144 return create(cx, scope, enclosing, gc::Heap::Default);
1145 }
1146
1147 /* static */
1148 NamedLambdaObject* NamedLambdaObject::create(JSContext* cx,
1149 HandleFunction callee,
1150 HandleObject enclosing,
1151 gc::Heap heap,
1152 gc::AllocSite* site) {
1153 MOZ_ASSERT(callee->isNamedLambda());
1154 Rooted<Scope*> scope(cx, callee->nonLazyScript()->maybeNamedLambdaScope());
1155 MOZ_ASSERT(scope && scope->environmentShape());
1156
1157 #ifdef DEBUG
1158 {
1159 // Named lambda objects have one (non-writable) property.
1160 SharedShapePropertyIter<NoGC> iter(scope->environmentShape());
1161 MOZ_ASSERT(iter->slot() == lambdaSlot());
1162 MOZ_ASSERT(!iter->writable());
1163 iter++;
1164 MOZ_ASSERT(iter.done());
1165
1166 // There should be exactly one binding in the named lambda scope.
1167 BindingIter bi(scope);
1168 bi++;
1169 MOZ_ASSERT(bi.done());
1170 }
1171 #endif
1172
1173 BlockLexicalEnvironmentObject* obj = BlockLexicalEnvironmentObject::create(
1174 cx, scope.as<LexicalScope>(), enclosing, heap, site);
1175 if (!obj) {
1176 return nullptr;
1177 }
1178
1179 obj->initFixedSlot(lambdaSlot(), ObjectValue(*callee));
1180 return static_cast<NamedLambdaObject*>(obj);
1181 }
1182
1183 /* static */
1184 NamedLambdaObject* NamedLambdaObject::createTemplateObject(
1185 JSContext* cx, HandleFunction callee) {
1186 return create(cx, callee, nullptr, gc::Heap::Tenured);
1187 }
1188
1189 /* static */
1190 NamedLambdaObject* NamedLambdaObject::createWithoutEnclosing(
1191 JSContext* cx, HandleFunction callee, gc::Heap heap) {
1192 return create(cx, callee, nullptr, heap);
1193 }
1194
1195 /* static */
1196 NamedLambdaObject* NamedLambdaObject::createForFrame(JSContext* cx,
1197 AbstractFramePtr frame,
1198 gc::AllocSite* site) {
1199 RootedFunction fun(cx, frame.callee());
1200 RootedObject enclosing(cx, frame.environmentChain());
1201 gc::Heap heap = site ? site->initialHeap() : gc::Heap::Default;
1202 return create(cx, fun, enclosing, heap, site);
1203 }
1204
1205 /* static */
1206 size_t NamedLambdaObject::lambdaSlot() {
1207 // Named lambda environments have exactly one name.
1208 return JSSLOT_FREE(&LexicalEnvironmentObject::class_);
1209 }
1210
1211 /* static */
1212 ClassBodyLexicalEnvironmentObject* ClassBodyLexicalEnvironmentObject::create(
1213 JSContext* cx, Handle<ClassBodyScope*> scope, HandleObject enclosing,
1214 gc::Heap heap) {
1215 cx->check(enclosing);
1216 MOZ_ASSERT(scope->hasEnvironment());
1217
1218 Rooted<SharedShape*> shape(cx, scope->environmentShape());
1219 auto* env = static_cast<ClassBodyLexicalEnvironmentObject*>(
1220 LexicalEnvironmentObject::create(cx, shape, enclosing, heap));
1221 if (!env) {
1222 return nullptr;
1223 }
1224
1225 env->initScope(scope);
1226 return env;
1227 }
1228
1229 /* static */
1230 ClassBodyLexicalEnvironmentObject*
1231 ClassBodyLexicalEnvironmentObject::createForFrame(JSContext* cx,
1232 Handle<ClassBodyScope*> scope,
1233 AbstractFramePtr frame) {
1234 RootedObject enclosing(cx, frame.environmentChain());
1235 return create(cx, scope, enclosing, gc::Heap::Default);
1236 }
1237
1238 /* static */
1239 ClassBodyLexicalEnvironmentObject*
1240 ClassBodyLexicalEnvironmentObject::createTemplateObject(
1241 JSContext* cx, Handle<ClassBodyScope*> scope) {
1242 return create(cx, scope, nullptr, gc::Heap::Tenured);
1243 }
1244
1245 /* static */
1246 ClassBodyLexicalEnvironmentObject*
1247 ClassBodyLexicalEnvironmentObject::createWithoutEnclosing(
1248 JSContext* cx, Handle<ClassBodyScope*> scope) {
1249 return create(cx, scope, nullptr, gc::Heap::Default);
1250 }
1251
1252 JSObject* ExtensibleLexicalEnvironmentObject::thisObject() const {
1253 JSObject* obj = &getReservedSlot(THIS_VALUE_OR_SCOPE_SLOT).toObject();
1254
1255 // Windows must never be exposed to script. initThisObject should have set
1256 // this to the WindowProxy.
1257 MOZ_ASSERT(!IsWindow(obj));
1258
1259 // WarpBuilder relies on the return value not being nursery-allocated for the
1260 // global lexical environment.
1261 MOZ_ASSERT_IF(isGlobal(), obj->isTenured());
1262
1263 return obj;
1264 }
1265
1266 /* static */
1267 ExtensibleLexicalEnvironmentObject*
1268 ExtensibleLexicalEnvironmentObject::forVarEnvironment(JSObject* obj) {
1269 ExtensibleLexicalEnvironmentObject* lexical = nullptr;
1270 if (obj->is<GlobalObject>()) {
1271 lexical = &obj->as<GlobalObject>().lexicalEnvironment();
1272 } else {
1273 lexical = ObjectRealm::get(obj).getNonSyntacticLexicalEnvironment(obj);
1274 }
1275 MOZ_ASSERT(lexical);
1276 return lexical;
1277 }
1278
1279 /* static */
1280 GlobalLexicalEnvironmentObject* GlobalLexicalEnvironmentObject::create(
1281 JSContext* cx, Handle<GlobalObject*> global) {
1282 MOZ_ASSERT(global);
1283
1284 Rooted<SharedShape*> shape(
1285 cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
1286 if (!shape) {
1287 return nullptr;
1288 }
1289
1290 auto* env = static_cast<GlobalLexicalEnvironmentObject*>(
1291 LexicalEnvironmentObject::create(cx, shape, global, gc::Heap::Tenured));
1292 if (!env) {
1293 return nullptr;
1294 }
1295
1296 env->initThisObject(global);
1297 return env;
1298 }
1299
1300 void GlobalLexicalEnvironmentObject::setWindowProxyThisObject(JSObject* obj) {
1301 MOZ_ASSERT(IsWindowProxy(obj));
1302 setReservedSlot(THIS_VALUE_OR_SCOPE_SLOT, ObjectValue(*obj));
1303 }
1304
1305 /* static */
1306 NonSyntacticLexicalEnvironmentObject*
1307 NonSyntacticLexicalEnvironmentObject::create(JSContext* cx,
1308 HandleObject enclosing,
1309 HandleObject thisv) {
1310 MOZ_ASSERT(enclosing);
1311 MOZ_ASSERT(!IsSyntacticEnvironment(enclosing));
1312
1313 Rooted<SharedShape*> shape(
1314 cx, LexicalScope::getEmptyExtensibleEnvironmentShape(cx));
1315 if (!shape) {
1316 return nullptr;
1317 }
1318
1319 auto* env = static_cast<NonSyntacticLexicalEnvironmentObject*>(
1320 LexicalEnvironmentObject::create(cx, shape, enclosing,
1321 gc::Heap::Tenured));
1322 if (!env) {
1323 return nullptr;
1324 }
1325
1326 env->initThisObject(thisv);
1327
1328 return env;
1329 }
1330
1331 /* static */
1332 RuntimeLexicalErrorObject* RuntimeLexicalErrorObject::create(
1333 JSContext* cx, HandleObject enclosing, unsigned errorNumber) {
1334 Rooted<SharedShape*> shape(
1335 cx,
1336 EmptyEnvironmentShape(cx, &class_, JSSLOT_FREE(&class_), ObjectFlags()));
1337 if (!shape) {
1338 return nullptr;
1339 }
1340
1341 auto* obj = CreateEnvironmentObject<RuntimeLexicalErrorObject>(cx, shape);
1342 if (!obj) {
1343 return nullptr;
1344 }
1345 obj->initEnclosingEnvironment(enclosing);
1346 obj->initReservedSlot(ERROR_SLOT, Int32Value(int32_t(errorNumber)));
1347
1348 return obj;
1349 }
1350
1351 static void ReportRuntimeLexicalErrorId(JSContext* cx, unsigned errorNumber,
1352 HandleId id) {
1353 if (id.isAtom()) {
1354 Rooted<PropertyName*> name(cx, id.toAtom()->asPropertyName());
1355 ReportRuntimeLexicalError(cx, errorNumber, name);
1356 return;
1357 }
1358 MOZ_CRASH(
1359 "RuntimeLexicalErrorObject should only be used with property names");
1360 }
1361
1362 static bool lexicalError_LookupProperty(JSContext* cx, HandleObject obj,
1363 HandleId id, MutableHandleObject objp,
1364 PropertyResult* propp) {
1365 ReportRuntimeLexicalErrorId(
1366 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1367 return false;
1368 }
1369
1370 static bool lexicalError_HasProperty(JSContext* cx, HandleObject obj,
1371 HandleId id, bool* foundp) {
1372 ReportRuntimeLexicalErrorId(
1373 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1374 return false;
1375 }
1376
1377 static bool lexicalError_GetProperty(JSContext* cx, HandleObject obj,
1378 HandleValue receiver, HandleId id,
1379 MutableHandleValue vp) {
1380 ReportRuntimeLexicalErrorId(
1381 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1382 return false;
1383 }
1384
1385 static bool lexicalError_SetProperty(JSContext* cx, HandleObject obj,
1386 HandleId id, HandleValue v,
1387 HandleValue receiver,
1388 ObjectOpResult& result) {
1389 ReportRuntimeLexicalErrorId(
1390 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1391 return false;
1392 }
1393
1394 static bool lexicalError_GetOwnPropertyDescriptor(
1395 JSContext* cx, HandleObject obj, HandleId id,
1396 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) {
1397 ReportRuntimeLexicalErrorId(
1398 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1399 return false;
1400 }
1401
1402 static bool lexicalError_DeleteProperty(JSContext* cx, HandleObject obj,
1403 HandleId id, ObjectOpResult& result) {
1404 ReportRuntimeLexicalErrorId(
1405 cx, obj->as<RuntimeLexicalErrorObject>().errorNumber(), id);
1406 return false;
1407 }
1408
1409 static const ObjectOps RuntimeLexicalErrorObjectObjectOps = {
1410 lexicalError_LookupProperty, // lookupProperty
1411 nullptr, // defineProperty
1412 lexicalError_HasProperty, // hasProperty
1413 lexicalError_GetProperty, // getProperty
1414 lexicalError_SetProperty, // setProperty
1415 lexicalError_GetOwnPropertyDescriptor, // getOwnPropertyDescriptor
1416 lexicalError_DeleteProperty, // deleteProperty
1417 nullptr, // getElements
1418 nullptr, // funToString
1419 };
1420
1421 const JSClass RuntimeLexicalErrorObject::class_ = {
1422 "RuntimeLexicalError",
1423 JSCLASS_HAS_RESERVED_SLOTS(RuntimeLexicalErrorObject::RESERVED_SLOTS),
1424 JS_NULL_CLASS_OPS,
1425 JS_NULL_CLASS_SPEC,
1426 JS_NULL_CLASS_EXT,
1427 &RuntimeLexicalErrorObjectObjectOps,
1428 };
1429
1430 /*****************************************************************************/
1431
1432 EnvironmentIter::EnvironmentIter(JSContext* cx, const EnvironmentIter& ei)
1433 : si_(cx, ei.si_.get()), env_(cx, ei.env_), frame_(ei.frame_) {}
1434
1435 EnvironmentIter::EnvironmentIter(JSContext* cx, JSObject* env, Scope* scope)
1436 : si_(cx, ScopeIter(scope)), env_(cx, env), frame_(NullFramePtr()) {
1437 settle();
1438 }
1439
1440 EnvironmentIter::EnvironmentIter(JSContext* cx, AbstractFramePtr frame,
1441 const jsbytecode* pc)
1442 : si_(cx, frame.script()->innermostScope(pc)),
1443 env_(cx, frame.environmentChain()),
1444 frame_(frame) {
1445 cx->check(frame);
1446 settle();
1447 }
1448
1449 EnvironmentIter::EnvironmentIter(JSContext* cx, JSObject* env, Scope* scope,
1450 AbstractFramePtr frame)
1451 : si_(cx, ScopeIter(scope)), env_(cx, env), frame_(frame) {
1452 cx->check(frame);
1453 settle();
1454 }
1455
1456 void EnvironmentIter::incrementScopeIter() {
1457 if (si_.scope()->is<GlobalScope>()) {
1458 // GlobalScopes may be syntactic or non-syntactic. Non-syntactic
1459 // GlobalScopes correspond to zero or more non-syntactic
1460 // EnvironmentsObjects followed by the global lexical scope, then the
1461 // GlobalObject or another non-EnvironmentObject object.
1462 if (!env_->is<EnvironmentObject>()) {
1463 si_++;
1464 }
1465 } else {
1466 si_++;
1467 }
1468 }
1469
1470 void EnvironmentIter::settle() {
1471 // Check for trying to iterate a function or eval frame before the prologue
1472 // has created the CallObject, in which case we have to skip.
1473 if (frame_ && frame_.hasScript() &&
1474 frame_.script()->initialEnvironmentShape() &&
1475 !frame_.hasInitialEnvironment()) {
1476 // Skip until we're at the enclosing scope of the script.
1477 while (si_.scope() != frame_.script()->enclosingScope()) {
1478 if (env_->is<BlockLexicalEnvironmentObject>() &&
1479 &env_->as<BlockLexicalEnvironmentObject>().scope() == si_.scope()) {
1480 MOZ_ASSERT(si_.kind() == ScopeKind::NamedLambda ||
1481 si_.kind() == ScopeKind::StrictNamedLambda);
1482 env_ =
1483 &env_->as<BlockLexicalEnvironmentObject>().enclosingEnvironment();
1484 }
1485 incrementScopeIter();
1486 }
1487 }
1488
1489 // Check if we have left the extent of the initial frame after we've
1490 // settled on a static scope.
1491 if (frame_ &&
1492 (!si_ ||
1493 (frame_.hasScript() &&
1494 si_.scope() == frame_.script()->enclosingScope()) ||
1495 (frame_.isWasmDebugFrame() && !si_.scope()->is<WasmFunctionScope>()))) {
1496 frame_ = NullFramePtr();
1497 }
1498
1499 #ifdef DEBUG
1500 if (si_) {
1501 if (hasSyntacticEnvironment()) {
1502 Scope* scope = si_.scope();
1503 if (scope->is<LexicalScope>()) {
1504 MOZ_ASSERT(scope == &env_->as<BlockLexicalEnvironmentObject>().scope());
1505 } else if (scope->is<FunctionScope>()) {
1506 MOZ_ASSERT(scope->as<FunctionScope>().script() ==
1507 env_->as<CallObject>()
1508 .callee()
1509 .maybeCanonicalFunction()
1510 ->baseScript());
1511 } else if (scope->is<VarScope>()) {
1512 MOZ_ASSERT(scope == &env_->as<VarEnvironmentObject>().scope());
1513 } else if (scope->is<WithScope>()) {
1514 MOZ_ASSERT(scope == &env_->as<WithEnvironmentObject>().scope());
1515 } else if (scope->is<EvalScope>()) {
1516 MOZ_ASSERT(scope == &env_->as<VarEnvironmentObject>().scope());
1517 } else if (scope->is<GlobalScope>()) {
1518 MOZ_ASSERT(env_->is<GlobalObject>() ||
1519 env_->is<GlobalLexicalEnvironmentObject>());
1520 }
1521 } else if (hasNonSyntacticEnvironmentObject()) {
1522 if (env_->is<LexicalEnvironmentObject>()) {
1523 // The global lexical environment still encloses non-syntactic
1524 // environment objects.
1525 MOZ_ASSERT(env_->is<NonSyntacticLexicalEnvironmentObject>() ||
1526 env_->is<GlobalLexicalEnvironmentObject>());
1527 } else if (env_->is<WithEnvironmentObject>()) {
1528 MOZ_ASSERT(!env_->as<WithEnvironmentObject>().isSyntactic());
1529 } else {
1530 MOZ_ASSERT(env_->is<NonSyntacticVariablesObject>());
1531 }
1532 }
1533 }
1534 #endif
1535 }
1536
1537 JSObject& EnvironmentIter::enclosingEnvironment() const {
1538 // As an engine invariant (maintained internally and asserted by Execute),
1539 // EnvironmentObjects and non-EnvironmentObjects cannot be interleaved on
1540 // the scope chain; every scope chain must start with zero or more
1541 // EnvironmentObjects and terminate with one or more
1542 // non-EnvironmentObjects (viz., GlobalObject).
1543 MOZ_ASSERT(done());
1544 MOZ_ASSERT(!env_->is<EnvironmentObject>());
1545 return *env_;
1546 }
1547
1548 bool EnvironmentIter::hasNonSyntacticEnvironmentObject() const {
1549 // The case we're worrying about here is a NonSyntactic static scope which
1550 // has 0+ corresponding non-syntactic WithEnvironmentObject scopes, a
1551 // NonSyntacticVariablesObject, or a NonSyntacticLexicalEnvironmentObject.
1552 if (si_.kind() == ScopeKind::NonSyntactic) {
1553 MOZ_ASSERT_IF(env_->is<WithEnvironmentObject>(),
1554 !env_->as<WithEnvironmentObject>().isSyntactic());
1555 return env_->is<EnvironmentObject>();
1556 }
1557 return false;
1558 }
1559
1560 /* static */
1561 HashNumber MissingEnvironmentKey::hash(MissingEnvironmentKey ek) {
1562 return size_t(ek.frame_.raw()) ^ size_t(ek.scope_);
1563 }
1564
1565 /* static */
1566 bool MissingEnvironmentKey::match(MissingEnvironmentKey ek1,
1567 MissingEnvironmentKey ek2) {
1568 return ek1.frame_ == ek2.frame_ && ek1.scope_ == ek2.scope_;
1569 }
1570
1571 bool LiveEnvironmentVal::traceWeak(JSTracer* trc) {
1572 return TraceWeakEdge(trc, &scope_, "LiveEnvironmentVal::scope_");
1573 }
1574
1575 // Live EnvironmentIter values may be added to DebugEnvironments::liveEnvs, as
1576 // LiveEnvironmentVal instances. They need to have write barriers when they are
1577 // added to the hash table, but no barriers when rehashing inside GC. It's a
1578 // nasty hack, but the important thing is that LiveEnvironmentVal and
1579 // MissingEnvironmentKey need to alias each other.
1580 void LiveEnvironmentVal::staticAsserts() {
1581 static_assert(
1582 sizeof(LiveEnvironmentVal) == sizeof(MissingEnvironmentKey),
1583 "LiveEnvironmentVal must be same size of MissingEnvironmentKey");
1584 static_assert(
1585 offsetof(LiveEnvironmentVal, scope_) ==
1586 offsetof(MissingEnvironmentKey, scope_),
1587 "LiveEnvironmentVal.scope_ must alias MissingEnvironmentKey.scope_");
1588 }
1589
1590 /*****************************************************************************/
1591
1592 namespace {
1593
1594 /*
1595 * DebugEnvironmentProxy is the handler for DebugEnvironmentProxy proxy
1596 * objects. Having a custom handler (rather than trying to reuse js::Wrapper)
1597 * gives us several important abilities:
1598 * - We want to pass the EnvironmentObject as the receiver to forwarded scope
1599 * property ops on aliased variables so that Call/Block/With ops do not all
1600 * require a 'normalization' step.
1601 * - The debug scope proxy can directly manipulate the stack frame to allow
1602 * the debugger to read/write args/locals that were otherwise unaliased.
1603 * - The debug scope proxy can store unaliased variables after the stack frame
1604 * is popped so that they may still be read/written by the debugger.
1605 * - The engine has made certain assumptions about the possible reads/writes
1606 * in a scope. DebugEnvironmentProxy allows us to prevent the debugger from
1607 * breaking those assumptions.
1608 * - The engine makes optimizations that are observable to the debugger. The
1609 * proxy can either hide these optimizations or make the situation more
1610 * clear to the debugger. An example is 'arguments'.
1611 */
1612 class DebugEnvironmentProxyHandler : public NurseryAllocableProxyHandler {
1613 enum Action { SET, GET };
1614
1615 enum AccessResult { ACCESS_UNALIASED, ACCESS_GENERIC, ACCESS_LOST };
1616
1617 /*
1618 * This function handles access to unaliased locals/formals. Since they
1619 * are unaliased, the values of these variables are not stored in the
1620 * slots of the normal CallObject and BlockLexicalEnvironmentObject
1621 * environments and thus must be recovered from somewhere else:
1622 * + if the invocation for which the env was created is still executing,
1623 * there is a JS frame live on the stack holding the values;
1624 * + if the invocation for which the env was created finished executing:
1625 * - and there was a DebugEnvironmentProxy associated with env, then
1626 * the DebugEnvironments::onPop(Call|Lexical) handler copied out the
1627 * unaliased variables. In both cases, a dense array is created in
1628 * onPop(Call|Lexical) to hold the unaliased values and attached to
1629 * the DebugEnvironmentProxy;
1630 * - and there was not a DebugEnvironmentProxy yet associated with the
1631 * scope, then the unaliased values are lost and not recoverable.
1632 *
1633 * Callers should check accessResult for non-failure results:
1634 * - ACCESS_UNALIASED if the access was unaliased and completed
1635 * - ACCESS_GENERIC if the access was aliased or the property not found
1636 * - ACCESS_LOST if the value has been lost to the debugger and the
1637 * action is GET; if the action is SET, we assign to the
1638 * name of the variable on the environment object
1639 */
1640 bool handleUnaliasedAccess(JSContext* cx,
1641 Handle<DebugEnvironmentProxy*> debugEnv,
1642 Handle<EnvironmentObject*> env, HandleId id,
1643 Action action, MutableHandleValue vp,
1644 AccessResult* accessResult) const {
1645 MOZ_ASSERT(&debugEnv->environment() == env);
1646 MOZ_ASSERT_IF(action == SET, !debugEnv->isOptimizedOut());
1647 *accessResult = ACCESS_GENERIC;
1648 LiveEnvironmentVal* maybeLiveEnv =
1649 DebugEnvironments::hasLiveEnvironment(*env);
1650
1651 // Handle unaliased formals, vars, lets, and consts at function or module
1652 // scope.
1653 if (env->is<CallObject>() || env->is<ModuleEnvironmentObject>()) {
1654 RootedScript script(cx);
1655 if (env->is<CallObject>()) {
1656 CallObject& callobj = env->as<CallObject>();
1657 RootedFunction fun(cx, &callobj.callee());
1658 script = JSFunction::getOrCreateScript(cx, fun);
1659 } else {
1660 script = env->as<ModuleEnvironmentObject>().module().maybeScript();
1661 if (!script) {
1662 return true;
1663 }
1664 }
1665
1666 BindingIter bi(script);
1667 while (bi && NameToId(bi.name()->asPropertyName()) != id) {
1668 bi++;
1669 }
1670 if (!bi) {
1671 return true;
1672 }
1673
1674 if (action == SET && bi.kind() == BindingKind::Const) {
1675 ReportRuntimeLexicalError(cx, JSMSG_BAD_CONST_ASSIGN, id);
1676 return false;
1677 }
1678
1679 if (bi.location().kind() == BindingLocation::Kind::Import) {
1680 return true;
1681 }
1682
1683 if (!bi.hasArgumentSlot()) {
1684 if (bi.closedOver()) {
1685 return true;
1686 }
1687
1688 uint32_t i = bi.location().slot();
1689 if (maybeLiveEnv) {
1690 AbstractFramePtr frame = maybeLiveEnv->frame();
1691 if (action == GET) {
1692 vp.set(frame.unaliasedLocal(i));
1693 } else {
1694 frame.unaliasedLocal(i) = vp;
1695 }
1696 } else if (AbstractGeneratorObject* genObj =
1697 GetGeneratorObjectForEnvironment(cx, env);
1698 genObj && genObj->isSuspended() &&
1699 genObj->hasStackStorage()) {
1700 if (action == GET) {
1701 vp.set(genObj->getUnaliasedLocal(i));
1702 } else {
1703 genObj->setUnaliasedLocal(i, vp);
1704 }
1705 } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
1706 if (action == GET) {
1707 vp.set(snapshot->getDenseElement(script->numArgs() + i));
1708 } else {
1709 snapshot->setDenseElement(script->numArgs() + i, vp);
1710 }
1711 } else {
1712 /* The unaliased value has been lost to the debugger. */
1713 if (action == GET) {
1714 *accessResult = ACCESS_LOST;
1715 return true;
1716 }
1717 }
1718 } else {
1719 unsigned i = bi.argumentSlot();
1720 if (bi.closedOver()) {
1721 return true;
1722 }
1723
1724 if (maybeLiveEnv) {
1725 AbstractFramePtr frame = maybeLiveEnv->frame();
1726 if (script->argsObjAliasesFormals() && frame.hasArgsObj()) {
1727 if (action == GET) {
1728 vp.set(frame.argsObj().arg(i));
1729 } else {
1730 frame.argsObj().setArg(i, vp);
1731 }
1732 } else {
1733 if (action == GET) {
1734 vp.set(frame.unaliasedFormal(i, DONT_CHECK_ALIASING));
1735 } else {
1736 frame.unaliasedFormal(i, DONT_CHECK_ALIASING) = vp;
1737 }
1738 }
1739 } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
1740 if (action == GET) {
1741 vp.set(snapshot->getDenseElement(i));
1742 } else {
1743 snapshot->setDenseElement(i, vp);
1744 }
1745 } else {
1746 /* The unaliased value has been lost to the debugger. */
1747 if (action == GET) {
1748 *accessResult = ACCESS_LOST;
1749 return true;
1750 }
1751 }
1752 }
1753
1754 // It is possible that an optimized out value flows to this
1755 // location due to Debugger.Frame.prototype.eval operating on a
1756 // live bailed-out Baseline frame. In that case, treat the access
1757 // as lost.
1758 if (vp.isMagic() && vp.whyMagic() == JS_OPTIMIZED_OUT) {
1759 *accessResult = ACCESS_LOST;
1760 } else {
1761 *accessResult = ACCESS_UNALIASED;
1762 }
1763
1764 return true;
1765 }
1766
1767 /*
1768 * Handle unaliased vars in functions with parameter expressions and
1769 * lexical bindings at block scope.
1770 */
1771 if (env->is<LexicalEnvironmentObject>() ||
1772 env->is<VarEnvironmentObject>()) {
1773 // Currently consider all non-syntactic top-level lexical bindings to be
1774 // aliased.
1775 if (env->is<LexicalEnvironmentObject>() &&
1776 !env->is<GlobalLexicalEnvironmentObject>() &&
1777 env->as<LexicalEnvironmentObject>().isExtensible()) {
1778 MOZ_ASSERT(!IsSyntacticEnvironment(env));
1779 return true;
1780 }
1781
1782 // Currently all vars inside non-strict eval var environments are aliased.
1783 if (env->is<VarEnvironmentObject>() &&
1784 env->as<VarEnvironmentObject>().isForNonStrictEval()) {
1785 return true;
1786 }
1787
1788 Rooted<Scope*> scope(cx, getEnvironmentScope(*env));
1789 uint32_t firstFrameSlot = scope->firstFrameSlot();
1790
1791 BindingIter bi(scope);
1792 while (bi && NameToId(bi.name()->asPropertyName()) != id) {
1793 bi++;
1794 }
1795 if (!bi) {
1796 return true;
1797 }
1798
1799 if (action == SET && bi.kind() == BindingKind::Const) {
1800 ReportRuntimeLexicalError(cx, JSMSG_BAD_CONST_ASSIGN, id);
1801 return false;
1802 }
1803
1804 BindingLocation loc = bi.location();
1805 if (loc.kind() == BindingLocation::Kind::Environment) {
1806 return true;
1807 }
1808
1809 // Named lambdas that are not closed over are lost.
1810 if (loc.kind() == BindingLocation::Kind::NamedLambdaCallee) {
1811 if (action == GET) {
1812 *accessResult = ACCESS_LOST;
1813 }
1814 return true;
1815 }
1816
1817 MOZ_ASSERT(loc.kind() == BindingLocation::Kind::Frame);
1818
1819 if (maybeLiveEnv) {
1820 AbstractFramePtr frame = maybeLiveEnv->frame();
1821 uint32_t local = loc.slot();
1822 MOZ_ASSERT(local < frame.script()->nfixed());
1823 Value& localVal = frame.unaliasedLocal(local);
1824 if (action == GET) {
1825 vp.set(localVal);
1826 } else {
1827 // Note: localVal could also be JS_OPTIMIZED_OUT.
1828 if (localVal.isMagic() &&
1829 localVal.whyMagic() == JS_UNINITIALIZED_LEXICAL) {
1830 ReportRuntimeLexicalError(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
1831 return false;
1832 }
1833
1834 localVal = vp;
1835 }
1836 } else if (AbstractGeneratorObject* genObj =
1837 GetGeneratorObjectForEnvironment(cx, debugEnv);
1838 genObj && genObj->isSuspended() && genObj->hasStackStorage()) {
1839 if (action == GET) {
1840 vp.set(genObj->getUnaliasedLocal(loc.slot()));
1841 } else {
1842 genObj->setUnaliasedLocal(loc.slot(), vp);
1843 }
1844 } else if (NativeObject* snapshot = debugEnv->maybeSnapshot()) {
1845 // Indices in the frame snapshot are offset by the first frame
1846 // slot. See DebugEnvironments::takeFrameSnapshot.
1847 MOZ_ASSERT(loc.slot() >= firstFrameSlot);
1848 uint32_t snapshotIndex = loc.slot() - firstFrameSlot;
1849 if (action == GET) {
1850 vp.set(snapshot->getDenseElement(snapshotIndex));
1851 } else {
1852 snapshot->setDenseElement(snapshotIndex, vp);
1853 }
1854 } else {
1855 if (action == GET) {
1856 // A {Lexical,Var}EnvironmentObject whose static scope
1857 // does not have an environment shape at all is a "hollow"
1858 // block object reflected for missing block scopes. Their
1859 // slot values are lost.
1860 if (!scope->hasEnvironment()) {
1861 *accessResult = ACCESS_LOST;
1862 return true;
1863 }
1864
1865 if (!GetProperty(cx, env, env, id, vp)) {
1866 return false;
1867 }
1868 } else {
1869 if (!SetProperty(cx, env, id, vp)) {
1870 return false;
1871 }
1872 }
1873 }
1874
1875 // See comment above in analogous CallObject case.
1876 if (vp.isMagic() && vp.whyMagic() == JS_OPTIMIZED_OUT) {
1877 *accessResult = ACCESS_LOST;
1878 } else {
1879 *accessResult = ACCESS_UNALIASED;
1880 }
1881
1882 return true;
1883 }
1884
1885 if (env->is<WasmFunctionCallObject>()) {
1886 if (maybeLiveEnv) {
1887 Rooted<Scope*> scope(cx, getEnvironmentScope(*env));
1888 uint32_t index = 0;
1889 for (BindingIter bi(scope); bi; bi++) {
1890 if (id.isAtom(bi.name())) {
1891 break;
1892 }
1893 MOZ_ASSERT(!bi.isLast());
1894 index++;
1895 }
1896
1897 AbstractFramePtr frame = maybeLiveEnv->frame();
1898 MOZ_ASSERT(frame.isWasmDebugFrame());
1899 wasm::DebugFrame* wasmFrame = frame.asWasmDebugFrame();
1900 if (action == GET) {
1901 if (!wasmFrame->getLocal(index, vp)) {
1902 ReportOutOfMemory(cx);
1903 return false;
1904 }
1905 *accessResult = ACCESS_UNALIASED;
1906 } else { // if (action == SET)
1907 // TODO
1908 }
1909 } else {
1910 *accessResult = ACCESS_LOST;
1911 }
1912 return true;
1913 }
1914
1915 if (env->is<WasmInstanceEnvironmentObject>()) {
1916 Rooted<Scope*> scope(cx, getEnvironmentScope(*env));
1917 MOZ_ASSERT(scope->is<WasmInstanceScope>());
1918 uint32_t index = 0;
1919 for (BindingIter bi(scope); bi; bi++) {
1920 if (id.isAtom(bi.name())) {
1921 break;
1922 }
1923 MOZ_ASSERT(!bi.isLast());
1924 index++;
1925 }
1926 Rooted<WasmInstanceScope*> instanceScope(cx,
1927 &scope->as<WasmInstanceScope>());
1928 wasm::Instance& instance = instanceScope->instance()->instance();
1929
1930 if (action == GET) {
1931 if (instanceScope->memoriesStart() <= index &&
1932 index < instanceScope->globalsStart()) {
1933 vp.set(ObjectValue(
1934 *instance.memory(index - instanceScope->memoriesStart())));
1935 }
1936 if (instanceScope->globalsStart() <= index) {
1937 MOZ_ASSERT(index < instanceScope->namesCount());
1938 if (!instance.debug().getGlobal(
1939 instance, index - instanceScope->globalsStart(), vp)) {
1940 ReportOutOfMemory(cx);
1941 return false;
1942 }
1943 }
1944 *accessResult = ACCESS_UNALIASED;
1945 } else { // if (action == SET)
1946 // TODO
1947 }
1948 return true;
1949 }
1950
1951 /* The rest of the internal scopes do not have unaliased vars. */
1952 MOZ_ASSERT(!IsSyntacticEnvironment(env) ||
1953 env->is<WithEnvironmentObject>());
1954 return true;
1955 }
1956
1957 static bool isArguments(JSContext* cx, jsid id) {
1958 return id == NameToId(cx->names().arguments);
1959 }
1960 static bool isThis(JSContext* cx, jsid id) {
1961 return id == NameToId(cx->names().dot_this_);
1962 }
1963
1964 static bool isFunctionEnvironment(const JSObject& env) {
1965 return env.is<CallObject>();
1966 }
1967
1968 static bool isNonExtensibleLexicalEnvironment(const JSObject& env) {
1969 return env.is<ScopedLexicalEnvironmentObject>();
1970 }
1971
1972 static Scope* getEnvironmentScope(const JSObject& env) {
1973 if (isFunctionEnvironment(env)) {
1974 return env.as<CallObject>().callee().nonLazyScript()->bodyScope();
1975 }
1976 if (env.is<ModuleEnvironmentObject>()) {
1977 JSScript* script =
1978 env.as<ModuleEnvironmentObject>().module().maybeScript();
1979 return script ? script->bodyScope() : nullptr;
1980 }
1981 if (isNonExtensibleLexicalEnvironment(env)) {
1982 return &env.as<ScopedLexicalEnvironmentObject>().scope();
1983 }
1984 if (env.is<VarEnvironmentObject>()) {
1985 return &env.as<VarEnvironmentObject>().scope();
1986 }
1987 if (env.is<WasmInstanceEnvironmentObject>()) {
1988 return &env.as<WasmInstanceEnvironmentObject>().scope();
1989 }
1990 if (env.is<WasmFunctionCallObject>()) {
1991 return &env.as<WasmFunctionCallObject>().scope();
1992 }
1993 if (env.is<GlobalLexicalEnvironmentObject>()) {
1994 return &env.as<GlobalLexicalEnvironmentObject>()
1995 .global()
1996 .emptyGlobalScope();
1997 }
1998 return nullptr;
1999 }
2000
2001 friend Scope* js::GetEnvironmentScope(const JSObject& env);
2002
2003 /*
2004 * In theory, every non-arrow function scope contains an 'arguments'
2005 * bindings. However, the engine only adds a binding if 'arguments' is
2006 * used in the function body. Thus, from the debugger's perspective,
2007 * 'arguments' may be missing from the list of bindings.
2008 */
2009 static bool isMissingArgumentsBinding(EnvironmentObject& env) {
2010 return isFunctionEnvironment(env) &&
2011 !env.as<CallObject>().callee().baseScript()->needsArgsObj();
2012 }
2013
2014 /*
2015 * Similar to 'arguments' above, we don't add a 'this' binding to
2016 * non-arrow functions if it's not used.
2017 */
2018 static bool isMissingThisBinding(EnvironmentObject& env) {
2019 return isFunctionEnvironmentWithThis(env) &&
2020 !env.as<CallObject>()
2021 .callee()
2022 .baseScript()
2023 ->functionHasThisBinding();
2024 }
2025
2026 /*
2027 * This function checks if an arguments object needs to be created when
2028 * the debugger requests 'arguments' for a function scope where the
2029 * arguments object was not otherwise needed.
2030 */
2031 static bool isMissingArguments(JSContext* cx, jsid id,
2032 EnvironmentObject& env) {
2033 return isArguments(cx, id) && isMissingArgumentsBinding(env);
2034 }
2035 static bool isMissingThis(JSContext* cx, jsid id, EnvironmentObject& env) {
2036 return isThis(cx, id) && isMissingThisBinding(env);
2037 }
2038
2039 /*
2040 * If the value of |this| is requested before the this-binding has been
2041 * initialized by JSOp::FunctionThis, the this-binding will be |undefined|.
2042 * In that case, we have to call createMissingThis to initialize the
2043 * this-binding.
2044 *
2045 * Note that an |undefined| this-binding is perfectly valid in strict-mode
2046 * code, but that's fine: createMissingThis will do the right thing in that
2047 * case.
2048 */
2049 static bool isMaybeUninitializedThisValue(JSContext* cx, jsid id,
2050 const Value& v) {
2051 return isThis(cx, id) && v.isUndefined();
2052 }
2053
2054 /*
2055 * Create a missing arguments object. If the function returns true but
2056 * argsObj is null, it means the env is dead.
2057 */
2058 static bool createMissingArguments(JSContext* cx, EnvironmentObject& env,
2059 MutableHandle<ArgumentsObject*> argsObj) {
2060 argsObj.set(nullptr);
2061
2062 LiveEnvironmentVal* maybeEnv = DebugEnvironments::hasLiveEnvironment(env);
2063 if (!maybeEnv) {
2064 return true;
2065 }
2066
2067 argsObj.set(ArgumentsObject::createUnexpected(cx, maybeEnv->frame()));
2068 return !!argsObj;
2069 }
2070
2071 /*
2072 * Create a missing this Value. If the function returns true but
2073 * *success is false, it means the scope is dead.
2074 */
2075 static bool createMissingThis(JSContext* cx, EnvironmentObject& env,
2076 MutableHandleValue thisv, bool* success) {
2077 *success = false;
2078
2079 LiveEnvironmentVal* maybeEnv = DebugEnvironments::hasLiveEnvironment(env);
2080 if (!maybeEnv) {
2081 return true;
2082 }
2083
2084 if (!GetFunctionThis(cx, maybeEnv->frame(), thisv)) {
2085 return false;
2086 }
2087
2088 // Update the this-argument to avoid boxing primitive |this| more
2089 // than once.
2090 maybeEnv->frame().thisArgument() = thisv;
2091 *success = true;
2092 return true;
2093 }
2094
2095 static void reportOptimizedOut(JSContext* cx, HandleId id) {
2096 if (isThis(cx, id)) {
2097 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
2098 JSMSG_DEBUG_OPTIMIZED_OUT, "this");
2099 return;
2100 }
2101
2102 if (UniqueChars printable =
2103 IdToPrintableUTF8(cx, id, IdToPrintableBehavior::IdIsIdentifier)) {
2104 JS_ReportErrorNumberUTF8(cx, GetErrorMessage, nullptr,
2105 JSMSG_DEBUG_OPTIMIZED_OUT, printable.get());
2106 }
2107 }
2108
2109 public:
2110 static const char family;
2111 static const DebugEnvironmentProxyHandler singleton;
2112
2113 constexpr DebugEnvironmentProxyHandler()
2114 : NurseryAllocableProxyHandler(&family) {}
2115
2116 static bool isFunctionEnvironmentWithThis(const JSObject& env) {
2117 // All functions except arrows should have their own this binding.
2118 return isFunctionEnvironment(env) &&
2119 !env.as<CallObject>().callee().hasLexicalThis();
2120 }
2121
2122 bool getPrototypeIfOrdinary(JSContext* cx, HandleObject proxy,
2123 bool* isOrdinary,
2124 MutableHandleObject protop) const override {
2125 MOZ_CRASH(
2126 "shouldn't be possible to access the prototype chain of a "
2127 "DebugEnvironmentProxyHandler");
2128 }
2129
2130 bool preventExtensions(JSContext* cx, HandleObject proxy,
2131 ObjectOpResult& result) const override {
2132 // always [[Extensible]], can't be made non-[[Extensible]], like most
2133 // proxies
2134 return result.fail(JSMSG_CANT_CHANGE_EXTENSIBILITY);
2135 }
2136
2137 bool isExtensible(JSContext* cx, HandleObject proxy,
2138 bool* extensible) const override {
2139 // See above.
2140 *extensible = true;
2141 return true;
2142 }
2143
2144 bool getMissingArgumentsPropertyDescriptor(
2145 JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
2146 EnvironmentObject& env,
2147 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) const {
2148 Rooted<ArgumentsObject*> argsObj(cx);
2149 if (!createMissingArguments(cx, env, &argsObj)) {
2150 return false;
2151 }
2152
2153 if (!argsObj) {
2154 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2155 JSMSG_DEBUG_NOT_ON_STACK, "Debugger scope");
2156 return false;
2157 }
2158
2159 desc.set(mozilla::Some(PropertyDescriptor::Data(
2160 ObjectValue(*argsObj), {JS::PropertyAttribute::Enumerable})));
2161 return true;
2162 }
2163 bool getMissingThisPropertyDescriptor(
2164 JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
2165 EnvironmentObject& env,
2166 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) const {
2167 RootedValue thisv(cx);
2168 bool success;
2169 if (!createMissingThis(cx, env, &thisv, &success)) {
2170 return false;
2171 }
2172
2173 if (!success) {
2174 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2175 JSMSG_DEBUG_NOT_ON_STACK, "Debugger scope");
2176 return false;
2177 }
2178
2179 desc.set(mozilla::Some(
2180 PropertyDescriptor::Data(thisv, {JS::PropertyAttribute::Enumerable})));
2181 return true;
2182 }
2183
2184 bool getOwnPropertyDescriptor(
2185 JSContext* cx, HandleObject proxy, HandleId id,
2186 MutableHandle<mozilla::Maybe<PropertyDescriptor>> desc) const override {
2187 Rooted<DebugEnvironmentProxy*> debugEnv(
2188 cx, &proxy->as<DebugEnvironmentProxy>());
2189 Rooted<EnvironmentObject*> env(cx, &debugEnv->environment());
2190
2191 if (isMissingArguments(cx, id, *env)) {
2192 return getMissingArgumentsPropertyDescriptor(cx, debugEnv, *env, desc);
2193 }
2194
2195 if (isMissingThis(cx, id, *env)) {
2196 return getMissingThisPropertyDescriptor(cx, debugEnv, *env, desc);
2197 }
2198
2199 RootedValue v(cx);
2200 AccessResult access;
2201 if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, &v, &access)) {
2202 return false;
2203 }
2204
2205 switch (access) {
2206 case ACCESS_UNALIASED: {
2207 desc.set(mozilla::Some(
2208 PropertyDescriptor::Data(v, {JS::PropertyAttribute::Enumerable})));
2209 return true;
2210 }
2211 case ACCESS_GENERIC:
2212 return GetOwnPropertyDescriptor(cx, env, id, desc);
2213 case ACCESS_LOST:
2214 reportOptimizedOut(cx, id);
2215 return false;
2216 default:
2217 MOZ_CRASH("bad AccessResult");
2218 }
2219 }
2220
2221 bool getMissingArguments(JSContext* cx, EnvironmentObject& env,
2222 MutableHandleValue vp) const {
2223 Rooted<ArgumentsObject*> argsObj(cx);
2224 if (!createMissingArguments(cx, env, &argsObj)) {
2225 return false;
2226 }
2227
2228 if (!argsObj) {
2229 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2230 JSMSG_DEBUG_NOT_ON_STACK, "Debugger env");
2231 return false;
2232 }
2233
2234 vp.setObject(*argsObj);
2235 return true;
2236 }
2237
2238 bool getMissingThis(JSContext* cx, EnvironmentObject& env,
2239 MutableHandleValue vp) const {
2240 RootedValue thisv(cx);
2241 bool success;
2242 if (!createMissingThis(cx, env, &thisv, &success)) {
2243 return false;
2244 }
2245
2246 if (!success) {
2247 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2248 JSMSG_DEBUG_NOT_ON_STACK, "Debugger env");
2249 return false;
2250 }
2251
2252 vp.set(thisv);
2253 return true;
2254 }
2255
2256 bool get(JSContext* cx, HandleObject proxy, HandleValue receiver, HandleId id,
2257 MutableHandleValue vp) const override {
2258 Rooted<DebugEnvironmentProxy*> debugEnv(
2259 cx, &proxy->as<DebugEnvironmentProxy>());
2260 Rooted<EnvironmentObject*> env(
2261 cx, &proxy->as<DebugEnvironmentProxy>().environment());
2262
2263 if (isMissingArguments(cx, id, *env)) {
2264 return getMissingArguments(cx, *env, vp);
2265 }
2266
2267 if (isMissingThis(cx, id, *env)) {
2268 return getMissingThis(cx, *env, vp);
2269 }
2270
2271 AccessResult access;
2272 if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, vp, &access)) {
2273 return false;
2274 }
2275
2276 switch (access) {
2277 case ACCESS_UNALIASED:
2278 if (isMaybeUninitializedThisValue(cx, id, vp)) {
2279 return getMissingThis(cx, *env, vp);
2280 }
2281 return true;
2282 case ACCESS_GENERIC:
2283 if (!GetProperty(cx, env, env, id, vp)) {
2284 return false;
2285 }
2286 if (isMaybeUninitializedThisValue(cx, id, vp)) {
2287 return getMissingThis(cx, *env, vp);
2288 }
2289 return true;
2290 case ACCESS_LOST:
2291 reportOptimizedOut(cx, id);
2292 return false;
2293 default:
2294 MOZ_CRASH("bad AccessResult");
2295 }
2296 }
2297
2298 bool getMissingArgumentsMaybeSentinelValue(JSContext* cx,
2299 EnvironmentObject& env,
2300 MutableHandleValue vp) const {
2301 Rooted<ArgumentsObject*> argsObj(cx);
2302 if (!createMissingArguments(cx, env, &argsObj)) {
2303 return false;
2304 }
2305 vp.set(argsObj ? ObjectValue(*argsObj) : MagicValue(JS_MISSING_ARGUMENTS));
2306 return true;
2307 }
2308
2309 bool getMissingThisMaybeSentinelValue(JSContext* cx, EnvironmentObject& env,
2310 MutableHandleValue vp) const {
2311 RootedValue thisv(cx);
2312 bool success;
2313 if (!createMissingThis(cx, env, &thisv, &success)) {
2314 return false;
2315 }
2316 vp.set(success ? thisv : MagicValue(JS_OPTIMIZED_OUT));
2317 return true;
2318 }
2319
2320 /*
2321 * Like 'get', but returns sentinel values instead of throwing on
2322 * exceptional cases.
2323 */
2324 bool getMaybeSentinelValue(JSContext* cx,
2325 Handle<DebugEnvironmentProxy*> debugEnv,
2326 HandleId id, MutableHandleValue vp) const {
2327 Rooted<EnvironmentObject*> env(cx, &debugEnv->environment());
2328
2329 if (isMissingArguments(cx, id, *env)) {
2330 return getMissingArgumentsMaybeSentinelValue(cx, *env, vp);
2331 }
2332 if (isMissingThis(cx, id, *env)) {
2333 return getMissingThisMaybeSentinelValue(cx, *env, vp);
2334 }
2335
2336 AccessResult access;
2337 if (!handleUnaliasedAccess(cx, debugEnv, env, id, GET, vp, &access)) {
2338 return false;
2339 }
2340
2341 switch (access) {
2342 case ACCESS_UNALIASED:
2343 if (isMaybeUninitializedThisValue(cx, id, vp)) {
2344 return getMissingThisMaybeSentinelValue(cx, *env, vp);
2345 }
2346 return true;
2347 case ACCESS_GENERIC:
2348 if (!GetProperty(cx, env, env, id, vp)) {
2349 return false;
2350 }
2351 if (isMaybeUninitializedThisValue(cx, id, vp)) {
2352 return getMissingThisMaybeSentinelValue(cx, *env, vp);
2353 }
2354 return true;
2355 case ACCESS_LOST:
2356 vp.setMagic(JS_OPTIMIZED_OUT);
2357 return true;
2358 default:
2359 MOZ_CRASH("bad AccessResult");
2360 }
2361 }
2362
2363 bool set(JSContext* cx, HandleObject proxy, HandleId id, HandleValue v,
2364 HandleValue receiver, ObjectOpResult& result) const override {
2365 Rooted<DebugEnvironmentProxy*> debugEnv(
2366 cx, &proxy->as<DebugEnvironmentProxy>());
2367 Rooted<EnvironmentObject*> env(
2368 cx, &proxy->as<DebugEnvironmentProxy>().environment());
2369
2370 if (debugEnv->isOptimizedOut()) {
2371 return Throw(cx, id, JSMSG_DEBUG_CANT_SET_OPT_ENV);
2372 }
2373
2374 AccessResult access;
2375 RootedValue valCopy(cx, v);
2376 if (!handleUnaliasedAccess(cx, debugEnv, env, id, SET, &valCopy, &access)) {
2377 return false;
2378 }
2379
2380 switch (access) {
2381 case ACCESS_UNALIASED:
2382 return result.succeed();
2383 case ACCESS_GENERIC: {
2384 RootedValue envVal(cx, ObjectValue(*env));
2385 RootedValue initialVal(cx);
2386 if (!GetProperty(cx, env, env, id, &initialVal)) {
2387 return false;
2388 }
2389 // Note: initialVal could be JS_OPTIMIZED_OUT, which is why we don't use
2390 // .whyMagic(JS_UNINITALIZED_LEXICAL).
2391 if (initialVal.isMagic() &&
2392 initialVal.whyMagic() == JS_UNINITIALIZED_LEXICAL) {
2393 ReportRuntimeLexicalErrorId(cx, JSMSG_UNINITIALIZED_LEXICAL, id);
2394 return false;
2395 }
2396
2397 return SetProperty(cx, env, id, v, envVal, result);
2398 }
2399 default:
2400 MOZ_CRASH("bad AccessResult");
2401 }
2402 }
2403
2404 bool defineProperty(JSContext* cx, HandleObject proxy, HandleId id,
2405 Handle<PropertyDescriptor> desc,
2406 ObjectOpResult& result) const override {
2407 Rooted<EnvironmentObject*> env(
2408 cx, &proxy->as<DebugEnvironmentProxy>().environment());
2409
2410 bool found;
2411 if (!has(cx, proxy, id, &found)) {
2412 return false;
2413 }
2414 if (found) {
2415 return Throw(cx, id, JSMSG_CANT_REDEFINE_PROP);
2416 }
2417
2418 return JS_DefinePropertyById(cx, env, id, desc, result);
2419 }
2420
2421 bool ownPropertyKeys(JSContext* cx, HandleObject proxy,
2422 MutableHandleIdVector props) const override {
2423 Rooted<EnvironmentObject*> env(
2424 cx, &proxy->as<DebugEnvironmentProxy>().environment());
2425
2426 if (isMissingArgumentsBinding(*env)) {
2427 if (!props.append(NameToId(cx->names().arguments))) {
2428 return false;
2429 }
2430 }
2431 if (isMissingThisBinding(*env)) {
2432 if (!props.append(NameToId(cx->names().dot_this_))) {
2433 return false;
2434 }
2435 }
2436
2437 // WithEnvironmentObject isn't a very good proxy. It doesn't have a
2438 // JSNewEnumerateOp implementation, because if it just delegated to the
2439 // target object, the object would indicate that native enumeration is
2440 // the thing to do, but native enumeration over the WithEnvironmentObject
2441 // wrapper yields no properties. So instead here we hack around the
2442 // issue: punch a hole through to the with object target, then manually
2443 // examine @@unscopables.
2444 RootedObject target(cx);
2445 bool isWith = env->is<WithEnvironmentObject>();
2446 if (isWith) {
2447 target = &env->as<WithEnvironmentObject>().object();
2448 } else {
2449 target = env;
2450 }
2451 if (!GetPropertyKeys(cx, target, JSITER_OWNONLY, props)) {
2452 return false;
2453 }
2454
2455 if (isWith) {
2456 size_t j = 0;
2457 bool supportUnscopables =
2458 env->as<WithEnvironmentObject>().supportUnscopables();
2459 for (size_t i = 0; i < props.length(); i++) {
2460 bool inScope = true;
2461 if (supportUnscopables &&
2462 !CheckUnscopables(cx, env, props[i], &inScope)) {
2463 return false;
2464 }
2465 if (inScope) {
2466 props[j++].set(props[i]);
2467 }
2468 }
2469 if (!props.resize(j)) {
2470 return false;
2471 }
2472 }
2473
2474 /*
2475 * Environments with Scopes are optimized to not contain unaliased
2476 * variables so they must be manually appended here.
2477 */
2478 if (Scope* scope = getEnvironmentScope(*env)) {
2479 for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
2480 if (!bi.closedOver() &&
2481 !props.append(NameToId(bi.name()->asPropertyName()))) {
2482 return false;
2483 }
2484 }
2485 }
2486
2487 return true;
2488 }
2489
2490 bool has(JSContext* cx, HandleObject proxy, HandleId id_,
2491 bool* bp) const override {
2492 RootedId id(cx, id_);
2493 EnvironmentObject& envObj =
2494 proxy->as<DebugEnvironmentProxy>().environment();
2495
2496 if (isArguments(cx, id) && isFunctionEnvironment(envObj)) {
2497 *bp = true;
2498 return true;
2499 }
2500
2501 // Be careful not to look up '.this' as a normal binding below, it will
2502 // assert in with_HasProperty.
2503 if (isThis(cx, id)) {
2504 *bp = isFunctionEnvironmentWithThis(envObj);
2505 return true;
2506 }
2507
2508 bool found;
2509 RootedObject env(cx, &envObj);
2510 if (!JS_HasPropertyById(cx, env, id, &found)) {
2511 return false;
2512 }
2513
2514 if (!found) {
2515 if (Scope* scope = getEnvironmentScope(*env)) {
2516 for (BindingIter bi(scope); bi; bi++) {
2517 if (!bi.closedOver() && NameToId(bi.name()->asPropertyName()) == id) {
2518 found = true;
2519 break;
2520 }
2521 }
2522 }
2523 }
2524
2525 *bp = found;
2526 return true;
2527 }
2528
2529 bool delete_(JSContext* cx, HandleObject proxy, HandleId id,
2530 ObjectOpResult& result) const override {
2531 return result.fail(JSMSG_CANT_DELETE);
2532 }
2533 };
2534
2535 } /* anonymous namespace */
2536
2537 Scope* js::GetEnvironmentScope(const JSObject& env) {
2538 return DebugEnvironmentProxyHandler::getEnvironmentScope(env);
2539 }
2540
2541 template <>
2542 bool JSObject::is<js::DebugEnvironmentProxy>() const {
2543 return IsDerivedProxyObject(this, &DebugEnvironmentProxyHandler::singleton);
2544 }
2545
2546 const char DebugEnvironmentProxyHandler::family = 0;
2547 const DebugEnvironmentProxyHandler DebugEnvironmentProxyHandler::singleton;
2548
2549 /* static */
2550 DebugEnvironmentProxy* DebugEnvironmentProxy::create(JSContext* cx,
2551 EnvironmentObject& env,
2552 HandleObject enclosing) {
2553 MOZ_ASSERT(env.realm() == cx->realm());
2554 MOZ_ASSERT(!enclosing->is<EnvironmentObject>());
2555
2556 RootedValue priv(cx, ObjectValue(env));
2557 JSObject* obj = NewProxyObject(cx, &DebugEnvironmentProxyHandler::singleton,
2558 priv, nullptr /* proto */);
2559 if (!obj) {
2560 return nullptr;
2561 }
2562
2563 DebugEnvironmentProxy* debugEnv = &obj->as<DebugEnvironmentProxy>();
2564 debugEnv->setReservedSlot(ENCLOSING_SLOT, ObjectValue(*enclosing));
2565 debugEnv->setReservedSlot(SNAPSHOT_SLOT, NullValue());
2566
2567 return debugEnv;
2568 }
2569
2570 EnvironmentObject& DebugEnvironmentProxy::environment() const {
2571 return target()->as<EnvironmentObject>();
2572 }
2573
2574 JSObject& DebugEnvironmentProxy::enclosingEnvironment() const {
2575 return reservedSlot(ENCLOSING_SLOT).toObject();
2576 }
2577
2578 ArrayObject* DebugEnvironmentProxy::maybeSnapshot() const {
2579 JSObject* obj = reservedSlot(SNAPSHOT_SLOT).toObjectOrNull();
2580 return obj ? &obj->as<ArrayObject>() : nullptr;
2581 }
2582
2583 void DebugEnvironmentProxy::initSnapshot(ArrayObject& o) {
2584 #ifdef DEBUG
2585 if (maybeSnapshot()) {
2586 auto* callObj = CallObject::find(&environment());
2587 if (callObj) {
2588 MOZ_ASSERT(callObj->callee().isGeneratorOrAsync());
2589 } else {
2590 auto* moduleEnv = ModuleEnvironmentObject::find(&environment());
2591 MOZ_ASSERT(moduleEnv);
2592 MOZ_ASSERT(moduleEnv->module().hasTopLevelAwait());
2593 }
2594 }
2595 #endif
2596
2597 setReservedSlot(SNAPSHOT_SLOT, ObjectValue(o));
2598 }
2599
2600 bool DebugEnvironmentProxy::isForDeclarative() const {
2601 EnvironmentObject& e = environment();
2602 return e.is<CallObject>() || e.is<VarEnvironmentObject>() ||
2603 e.is<ModuleEnvironmentObject>() ||
2604 e.is<WasmInstanceEnvironmentObject>() ||
2605 e.is<WasmFunctionCallObject>() || e.is<LexicalEnvironmentObject>();
2606 }
2607
2608 /* static */
2609 bool DebugEnvironmentProxy::getMaybeSentinelValue(
2610 JSContext* cx, Handle<DebugEnvironmentProxy*> env, HandleId id,
2611 MutableHandleValue vp) {
2612 return DebugEnvironmentProxyHandler::singleton.getMaybeSentinelValue(cx, env,
2613 id, vp);
2614 }
2615
2616 bool DebugEnvironmentProxy::isFunctionEnvironmentWithThis() {
2617 return DebugEnvironmentProxyHandler::isFunctionEnvironmentWithThis(
2618 environment());
2619 }
2620
2621 bool DebugEnvironmentProxy::isOptimizedOut() const {
2622 EnvironmentObject& e = environment();
2623
2624 if (DebugEnvironments::hasLiveEnvironment(e)) {
2625 return false;
2626 }
2627
2628 if (e.is<LexicalEnvironmentObject>()) {
2629 return e.is<BlockLexicalEnvironmentObject>() &&
2630 !e.as<BlockLexicalEnvironmentObject>().scope().hasEnvironment();
2631 }
2632
2633 if (e.is<CallObject>()) {
2634 return !e.as<CallObject>().callee().needsCallObject() && !maybeSnapshot();
2635 }
2636
2637 return false;
2638 }
2639
2640 /*****************************************************************************/
2641
2642 [[nodiscard]] static bool GetFrameEnvironmentAndScope(
2643 JSContext* cx, AbstractFramePtr frame, const jsbytecode* pc,
2644 MutableHandleObject env, MutableHandle<Scope*> scope);
2645
2646 DebugEnvironments::DebugEnvironments(JSContext* cx, Zone* zone)
2647 : zone_(zone),
2648 proxiedEnvs(cx),
2649 missingEnvs(cx->zone()),
2650 liveEnvs(cx->zone()) {}
2651
2652 DebugEnvironments::~DebugEnvironments() { MOZ_ASSERT(missingEnvs.empty()); }
2653
2654 void DebugEnvironments::trace(JSTracer* trc) { proxiedEnvs.trace(trc); }
2655
2656 void DebugEnvironments::traceWeak(JSTracer* trc) {
2657 /*
2658 * missingEnvs points to debug envs weakly so that debug envs can be
2659 * released more eagerly.
2660 */
2661 for (MissingEnvironmentMap::Enum e(missingEnvs); !e.empty(); e.popFront()) {
2662 auto result =
2663 TraceWeakEdge(trc, &e.front().value(), "MissingEnvironmentMap value");
2664 if (result.isDead()) {
2665 /*
2666 * Note that onPopCall, onPopVar, and onPopLexical rely on missingEnvs to
2667 * find environment objects that we synthesized for the debugger's sake,
2668 * and clean up the synthetic environment objects' entries in liveEnvs.
2669 * So if we remove an entry from missingEnvs here, we must also remove the
2670 * corresponding liveEnvs entry.
2671 *
2672 * Since the DebugEnvironmentProxy is the only thing using its environment
2673 * object, and the DSO is about to be finalized, you might assume that the
2674 * synthetic SO is also about to be finalized too, and thus the loop below
2675 * will take care of things. But complex GC behavior means that marks are
2676 * only conservative approximations of liveness; we should assume that
2677 * anything could be marked.
2678 *
2679 * Thus, we must explicitly remove the entries from both liveEnvs and
2680 * missingEnvs here.
2681 */
2682 liveEnvs.remove(&result.initialTarget()->environment());
2683 e.removeFront();
2684 } else {
2685 MissingEnvironmentKey key = e.front().key();
2686 Scope* scope = key.scope();
2687 MOZ_ALWAYS_TRUE(TraceManuallyBarrieredWeakEdge(
2688 trc, &scope, "MissingEnvironmentKey scope"));
2689 if (scope != key.scope()) {
2690 key.updateScope(scope);
2691 e.rekeyFront(key);
2692 }
2693 }
2694 }
2695
2696 /*
2697 * Scopes can be finalized when a debugger-synthesized EnvironmentObject is
2698 * no longer reachable via its DebugEnvironmentProxy.
2699 */
2700 liveEnvs.traceWeak(trc);
2701 }
2702
2703 void DebugEnvironments::finish() { proxiedEnvs.clear(); }
2704
2705 #ifdef JSGC_HASH_TABLE_CHECKS
2706 void DebugEnvironments::checkHashTablesAfterMovingGC() {
2707 /*
2708 * This is called at the end of StoreBuffer::mark() to check that our
2709 * postbarriers have worked and that no hashtable keys (or values) are left
2710 * pointing into the nursery.
2711 *
2712 * |proxiedEnvs| is checked automatically because it is a WeakMap.
2713 */
2714 CheckTableAfterMovingGC(missingEnvs, [this](const auto& entry) {
2715 CheckGCThingAfterMovingGC(entry.key().scope(), zone());
2716 // Use unbarrieredGet() to prevent triggering read barrier while collecting.
2717 CheckGCThingAfterMovingGC(entry.value().unbarrieredGet(), zone());
2718 return entry.key();
2719 });
2720 CheckTableAfterMovingGC(liveEnvs, [this](const auto& entry) {
2721 CheckGCThingAfterMovingGC(entry.key(), zone());
2722 CheckGCThingAfterMovingGC(entry.value().scope_.get(), zone());
2723 return entry.key().unbarrieredGet();
2724 });
2725 }
2726 #endif
2727
2728 /*
2729 * Unfortunately, GetDebugEnvironmentForFrame needs to work even outside debug
2730 * mode (in particular, JS_GetFrameScopeChain does not require debug mode).
2731 * Since DebugEnvironments::onPop* are only called in debuggee frames, this
2732 * means we cannot use any of the maps in DebugEnvironments. This will produce
2733 * debug scope chains that do not obey the debugger invariants but that is just
2734 * fine.
2735 */
2736 static bool CanUseDebugEnvironmentMaps(JSContext* cx) {
2737 return cx->realm()->isDebuggee();
2738 }
2739
2740 DebugEnvironments* DebugEnvironments::ensureRealmData(JSContext* cx) {
2741 Realm* realm = cx->realm();
2742 if (auto* debugEnvs = realm->debugEnvs()) {
2743 return debugEnvs;
2744 }
2745
2746 auto debugEnvs = cx->make_unique<DebugEnvironments>(cx, cx->zone());
2747 if (!debugEnvs) {
2748 return nullptr;
2749 }
2750
2751 realm->debugEnvsRef() = std::move(debugEnvs);
2752 return realm->debugEnvs();
2753 }
2754
2755 /* static */
2756 DebugEnvironmentProxy* DebugEnvironments::hasDebugEnvironment(
2757 JSContext* cx, EnvironmentObject& env) {
2758 DebugEnvironments* envs = env.realm()->debugEnvs();
2759 if (!envs) {
2760 return nullptr;
2761 }
2762
2763 if (JSObject* obj = envs->proxiedEnvs.get(&env)) {
2764 MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
2765 return &obj->as<DebugEnvironmentProxy>();
2766 }
2767
2768 return nullptr;
2769 }
2770
2771 /* static */
2772 bool DebugEnvironments::addDebugEnvironment(
2773 JSContext* cx, Handle<EnvironmentObject*> env,
2774 Handle<DebugEnvironmentProxy*> debugEnv) {
2775 MOZ_ASSERT(cx->realm() == env->realm());
2776 MOZ_ASSERT(cx->realm() == debugEnv->nonCCWRealm());
2777
2778 if (!CanUseDebugEnvironmentMaps(cx)) {
2779 return true;
2780 }
2781
2782 DebugEnvironments* envs = ensureRealmData(cx);
2783 if (!envs) {
2784 return false;
2785 }
2786
2787 if (!envs->proxiedEnvs.put(env, debugEnv)) {
2788 ReportOutOfMemory(cx);
2789 return false;
2790 }
2791
2792 return true;
2793 }
2794
2795 /* static */
2796 DebugEnvironmentProxy* DebugEnvironments::hasDebugEnvironment(
2797 JSContext* cx, const EnvironmentIter& ei) {
2798 MOZ_ASSERT(!ei.hasSyntacticEnvironment());
2799
2800 DebugEnvironments* envs = cx->realm()->debugEnvs();
2801 if (!envs) {
2802 return nullptr;
2803 }
2804
2805 if (MissingEnvironmentMap::Ptr p =
2806 envs->missingEnvs.lookup(MissingEnvironmentKey(ei))) {
2807 MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
2808 return p->value();
2809 }
2810 return nullptr;
2811 }
2812
2813 /* static */
2814 bool DebugEnvironments::addDebugEnvironment(
2815 JSContext* cx, const EnvironmentIter& ei,
2816 Handle<DebugEnvironmentProxy*> debugEnv) {
2817 MOZ_ASSERT(!ei.hasSyntacticEnvironment());
2818 MOZ_ASSERT(cx->realm() == debugEnv->nonCCWRealm());
2819
2820 if (!CanUseDebugEnvironmentMaps(cx)) {
2821 return true;
2822 }
2823
2824 DebugEnvironments* envs = ensureRealmData(cx);
2825 if (!envs) {
2826 return false;
2827 }
2828
2829 MissingEnvironmentKey key(ei);
2830 MOZ_ASSERT(!envs->missingEnvs.has(key));
2831 if (!envs->missingEnvs.put(key,
2832 WeakHeapPtr<DebugEnvironmentProxy*>(debugEnv))) {
2833 ReportOutOfMemory(cx);
2834 return false;
2835 }
2836
2837 // Only add to liveEnvs if we synthesized the debug env on a live
2838 // frame.
2839 if (ei.withinInitialFrame()) {
2840 MOZ_ASSERT(!envs->liveEnvs.has(&debugEnv->environment()));
2841 if (!envs->liveEnvs.put(&debugEnv->environment(), LiveEnvironmentVal(ei))) {
2842 ReportOutOfMemory(cx);
2843 return false;
2844 }
2845 }
2846
2847 return true;
2848 }
2849
2850 /* static */
2851 void DebugEnvironments::takeFrameSnapshot(
2852 JSContext* cx, Handle<DebugEnvironmentProxy*> debugEnv,
2853 AbstractFramePtr frame) {
2854 /*
2855 * When the JS stack frame is popped, the values of unaliased variables
2856 * are lost. If there is any debug env referring to this environment, save a
2857 * copy of the unaliased variables' values in an array for later debugger
2858 * access via DebugEnvironmentProxy::handleUnaliasedAccess.
2859 *
2860 * Note: since it is simplest for this function to be infallible, failure
2861 * in this code will be silently ignored. This does not break any
2862 * invariants since DebugEnvironmentProxy::maybeSnapshot can already be
2863 * nullptr.
2864 */
2865
2866 // Because this can be called during exception unwinding, save the exception
2867 // state and restore it when we're done.
2868 JS::AutoSaveExceptionState ases(cx);
2869
2870 JSScript* script = frame.script();
2871
2872 // Act like no snapshot was taken if we run OOM while taking the snapshot.
2873 Rooted<GCVector<Value>> vec(cx, GCVector<Value>(cx));
2874 if (debugEnv->environment().is<CallObject>()) {
2875 FunctionScope* scope = &script->bodyScope()->as<FunctionScope>();
2876 uint32_t frameSlotCount = scope->nextFrameSlot();
2877 MOZ_ASSERT(frameSlotCount <= script->nfixed());
2878
2879 // For simplicity, copy all frame slots from 0 to the frameSlotCount,
2880 // even if we don't need all of them (like in the case of a defaults
2881 // parameter scope having frame slots).
2882 uint32_t numFormals = frame.numFormalArgs();
2883 if (!vec.resize(numFormals + frameSlotCount)) {
2884 cx->recoverFromOutOfMemory();
2885 return;
2886 }
2887 mozilla::PodCopy(vec.begin(), frame.argv(), numFormals);
2888 for (uint32_t slot = 0; slot < frameSlotCount; slot++) {
2889 vec[slot + frame.numFormalArgs()].set(frame.unaliasedLocal(slot));
2890 }
2891
2892 /*
2893 * Copy in formals that are not aliased via the scope chain
2894 * but are aliased via the arguments object.
2895 */
2896 if (script->needsArgsObj() && frame.hasArgsObj()) {
2897 for (unsigned i = 0; i < frame.numFormalArgs(); ++i) {
2898 if (script->formalLivesInArgumentsObject(i)) {
2899 vec[i].set(frame.argsObj().arg(i));
2900 }
2901 }
2902 }
2903 } else {
2904 uint32_t frameSlotStart;
2905 uint32_t frameSlotEnd;
2906
2907 if (debugEnv->environment().is<BlockLexicalEnvironmentObject>()) {
2908 LexicalScope* scope =
2909 &debugEnv->environment().as<BlockLexicalEnvironmentObject>().scope();
2910 frameSlotStart = scope->firstFrameSlot();
2911 frameSlotEnd = scope->nextFrameSlot();
2912 } else if (debugEnv->environment()
2913 .is<ClassBodyLexicalEnvironmentObject>()) {
2914 ClassBodyScope* scope = &debugEnv->environment()
2915 .as<ClassBodyLexicalEnvironmentObject>()
2916 .scope();
2917 frameSlotStart = scope->firstFrameSlot();
2918 frameSlotEnd = scope->nextFrameSlot();
2919 } else if (debugEnv->environment().is<VarEnvironmentObject>()) {
2920 VarEnvironmentObject* env =
2921 &debugEnv->environment().as<VarEnvironmentObject>();
2922 if (frame.isFunctionFrame()) {
2923 VarScope* scope = &env->scope().as<VarScope>();
2924 frameSlotStart = scope->firstFrameSlot();
2925 frameSlotEnd = scope->nextFrameSlot();
2926 } else {
2927 EvalScope* scope = &env->scope().as<EvalScope>();
2928 MOZ_ASSERT(scope == script->bodyScope());
2929 frameSlotStart = 0;
2930 frameSlotEnd = scope->nextFrameSlot();
2931 }
2932 } else {
2933 MOZ_ASSERT(&debugEnv->environment().as<ModuleEnvironmentObject>() ==
2934 script->module()->environment());
2935 ModuleScope* scope = &script->bodyScope()->as<ModuleScope>();
2936 frameSlotStart = 0;
2937 frameSlotEnd = scope->nextFrameSlot();
2938 }
2939
2940 uint32_t frameSlotCount = frameSlotEnd - frameSlotStart;
2941 MOZ_ASSERT(frameSlotCount <= script->nfixed());
2942
2943 if (!vec.resize(frameSlotCount)) {
2944 cx->recoverFromOutOfMemory();
2945 return;
2946 }
2947 for (uint32_t slot = frameSlotStart; slot < frameSlotCount; slot++) {
2948 vec[slot - frameSlotStart].set(frame.unaliasedLocal(slot));
2949 }
2950 }
2951
2952 if (vec.length() == 0) {
2953 return;
2954 }
2955
2956 /*
2957 * Use a dense array as storage (since proxies do not have trace
2958 * hooks). This array must not escape into the wild.
2959 */
2960 Rooted<ArrayObject*> snapshot(
2961 cx, NewDenseCopiedArray(cx, vec.length(), vec.begin()));
2962 if (!snapshot) {
2963 MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
2964 cx->clearPendingException();
2965 return;
2966 }
2967
2968 debugEnv->initSnapshot(*snapshot);
2969 }
2970
2971 /* static */
2972 void DebugEnvironments::onPopCall(JSContext* cx, AbstractFramePtr frame) {
2973 cx->check(frame);
2974
2975 DebugEnvironments* envs = cx->realm()->debugEnvs();
2976 if (!envs) {
2977 return;
2978 }
2979
2980 Rooted<DebugEnvironmentProxy*> debugEnv(cx, nullptr);
2981
2982 FunctionScope* funScope = &frame.script()->bodyScope()->as<FunctionScope>();
2983 if (funScope->hasEnvironment()) {
2984 MOZ_ASSERT(frame.callee()->needsCallObject());
2985
2986 /*
2987 * The frame may be observed before the prologue has created the
2988 * CallObject. See EnvironmentIter::settle.
2989 */
2990 if (!frame.environmentChain()->is<CallObject>()) {
2991 return;
2992 }
2993
2994 CallObject& callobj = frame.environmentChain()->as<CallObject>();
2995 envs->liveEnvs.remove(&callobj);
2996 if (JSObject* obj = envs->proxiedEnvs.get(&callobj)) {
2997 debugEnv = &obj->as<DebugEnvironmentProxy>();
2998 }
2999 } else {
3000 MissingEnvironmentKey key(frame, funScope);
3001 if (MissingEnvironmentMap::Ptr p = envs->missingEnvs.lookup(key)) {
3002 debugEnv = p->value();
3003 envs->liveEnvs.remove(&debugEnv->environment().as<CallObject>());
3004 envs->missingEnvs.remove(p);
3005 }
3006 }
3007
3008 if (debugEnv) {
3009 DebugEnvironments::takeFrameSnapshot(cx, debugEnv, frame);
3010 }
3011 }
3012
3013 void DebugEnvironments::onPopLexical(JSContext* cx, AbstractFramePtr frame,
3014 const jsbytecode* pc) {
3015 cx->check(frame);
3016
3017 DebugEnvironments* envs = cx->realm()->debugEnvs();
3018 if (!envs) {
3019 return;
3020 }
3021
3022 EnvironmentIter ei(cx, frame, pc);
3023 onPopLexical(cx, ei);
3024 }
3025
3026 template <typename Environment, typename Scope>
3027 void DebugEnvironments::onPopGeneric(JSContext* cx, const EnvironmentIter& ei) {
3028 DebugEnvironments* envs = cx->realm()->debugEnvs();
3029 if (!envs) {
3030 return;
3031 }
3032
3033 MOZ_ASSERT(ei.withinInitialFrame());
3034 MOZ_ASSERT(ei.scope().is<Scope>());
3035
3036 Rooted<Environment*> env(cx);
3037 if (MissingEnvironmentMap::Ptr p =
3038 envs->missingEnvs.lookup(MissingEnvironmentKey(ei))) {
3039 env = &p->value()->environment().as<Environment>();
3040 envs->missingEnvs.remove(p);
3041 } else if (ei.hasSyntacticEnvironment()) {
3042 env = &ei.environment().as<Environment>();
3043 }
3044
3045 if (env) {
3046 envs->liveEnvs.remove(env);
3047
3048 if (JSObject* obj = envs->proxiedEnvs.get(env)) {
3049 Rooted<DebugEnvironmentProxy*> debugEnv(
3050 cx, &obj->as<DebugEnvironmentProxy>());
3051 DebugEnvironments::takeFrameSnapshot(cx, debugEnv, ei.initialFrame());
3052 }
3053 }
3054 }
3055
3056 void DebugEnvironments::onPopLexical(JSContext* cx, const EnvironmentIter& ei) {
3057 if (ei.scope().is<ClassBodyScope>()) {
3058 onPopGeneric<ScopedLexicalEnvironmentObject, ClassBodyScope>(cx, ei);
3059 } else {
3060 onPopGeneric<ScopedLexicalEnvironmentObject, LexicalScope>(cx, ei);
3061 }
3062 }
3063
3064 void DebugEnvironments::onPopVar(JSContext* cx, const EnvironmentIter& ei) {
3065 if (ei.scope().is<EvalScope>()) {
3066 onPopGeneric<VarEnvironmentObject, EvalScope>(cx, ei);
3067 } else {
3068 onPopGeneric<VarEnvironmentObject, VarScope>(cx, ei);
3069 }
3070 }
3071
3072 void DebugEnvironments::onPopWith(AbstractFramePtr frame) {
3073 Realm* realm = frame.realm();
3074 if (DebugEnvironments* envs = realm->debugEnvs()) {
3075 envs->liveEnvs.remove(
3076 &frame.environmentChain()->as<WithEnvironmentObject>());
3077 }
3078 }
3079
3080 void DebugEnvironments::onPopModule(JSContext* cx, const EnvironmentIter& ei) {
3081 onPopGeneric<ModuleEnvironmentObject, ModuleScope>(cx, ei);
3082 }
3083
3084 void DebugEnvironments::onPopWasm(JSContext* cx, AbstractFramePtr frame) {
3085 MOZ_ASSERT(frame.isWasmDebugFrame());
3086
3087 DebugEnvironments* envs = cx->realm()->debugEnvs();
3088 if (!envs) {
3089 return;
3090 }
3091
3092 Rooted<WasmInstanceObject*> instance(cx, frame.wasmInstance()->object());
3093 uint32_t funcIndex = frame.asWasmDebugFrame()->funcIndex();
3094 Rooted<Scope*> wasmFunctionScope(
3095 cx, instance->getExistingFunctionScope(funcIndex));
3096 if (!wasmFunctionScope) {
3097 return;
3098 }
3099
3100 MissingEnvironmentKey key(frame, wasmFunctionScope);
3101 if (MissingEnvironmentMap::Ptr p = envs->missingEnvs.lookup(key)) {
3102 EnvironmentObject& env = p->value()->environment();
3103 envs->liveEnvs.remove(&env);
3104 envs->missingEnvs.remove(p);
3105 }
3106 }
3107
3108 void DebugEnvironments::onRealmUnsetIsDebuggee(Realm* realm) {
3109 if (DebugEnvironments* envs = realm->debugEnvs()) {
3110 envs->proxiedEnvs.clear();
3111 envs->missingEnvs.clear();
3112 envs->liveEnvs.clear();
3113 }
3114 }
3115
3116 bool DebugEnvironments::updateLiveEnvironments(JSContext* cx) {
3117 AutoCheckRecursionLimit recursion(cx);
3118 if (!recursion.check(cx)) {
3119 return false;
3120 }
3121
3122 /*
3123 * Note that we must always update the top frame's environment objects'
3124 * entries in liveEnvs because we can't be sure code hasn't run in that
3125 * frame to change the environment chain since we were last called. The
3126 * fp->prevUpToDate() flag indicates whether the environments of frames
3127 * older than fp are already included in liveEnvs. It might seem simpler
3128 * to have fp instead carry a flag indicating whether fp itself is
3129 * accurately described, but then we would need to clear that flag
3130 * whenever fp ran code. By storing the 'up to date' bit for fp->prev() in
3131 * fp, simply popping fp effectively clears the flag for us, at exactly
3132 * the time when execution resumes fp->prev().
3133 */
3134 for (AllFramesIter i(cx); !i.done(); ++i) {
3135 if (!i.hasUsableAbstractFramePtr()) {
3136 continue;
3137 }
3138
3139 AbstractFramePtr frame = i.abstractFramePtr();
3140 if (frame.realm() != cx->realm()) {
3141 continue;
3142 }
3143
3144 if (!frame.isDebuggee()) {
3145 continue;
3146 }
3147
3148 RootedObject env(cx);
3149 Rooted<Scope*> scope(cx);
3150 if (!GetFrameEnvironmentAndScope(cx, frame, i.pc(), &env, &scope)) {
3151 return false;
3152 }
3153
3154 for (EnvironmentIter ei(cx, env, scope, frame); ei.withinInitialFrame();
3155 ei++) {
3156 if (ei.hasSyntacticEnvironment() && !ei.scope().is<GlobalScope>()) {
3157 MOZ_ASSERT(ei.environment().realm() == cx->realm());
3158 DebugEnvironments* envs = ensureRealmData(cx);
3159 if (!envs) {
3160 return false;
3161 }
3162 if (!envs->liveEnvs.put(&ei.environment(), LiveEnvironmentVal(ei))) {
3163 ReportOutOfMemory(cx);
3164 return false;
3165 }
3166 }
3167 }
3168
3169 if (frame.prevUpToDate()) {
3170 return true;
3171 }
3172 MOZ_ASSERT(frame.realm()->isDebuggee());
3173 frame.setPrevUpToDate();
3174 }
3175
3176 return true;
3177 }
3178
3179 LiveEnvironmentVal* DebugEnvironments::hasLiveEnvironment(
3180 EnvironmentObject& env) {
3181 DebugEnvironments* envs = env.realm()->debugEnvs();
3182 if (!envs) {
3183 return nullptr;
3184 }
3185
3186 if (LiveEnvironmentMap::Ptr p = envs->liveEnvs.lookup(&env)) {
3187 return &p->value();
3188 }
3189
3190 return nullptr;
3191 }
3192
3193 /* static */
3194 void DebugEnvironments::unsetPrevUpToDateUntil(JSContext* cx,
3195 AbstractFramePtr until) {
3196 // This are two exceptions where fp->prevUpToDate() is cleared without
3197 // popping the frame. When a frame is rematerialized or has its
3198 // debuggeeness toggled off->on, all frames younger than the frame must
3199 // have their prevUpToDate set to false. This is because unrematerialized
3200 // Ion frames and non-debuggee frames are skipped by updateLiveEnvironments.
3201 // If in the future a frame suddenly gains a usable AbstractFramePtr via
3202 // rematerialization or becomes a debuggee, the prevUpToDate invariant
3203 // will no longer hold for older frames on its stack.
3204 for (AllFramesIter i(cx); !i.done(); ++i) {
3205 if (!i.hasUsableAbstractFramePtr()) {
3206 continue;
3207 }
3208
3209 AbstractFramePtr frame = i.abstractFramePtr();
3210 if (frame == until) {
3211 return;
3212 }
3213
3214 if (frame.realm() != cx->realm()) {
3215 continue;
3216 }
3217
3218 frame.unsetPrevUpToDate();
3219 }
3220 }
3221
3222 /* static */
3223 void DebugEnvironments::forwardLiveFrame(JSContext* cx, AbstractFramePtr from,
3224 AbstractFramePtr to) {
3225 DebugEnvironments* envs = cx->realm()->debugEnvs();
3226 if (!envs) {
3227 return;
3228 }
3229
3230 for (MissingEnvironmentMap::Enum e(envs->missingEnvs); !e.empty();
3231 e.popFront()) {
3232 MissingEnvironmentKey key = e.front().key();
3233 if (key.frame() == from) {
3234 key.updateFrame(to);
3235 e.rekeyFront(key);
3236 }
3237 }
3238
3239 for (LiveEnvironmentMap::Enum e(envs->liveEnvs); !e.empty(); e.popFront()) {
3240 LiveEnvironmentVal& val = e.front().value();
3241 if (val.frame() == from) {
3242 val.updateFrame(to);
3243 }
3244 }
3245 }
3246
3247 /* static */
3248 void DebugEnvironments::traceLiveFrame(JSTracer* trc, AbstractFramePtr frame) {
3249 for (MissingEnvironmentMap::Enum e(missingEnvs); !e.empty(); e.popFront()) {
3250 if (e.front().key().frame() == frame) {
3251 TraceEdge(trc, &e.front().value(), "debug-env-live-frame-missing-env");
3252 }
3253 }
3254 }
3255
3256 /*****************************************************************************/
3257
3258 static JSObject* GetDebugEnvironment(JSContext* cx, const EnvironmentIter& ei);
3259
3260 static DebugEnvironmentProxy* GetDebugEnvironmentForEnvironmentObject(
3261 JSContext* cx, const EnvironmentIter& ei) {
3262 Rooted<EnvironmentObject*> env(cx, &ei.environment());
3263 if (DebugEnvironmentProxy* debugEnv =
3264 DebugEnvironments::hasDebugEnvironment(cx, *env)) {
3265 return debugEnv;
3266 }
3267
3268 EnvironmentIter copy(cx, ei);
3269 RootedObject enclosingDebug(cx, GetDebugEnvironment(cx, ++copy));
3270 if (!enclosingDebug) {
3271 return nullptr;
3272 }
3273
3274 Rooted<DebugEnvironmentProxy*> debugEnv(
3275 cx, DebugEnvironmentProxy::create(cx, *env, enclosingDebug));
3276 if (!debugEnv) {
3277 return nullptr;
3278 }
3279
3280 if (!DebugEnvironments::addDebugEnvironment(cx, env, debugEnv)) {
3281 return nullptr;
3282 }
3283
3284 return debugEnv;
3285 }
3286
3287 static DebugEnvironmentProxy* GetDebugEnvironmentForMissing(
3288 JSContext* cx, const EnvironmentIter& ei) {
3289 MOZ_ASSERT(!ei.hasSyntacticEnvironment() &&
3290 (ei.scope().is<FunctionScope>() || ei.scope().is<LexicalScope>() ||
3291 ei.scope().is<WasmInstanceScope>() ||
3292 ei.scope().is<WasmFunctionScope>() || ei.scope().is<VarScope>() ||
3293 ei.scope().kind() == ScopeKind::StrictEval));
3294
3295 if (DebugEnvironmentProxy* debugEnv =
3296 DebugEnvironments::hasDebugEnvironment(cx, ei)) {
3297 return debugEnv;
3298 }
3299
3300 EnvironmentIter copy(cx, ei);
3301 RootedObject enclosingDebug(cx, GetDebugEnvironment(cx, ++copy));
3302 if (!enclosingDebug) {
3303 return nullptr;
3304 }
3305
3306 /*
3307 * Create the missing environment object. For lexical environment objects,
3308 * this takes care of storing variable values after the stack frame has
3309 * been popped. For call objects, we only use the pretend call object to
3310 * access callee, bindings and to receive dynamically added
3311 * properties. Together, this provides the nice invariant that every
3312 * DebugEnvironmentProxy has a EnvironmentObject.
3313 *
3314 * Note: to preserve envChain depth invariants, these lazily-reified
3315 * envs must not be put on the frame's environment chain; instead, they are
3316 * maintained via DebugEnvironments hooks.
3317 */
3318 Rooted<DebugEnvironmentProxy*> debugEnv(cx);
3319 if (ei.scope().is<FunctionScope>()) {
3320 RootedFunction callee(cx,
3321 ei.scope().as<FunctionScope>().canonicalFunction());
3322
3323 JS::ExposeObjectToActiveJS(callee);
3324 Rooted<CallObject*> callobj(cx,
3325 CallObject::createHollowForDebug(cx, callee));
3326 if (!callobj) {
3327 return nullptr;
3328 }
3329
3330 debugEnv = DebugEnvironmentProxy::create(cx, *callobj, enclosingDebug);
3331 } else if (ei.scope().is<LexicalScope>()) {
3332 Rooted<LexicalScope*> lexicalScope(cx, &ei.scope().as<LexicalScope>());
3333 Rooted<BlockLexicalEnvironmentObject*> env(
3334 cx,
3335 BlockLexicalEnvironmentObject::createHollowForDebug(cx, lexicalScope));
3336 if (!env) {
3337 return nullptr;
3338 }
3339
3340 debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
3341 } else if (ei.scope().is<WasmInstanceScope>()) {
3342 Rooted<WasmInstanceScope*> wasmInstanceScope(
3343 cx, &ei.scope().as<WasmInstanceScope>());
3344 Rooted<WasmInstanceEnvironmentObject*> env(
3345 cx, WasmInstanceEnvironmentObject::createHollowForDebug(
3346 cx, wasmInstanceScope));
3347 if (!env) {
3348 return nullptr;
3349 }
3350
3351 debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
3352 } else if (ei.scope().is<WasmFunctionScope>()) {
3353 Rooted<WasmFunctionScope*> wasmFunctionScope(
3354 cx, &ei.scope().as<WasmFunctionScope>());
3355 RootedObject enclosing(
3356 cx, &enclosingDebug->as<DebugEnvironmentProxy>().environment());
3357 Rooted<WasmFunctionCallObject*> callobj(
3358 cx, WasmFunctionCallObject::createHollowForDebug(cx, enclosing,
3359 wasmFunctionScope));
3360 if (!callobj) {
3361 return nullptr;
3362 }
3363
3364 debugEnv = DebugEnvironmentProxy::create(cx, *callobj, enclosingDebug);
3365 } else {
3366 Rooted<Scope*> scope(cx, &ei.scope());
3367 MOZ_ASSERT(scope->is<VarScope>() || scope->kind() == ScopeKind::StrictEval);
3368
3369 Rooted<VarEnvironmentObject*> env(
3370 cx, VarEnvironmentObject::createHollowForDebug(cx, scope));
3371 if (!env) {
3372 return nullptr;
3373 }
3374
3375 debugEnv = DebugEnvironmentProxy::create(cx, *env, enclosingDebug);
3376 }
3377
3378 if (!debugEnv) {
3379 return nullptr;
3380 }
3381
3382 if (!DebugEnvironments::addDebugEnvironment(cx, ei, debugEnv)) {
3383 return nullptr;
3384 }
3385
3386 return debugEnv;
3387 }
3388
3389 static JSObject* GetDebugEnvironmentForNonEnvironmentObject(
3390 const EnvironmentIter& ei) {
3391 JSObject& enclosing = ei.enclosingEnvironment();
3392 #ifdef DEBUG
3393 JSObject* o = &enclosing;
3394 while ((o = o->enclosingEnvironment())) {
3395 MOZ_ASSERT(!o->is<EnvironmentObject>());
3396 }
3397 #endif
3398 return &enclosing;
3399 }
3400
3401 static JSObject* GetDebugEnvironment(JSContext* cx, const EnvironmentIter& ei) {
3402 AutoCheckRecursionLimit recursion(cx);
3403 if (!recursion.check(cx)) {
3404 return nullptr;
3405 }
3406
3407 if (ei.done()) {
3408 return GetDebugEnvironmentForNonEnvironmentObject(ei);
3409 }
3410
3411 if (ei.hasAnyEnvironmentObject()) {
3412 return GetDebugEnvironmentForEnvironmentObject(cx, ei);
3413 }
3414
3415 if (ei.scope().is<FunctionScope>() || ei.scope().is<LexicalScope>() ||
3416 ei.scope().is<WasmInstanceScope>() ||
3417 ei.scope().is<WasmFunctionScope>() || ei.scope().is<VarScope>() ||
3418 ei.scope().kind() == ScopeKind::StrictEval) {
3419 return GetDebugEnvironmentForMissing(cx, ei);
3420 }
3421
3422 EnvironmentIter copy(cx, ei);
3423 return GetDebugEnvironment(cx, ++copy);
3424 }
3425
3426 JSObject* js::GetDebugEnvironmentForFunction(JSContext* cx,
3427 HandleFunction fun) {
3428 cx->check(fun);
3429 MOZ_ASSERT(CanUseDebugEnvironmentMaps(cx));
3430 if (!DebugEnvironments::updateLiveEnvironments(cx)) {
3431 return nullptr;
3432 }
3433 JSScript* script = JSFunction::getOrCreateScript(cx, fun);
3434 if (!script) {
3435 return nullptr;
3436 }
3437 EnvironmentIter ei(cx, fun->environment(), script->enclosingScope());
3438 return GetDebugEnvironment(cx, ei);
3439 }
3440
3441 static auto GetSuspendedGeneratorEnvironmentAndScope(
3442 AbstractGeneratorObject& genObj, JSScript* script) {
3443 jsbytecode* pc =
3444 script->offsetToPC(script->resumeOffsets()[genObj.resumeIndex()]);
3445 return std::pair{&genObj.environmentChain(), script->innermostScope(pc)};
3446 }
3447
3448 JSObject* js::GetDebugEnvironmentForSuspendedGenerator(
3449 JSContext* cx, JSScript* script, AbstractGeneratorObject& genObj) {
3450 auto [env, scope] = GetSuspendedGeneratorEnvironmentAndScope(genObj, script);
3451
3452 EnvironmentIter ei(cx, env, scope);
3453 return GetDebugEnvironment(cx, ei);
3454 }
3455
3456 JSObject* js::GetDebugEnvironmentForFrame(JSContext* cx, AbstractFramePtr frame,
3457 jsbytecode* pc) {
3458 cx->check(frame);
3459 if (CanUseDebugEnvironmentMaps(cx) &&
3460 !DebugEnvironments::updateLiveEnvironments(cx)) {
3461 return nullptr;
3462 }
3463
3464 RootedObject env(cx);
3465 Rooted<Scope*> scope(cx);
3466 if (!GetFrameEnvironmentAndScope(cx, frame, pc, &env, &scope)) {
3467 return nullptr;
3468 }
3469
3470 EnvironmentIter ei(cx, env, scope, frame);
3471 return GetDebugEnvironment(cx, ei);
3472 }
3473
3474 JSObject* js::GetDebugEnvironmentForGlobalLexicalEnvironment(JSContext* cx) {
3475 EnvironmentIter ei(cx, &cx->global()->lexicalEnvironment(),
3476 &cx->global()->emptyGlobalScope());
3477 return GetDebugEnvironment(cx, ei);
3478 }
3479
3480 WithEnvironmentObject* js::CreateObjectsForEnvironmentChain(
3481 JSContext* cx, const JS::EnvironmentChain& chain,
3482 HandleObject terminatingEnv) {
3483 MOZ_ASSERT(!chain.empty());
3484
3485 #ifdef DEBUG
3486 for (size_t i = 0; i < chain.length(); ++i) {
3487 cx->check(chain.chain()[i]);
3488 MOZ_ASSERT(!chain.chain()[i]->isUnqualifiedVarObj());
3489 }
3490 #endif
3491
3492 // Construct With object wrappers for the things on this environment chain
3493 // and use the result as the thing to scope the function to.
3494 Rooted<WithEnvironmentObject*> withEnv(cx);
3495 RootedObject enclosingEnv(cx, terminatingEnv);
3496 for (size_t i = chain.length(); i > 0;) {
3497 withEnv = WithEnvironmentObject::createNonSyntactic(
3498 cx, chain.chain()[--i], enclosingEnv, chain.supportUnscopables());
3499 if (!withEnv) {
3500 return nullptr;
3501 }
3502 enclosingEnv = withEnv;
3503 }
3504
3505 return withEnv;
3506 }
3507
3508 JSObject& WithEnvironmentObject::object() const {
3509 return getReservedSlot(OBJECT_SLOT).toObject();
3510 }
3511
3512 JSObject* WithEnvironmentObject::withThis() const {
3513 JSObject* obj = &getReservedSlot(THIS_SLOT).toObject();
3514
3515 // Windows must never be exposed to script. WithEnvironmentObject::create
3516 // should have set this to the WindowProxy.
3517 MOZ_ASSERT(!IsWindow(obj));
3518
3519 return obj;
3520 }
3521
3522 bool WithEnvironmentObject::isSyntactic() const {
3523 Value v = getReservedSlot(SCOPE_OR_SUPPORT_UNSCOPABLES_SLOT);
3524 MOZ_ASSERT(v.isPrivateGCThing() || v.isBoolean());
3525 return v.isPrivateGCThing();
3526 }
3527
3528 bool WithEnvironmentObject::supportUnscopables() const {
3529 if (isSyntactic()) {
3530 return true;
3531 }
3532 Value v = getReservedSlot(SCOPE_OR_SUPPORT_UNSCOPABLES_SLOT);
3533 MOZ_ASSERT(v.isBoolean());
3534 return v.isTrue();
3535 }
3536
3537 WithScope& WithEnvironmentObject::scope() const {
3538 MOZ_ASSERT(isSyntactic());
3539 Value v = getReservedSlot(SCOPE_OR_SUPPORT_UNSCOPABLES_SLOT);
3540 return *static_cast<WithScope*>(v.toGCThing());
3541 }
3542
3543 ModuleEnvironmentObject* js::GetModuleEnvironmentForScript(JSScript* script) {
3544 return GetModuleObjectForScript(script)->environment();
3545 }
3546
3547 ModuleObject* js::GetModuleObjectForScript(JSScript* script) {
3548 for (ScopeIter si(script); si; si++) {
3549 if (si.kind() == ScopeKind::Module) {
3550 return si.scope()->as<ModuleScope>().module();
3551 }
3552 }
3553
3554 MOZ_CRASH("No module scope found for script");
3555 }
3556
3557 static bool GetThisValueForDebuggerEnvironmentIterMaybeOptimizedOut(
3558 JSContext* cx, const EnvironmentIter& originalIter, HandleObject envChain,
3559 const jsbytecode* pc, MutableHandleValue res) {
3560 for (EnvironmentIter ei(cx, originalIter); ei; ei++) {
3561 if (ei.scope().kind() == ScopeKind::Module) {
3562 res.setUndefined();
3563 return true;
3564 }
3565
3566 if (!ei.scope().is<FunctionScope>() ||
3567 ei.scope().as<FunctionScope>().canonicalFunction()->hasLexicalThis()) {
3568 continue;
3569 }
3570
3571 RootedScript script(cx, ei.scope().as<FunctionScope>().script());
3572
3573 if (ei.withinInitialFrame()) {
3574 MOZ_ASSERT(pc, "must have PC if there is an initial frame");
3575
3576 // Figure out if we executed JSOp::FunctionThis and set it.
3577 bool executedInitThisOp = false;
3578 if (script->functionHasThisBinding()) {
3579 for (const BytecodeLocation& loc : js::AllBytecodesIterable(script)) {
3580 if (loc.getOp() == JSOp::FunctionThis) {
3581 // The next op after JSOp::FunctionThis always sets it.
3582 executedInitThisOp = pc > GetNextPc(loc.toRawBytecode());
3583 break;
3584 }
3585 }
3586 }
3587
3588 if (!executedInitThisOp) {
3589 AbstractFramePtr initialFrame = ei.initialFrame();
3590 // Either we're yet to initialize the this-binding
3591 // (JSOp::FunctionThis), or the script does not have a this-binding
3592 // (because it doesn't use |this|).
3593
3594 // If our this-argument is an object, or we're in strict mode,
3595 // the this-binding is always the same as our this-argument.
3596 if (initialFrame.thisArgument().isObject() || script->strict()) {
3597 res.set(initialFrame.thisArgument());
3598 return true;
3599 }
3600
3601 // We didn't initialize the this-binding yet. Determine the
3602 // correct |this| value for this frame (box primitives if not
3603 // in strict mode), and assign it to the this-argument slot so
3604 // JSOp::FunctionThis will use it and not box a second time.
3605 if (!GetFunctionThis(cx, initialFrame, res)) {
3606 return false;
3607 }
3608 initialFrame.thisArgument() = res;
3609 return true;
3610 }
3611 }
3612
3613 if (!script->functionHasThisBinding()) {
3614 res.setMagic(JS_OPTIMIZED_OUT);
3615 return true;
3616 }
3617
3618 for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
3619 if (bi.name() != cx->names().dot_this_) {
3620 continue;
3621 }
3622
3623 BindingLocation loc = bi.location();
3624 if (loc.kind() == BindingLocation::Kind::Environment) {
3625 RootedObject callObj(cx, &ei.environment().as<CallObject>());
3626 return GetProperty(cx, callObj, callObj, bi.name()->asPropertyName(),
3627 res);
3628 }
3629
3630 if (loc.kind() == BindingLocation::Kind::Frame) {
3631 if (ei.withinInitialFrame()) {
3632 res.set(ei.initialFrame().unaliasedLocal(loc.slot()));
3633 return true;
3634 }
3635
3636 if (ei.hasAnyEnvironmentObject()) {
3637 RootedObject env(cx, &ei.environment());
3638 AbstractGeneratorObject* genObj =
3639 GetGeneratorObjectForEnvironment(cx, env);
3640 if (genObj && genObj->isSuspended() && genObj->hasStackStorage()) {
3641 res.set(genObj->getUnaliasedLocal(loc.slot()));
3642 return true;
3643 }
3644 }
3645 }
3646
3647 res.setMagic(JS_OPTIMIZED_OUT);
3648 return true;
3649 }
3650
3651 MOZ_CRASH("'this' binding must be found");
3652 }
3653
3654 GetNonSyntacticGlobalThis(cx, envChain, res);
3655 return true;
3656 }
3657
3658 bool js::GetThisValueForDebuggerFrameMaybeOptimizedOut(JSContext* cx,
3659 AbstractFramePtr frame,
3660 const jsbytecode* pc,
3661 MutableHandleValue res) {
3662 RootedObject envChain(cx);
3663 Rooted<Scope*> scope(cx);
3664 if (!GetFrameEnvironmentAndScope(cx, frame, pc, &envChain, &scope)) {
3665 return false;
3666 }
3667
3668 EnvironmentIter ei(cx, envChain, scope, frame);
3669 return GetThisValueForDebuggerEnvironmentIterMaybeOptimizedOut(
3670 cx, ei, envChain, pc, res);
3671 }
3672
3673 bool js::GetThisValueForDebuggerSuspendedGeneratorMaybeOptimizedOut(
3674 JSContext* cx, AbstractGeneratorObject& genObj, JSScript* script,
3675 MutableHandleValue res) {
3676 auto [env, scope] = GetSuspendedGeneratorEnvironmentAndScope(genObj, script);
3677 Rooted<JSObject*> envChain(cx, env);
3678
3679 EnvironmentIter ei(cx, envChain, scope);
3680 return GetThisValueForDebuggerEnvironmentIterMaybeOptimizedOut(
3681 cx, ei, envChain, nullptr, res);
3682 }
3683
3684 static void ReportRuntimeRedeclaration(JSContext* cx,
3685 Handle<PropertyName*> name,
3686 const char* redeclKind) {
3687 if (UniqueChars printable = AtomToPrintableString(cx, name)) {
3688 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3689 JSMSG_REDECLARED_VAR, redeclKind,
3690 printable.get());
3691 }
3692 }
3693
3694 [[nodiscard]] static bool CheckLexicalNameConflict(
3695 JSContext* cx, Handle<ExtensibleLexicalEnvironmentObject*> lexicalEnv,
3696 HandleObject varObj, Handle<PropertyName*> name) {
3697 const char* redeclKind = nullptr;
3698 RootedId id(cx, NameToId(name));
3699 mozilla::Maybe<PropertyInfo> prop;
3700 bool shadowsExistingProperty = false;
3701
3702 if ((prop = lexicalEnv->lookup(cx, name))) {
3703 // ES 15.1.11 step 5.b
3704 redeclKind = prop->writable() ? "let" : "const";
3705 } else if (varObj->is<NativeObject>() &&
3706 (prop = varObj->as<NativeObject>().lookup(cx, name))) {
3707 // Faster path for ES 15.1.11 step 5.c-d when the shape can be found
3708 // without going through a resolve hook.
3709 if (!prop->configurable()) {
3710 redeclKind = "non-configurable global property";
3711 } else {
3712 shadowsExistingProperty = true;
3713 }
3714 } else {
3715 // ES 15.1.11 step 5.c-d
3716 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
3717 if (!GetOwnPropertyDescriptor(cx, varObj, id, &desc)) {
3718 return false;
3719 }
3720 if (desc.isSome()) {
3721 if (!desc->configurable()) {
3722 redeclKind = "non-configurable global property";
3723 } else {
3724 shadowsExistingProperty = true;
3725 }
3726 }
3727 }
3728
3729 if (redeclKind) {
3730 ReportRuntimeRedeclaration(cx, name, redeclKind);
3731 return false;
3732 }
3733 if (shadowsExistingProperty && varObj->is<GlobalObject>()) {
3734 // Shadowing a configurable global property with a new lexical is one
3735 // of the rare ways to invalidate a GetGName stub.
3736 varObj->as<GlobalObject>().bumpGenerationCount();
3737 }
3738
3739 return true;
3740 }
3741
3742 [[nodiscard]] static bool CheckVarNameConflict(
3743 JSContext* cx, Handle<LexicalEnvironmentObject*> lexicalEnv,
3744 Handle<PropertyName*> name) {
3745 mozilla::Maybe<PropertyInfo> prop = lexicalEnv->lookup(cx, name);
3746 if (prop.isSome()) {
3747 ReportRuntimeRedeclaration(cx, name, prop->writable() ? "let" : "const");
3748 return false;
3749 }
3750 return true;
3751 }
3752
3753 static void ReportCannotDeclareGlobalBinding(JSContext* cx,
3754 Handle<PropertyName*> name,
3755 const char* reason) {
3756 if (UniqueChars printable = AtomToPrintableString(cx, name)) {
3757 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3758 JSMSG_CANT_DECLARE_GLOBAL_BINDING,
3759 printable.get(), reason);
3760 }
3761 }
3762
3763 [[nodiscard]] static bool CheckCanDeclareGlobalBinding(
3764 JSContext* cx, Handle<GlobalObject*> global, Handle<PropertyName*> name,
3765 bool isFunction) {
3766 RootedId id(cx, NameToId(name));
3767 Rooted<mozilla::Maybe<PropertyDescriptor>> desc(cx);
3768 if (!GetOwnPropertyDescriptor(cx, global, id, &desc)) {
3769 return false;
3770 }
3771
3772 // ES 8.1.1.4.15 CanDeclareGlobalVar
3773 // ES 8.1.1.4.16 CanDeclareGlobalFunction
3774
3775 // Step 4.
3776 if (desc.isNothing()) {
3777 // 8.1.14.15 step 6.
3778 // 8.1.14.16 step 5.
3779 if (global->isExtensible()) {
3780 return true;
3781 }
3782
3783 ReportCannotDeclareGlobalBinding(cx, name, "global is non-extensible");
3784 return false;
3785 }
3786
3787 // Global functions have additional restrictions.
3788 if (isFunction) {
3789 // 8.1.14.16 step 6.
3790 if (desc->configurable()) {
3791 return true;
3792 }
3793
3794 // 8.1.14.16 step 7.
3795 if (desc->isDataDescriptor() && desc->writable() && desc->enumerable()) {
3796 return true;
3797 }
3798
3799 ReportCannotDeclareGlobalBinding(cx, name,
3800 "property must be configurable or "
3801 "both writable and enumerable");
3802 return false;
3803 }
3804
3805 return true;
3806 }
3807
3808 // Add the var/let/const bindings to the variables environment of a global or
3809 // sloppy-eval script. The redeclaration checks should already have been
3810 // performed.
3811 static bool InitGlobalOrEvalDeclarations(
3812 JSContext* cx, HandleScript script,
3813 Handle<ExtensibleLexicalEnvironmentObject*> lexicalEnv,
3814 HandleObject varObj) {
3815 Rooted<BindingIter> bi(cx, BindingIter(script));
3816 for (; bi; bi++) {
3817 if (bi.isTopLevelFunction()) {
3818 continue;
3819 }
3820
3821 Rooted<PropertyName*> name(cx, bi.name()->asPropertyName());
3822 unsigned attrs = script->isForEval() ? JSPROP_ENUMERATE
3823 : JSPROP_ENUMERATE | JSPROP_PERMANENT;
3824
3825 switch (bi.kind()) {
3826 case BindingKind::Var: {
3827 PropertyResult prop;
3828 RootedObject obj2(cx);
3829 if (!LookupProperty(cx, varObj, name, &obj2, &prop)) {
3830 return false;
3831 }
3832
3833 if (prop.isNotFound() ||
3834 (obj2 != varObj && varObj->is<GlobalObject>())) {
3835 if (!DefineDataProperty(cx, varObj, name, UndefinedHandleValue,
3836 attrs)) {
3837 return false;
3838 }
3839 }
3840
3841 break;
3842 }
3843
3844 case BindingKind::Const:
3845 attrs |= JSPROP_READONLY;
3846 [[fallthrough]];
3847
3848 case BindingKind::Let: {
3849 RootedId id(cx, NameToId(name));
3850 RootedValue uninitialized(cx, MagicValue(JS_UNINITIALIZED_LEXICAL));
3851 if (!NativeDefineDataProperty(cx, lexicalEnv, id, uninitialized,
3852 attrs)) {
3853 return false;
3854 }
3855
3856 break;
3857 }
3858
3859 default:
3860 MOZ_CRASH("Expected binding kind");
3861 return false;
3862 }
3863 }
3864
3865 return true;
3866 }
3867
3868 // Define the hoisted top-level functions on the variables environment of a
3869 // global or sloppy-eval script. Redeclaration checks must already have been
3870 // performed.
3871 static bool InitHoistedFunctionDeclarations(JSContext* cx, HandleScript script,
3872 HandleObject envChain,
3873 HandleObject varObj,
3874 GCThingIndex lastFun) {
3875 // The inner-functions up to `lastFun` are the hoisted function declarations
3876 // of the script. We must clone and bind them now.
3877 for (size_t i = 0; i <= lastFun; ++i) {
3878 JS::GCCellPtr thing = script->gcthings()[i];
3879
3880 // Skip the initial scopes. In practice, there is at most one variables and
3881 // one lexical scope.
3882 if (thing.is<js::Scope>()) {
3883 MOZ_ASSERT(i < 2);
3884 continue;
3885 }
3886
3887 RootedFunction fun(cx, &thing.as<JSObject>().as<JSFunction>());
3888 Rooted<PropertyName*> name(cx, fun->fullExplicitName()->asPropertyName());
3889
3890 // Clone the function before exposing to script as a binding.
3891 JSObject* clone = Lambda(cx, fun, envChain);
3892 if (!clone) {
3893 return false;
3894 }
3895 RootedValue rval(cx, ObjectValue(*clone));
3896
3897 PropertyResult prop;
3898 RootedObject pobj(cx);
3899 if (!LookupProperty(cx, varObj, name, &pobj, &prop)) {
3900 return false;
3901 }
3902
3903 // ECMA requires functions defined when entering Eval code to be
3904 // impermanent.
3905 unsigned attrs = script->isForEval() ? JSPROP_ENUMERATE
3906 : JSPROP_ENUMERATE | JSPROP_PERMANENT;
3907
3908 if (prop.isNotFound() || pobj != varObj) {
3909 if (!DefineDataProperty(cx, varObj, name, rval, attrs)) {
3910 return false;
3911 }
3912
3913 // Done processing this function.
3914 continue;
3915 }
3916
3917 /*
3918 * A DebugEnvironmentProxy is okay here, and sometimes necessary. If
3919 * Debugger.Frame.prototype.eval defines a function with the same name as an
3920 * extant variable in the frame, the DebugEnvironmentProxy takes care of
3921 * storing the function in the stack frame (for non-aliased variables) or on
3922 * the scope object (for aliased).
3923 */
3924 MOZ_ASSERT(varObj->is<NativeObject>() ||
3925 varObj->is<DebugEnvironmentProxy>());
3926 if (varObj->is<GlobalObject>()) {
3927 PropertyInfo propInfo = prop.propertyInfo();
3928 if (propInfo.configurable()) {
3929 if (!DefineDataProperty(cx, varObj, name, rval, attrs)) {
3930 return false;
3931 }
3932 } else {
3933 MOZ_ASSERT(propInfo.isDataProperty());
3934 MOZ_ASSERT(propInfo.writable());
3935 MOZ_ASSERT(propInfo.enumerable());
3936 }
3937 }
3938
3939 /*
3940 * Non-global properties, and global properties which we aren't simply
3941 * redefining, must be set. First, this preserves their attributes.
3942 * Second, this will produce warnings and/or errors as necessary if the
3943 * specified Call object property is not writable (const).
3944 */
3945
3946 RootedId id(cx, NameToId(name));
3947 if (!PutProperty(cx, varObj, id, rval, script->strict())) {
3948 return false;
3949 }
3950 }
3951
3952 return true;
3953 }
3954
3955 [[nodiscard]] static bool CheckGlobalDeclarationConflicts(
3956 JSContext* cx, HandleScript script,
3957 Handle<ExtensibleLexicalEnvironmentObject*> lexicalEnv,
3958 HandleObject varObj) {
3959 // Due to the extensibility of the global lexical environment, we must
3960 // check for redeclaring a binding.
3961 //
3962 // In the case of non-syntactic environment chains, we are checking
3963 // redeclarations against the non-syntactic lexical environment and the
3964 // variables object that the lexical environment corresponds to.
3965 Rooted<PropertyName*> name(cx);
3966 Rooted<BindingIter> bi(cx, BindingIter(script));
3967
3968 // ES 15.1.11 GlobalDeclarationInstantiation
3969
3970 // Step 6.
3971 //
3972 // Check 'var' declarations do not conflict with existing bindings in the
3973 // global lexical environment.
3974 for (; bi; bi++) {
3975 if (bi.kind() != BindingKind::Var) {
3976 break;
3977 }
3978 name = bi.name()->asPropertyName();
3979 if (!CheckVarNameConflict(cx, lexicalEnv, name)) {
3980 return false;
3981 }
3982
3983 // Step 10 and 12.
3984 //
3985 // Check that global functions and vars may be declared.
3986 if (varObj->is<GlobalObject>()) {
3987 Handle<GlobalObject*> global = varObj.as<GlobalObject>();
3988 if (!CheckCanDeclareGlobalBinding(cx, global, name,
3989 bi.isTopLevelFunction())) {
3990 return false;
3991 }
3992 }
3993 }
3994
3995 // Step 5.
3996 //
3997 // Check that lexical bindings do not conflict.
3998 for (; bi; bi++) {
3999 name = bi.name()->asPropertyName();
4000 if (!CheckLexicalNameConflict(cx, lexicalEnv, varObj, name)) {
4001 return false;
4002 }
4003 }
4004
4005 return true;
4006 }
4007
4008 [[nodiscard]] static bool CheckVarNameConflictsInEnv(JSContext* cx,
4009 HandleScript script,
4010 HandleObject obj) {
4011 Rooted<LexicalEnvironmentObject*> env(cx);
4012
4013 if (obj->is<LexicalEnvironmentObject>()) {
4014 env = &obj->as<LexicalEnvironmentObject>();
4015 } else if (obj->is<DebugEnvironmentProxy>() &&
4016 obj->as<DebugEnvironmentProxy>()
4017 .environment()
4018 .is<LexicalEnvironmentObject>()) {
4019 env = &obj->as<DebugEnvironmentProxy>()
4020 .environment()
4021 .as<LexicalEnvironmentObject>();
4022 } else {
4023 // Environment cannot contain lexical bindings.
4024 return true;
4025 }
4026
4027 if (env->is<BlockLexicalEnvironmentObject>() &&
4028 env->as<BlockLexicalEnvironmentObject>().scope().kind() ==
4029 ScopeKind::SimpleCatch) {
4030 // Annex B.3.5 allows redeclaring simple (non-destructured) catch parameters
4031 // with var declarations.
4032 return true;
4033 }
4034
4035 Rooted<PropertyName*> name(cx);
4036 for (BindingIter bi(script); bi; bi++) {
4037 name = bi.name()->asPropertyName();
4038 if (!CheckVarNameConflict(cx, env, name)) {
4039 return false;
4040 }
4041 }
4042
4043 return true;
4044 }
4045
4046 static bool CheckArgumentsRedeclaration(JSContext* cx, HandleScript script) {
4047 for (BindingIter bi(script); bi; bi++) {
4048 if (bi.name() == cx->names().arguments) {
4049 ReportRuntimeRedeclaration(cx, cx->names().arguments, "let");
4050 return false;
4051 }
4052 }
4053
4054 return true;
4055 }
4056
4057 static bool CheckEvalDeclarationConflicts(JSContext* cx, HandleScript script,
4058 HandleObject envChain,
4059 HandleObject varObj) {
4060 // Strict eval has its own call objects and we shouldn't end up here.
4061 //
4062 // Non-strict eval may introduce 'var' bindings that conflict with lexical
4063 // bindings in an enclosing lexical scope.
4064 MOZ_ASSERT(!script->bodyScope()->hasEnvironment());
4065 MOZ_ASSERT(!script->strict());
4066
4067 MOZ_ASSERT(script->bodyScope()->as<EvalScope>().hasBindings());
4068
4069 RootedObject env(cx, envChain);
4070
4071 // ES 18.2.1.3.
4072
4073 // Step 5.
4074 //
4075 // Check that a direct eval will not hoist 'var' bindings over lexical
4076 // bindings with the same name.
4077 while (env != varObj) {
4078 if (!CheckVarNameConflictsInEnv(cx, script, env)) {
4079 return false;
4080 }
4081 env = env->enclosingEnvironment();
4082 }
4083
4084 // Check for redeclared "arguments" in function parameter expressions.
4085 //
4086 // Direct eval in function parameter expressions isn't allowed to redeclare
4087 // the implicit "arguments" bindings:
4088 // function f(a = eval("var arguments;")) {}
4089 //
4090 // |varObj| isn't a CallObject when the direct eval occurs in the function
4091 // body and the extra function body var scope is present. The extra var scope
4092 // is present iff the function has parameter expressions. So when we test
4093 // that |varObj| is a CallObject and function parameter expressions are
4094 // present, we can pinpoint the direct eval location to be in a function
4095 // parameter expression. Additionally we must ensure the function isn't an
4096 // arrow function, because arrow functions don't have an implicit "arguments"
4097 // binding.
4098 if (script->isDirectEvalInFunction() && varObj->is<CallObject>()) {
4099 JSFunction* fun = &varObj->as<CallObject>().callee();
4100 JSScript* funScript = fun->nonLazyScript();
4101 if (funScript->functionHasParameterExprs() && !fun->isArrow()) {
4102 if (!CheckArgumentsRedeclaration(cx, script)) {
4103 return false;
4104 }
4105 }
4106 }
4107
4108 // Step 8.
4109 //
4110 // Check that global functions may be declared.
4111 if (varObj->is<GlobalObject>()) {
4112 Handle<GlobalObject*> global = varObj.as<GlobalObject>();
4113 Rooted<PropertyName*> name(cx);
4114 for (Rooted<BindingIter> bi(cx, BindingIter(script)); bi; bi++) {
4115 name = bi.name()->asPropertyName();
4116 if (!CheckCanDeclareGlobalBinding(cx, global, name,
4117 bi.isTopLevelFunction())) {
4118 return false;
4119 }
4120 }
4121 }
4122
4123 return true;
4124 }
4125
4126 bool js::GlobalOrEvalDeclInstantiation(JSContext* cx, HandleObject envChain,
4127 HandleScript script,
4128 GCThingIndex lastFun) {
4129 MOZ_ASSERT(script->isGlobalCode() || script->isForEval());
4130 MOZ_ASSERT(!script->selfHosted());
4131
4132 RootedObject varObj(cx, &GetVariablesObject(envChain));
4133 Rooted<ExtensibleLexicalEnvironmentObject*> lexicalEnv(cx);
4134
4135 if (script->isForEval()) {
4136 if (!CheckEvalDeclarationConflicts(cx, script, envChain, varObj)) {
4137 return false;
4138 }
4139 } else {
4140 lexicalEnv = &NearestEnclosingExtensibleLexicalEnvironment(envChain);
4141 if (!CheckGlobalDeclarationConflicts(cx, script, lexicalEnv, varObj)) {
4142 return false;
4143 }
4144 }
4145
4146 if (!InitGlobalOrEvalDeclarations(cx, script, lexicalEnv, varObj)) {
4147 return false;
4148 }
4149
4150 return InitHoistedFunctionDeclarations(cx, script, envChain, varObj, lastFun);
4151 }
4152
4153 bool js::InitFunctionEnvironmentObjects(JSContext* cx, AbstractFramePtr frame) {
4154 MOZ_ASSERT(frame.isFunctionFrame());
4155 MOZ_ASSERT(frame.callee()->needsFunctionEnvironmentObjects());
4156
4157 RootedFunction callee(cx, frame.callee());
4158
4159 gc::AllocSite* site = nullptr;
4160 if (frame.isBaselineFrame()) {
4161 site = frame.asBaselineFrame()->icScript()->maybeEnvAllocSite();
4162 }
4163
4164 // Named lambdas may have an environment that holds itself for recursion.
4165 if (callee->needsNamedLambdaEnvironment()) {
4166 NamedLambdaObject* declEnv =
4167 NamedLambdaObject::createForFrame(cx, frame, site);
4168 if (!declEnv) {
4169 return false;
4170 }
4171 frame.pushOnEnvironmentChain(*declEnv);
4172 }
4173
4174 // If the function has parameter default expressions, there may be an
4175 // extra environment to hold the parameters.
4176 if (callee->needsCallObject()) {
4177 CallObject* callObj = CallObject::createForFrame(cx, frame, site);
4178 if (!callObj) {
4179 return false;
4180 }
4181 frame.pushOnEnvironmentChain(*callObj);
4182 }
4183
4184 return true;
4185 }
4186
4187 bool js::PushVarEnvironmentObject(JSContext* cx, Handle<Scope*> scope,
4188 AbstractFramePtr frame) {
4189 auto* env = VarEnvironmentObject::createForFrame(cx, scope, frame);
4190 if (!env) {
4191 return false;
4192 }
4193 frame.pushOnEnvironmentChain(*env);
4194 return true;
4195 }
4196
4197 static bool GetFrameEnvironmentAndScope(JSContext* cx, AbstractFramePtr frame,
4198 const jsbytecode* pc,
4199 MutableHandleObject env,
4200 MutableHandle<Scope*> scope) {
4201 env.set(frame.environmentChain());
4202
4203 if (frame.isWasmDebugFrame()) {
4204 Rooted<WasmInstanceObject*> instance(cx, frame.wasmInstance()->object());
4205 uint32_t funcIndex = frame.asWasmDebugFrame()->funcIndex();
4206 scope.set(WasmInstanceObject::getFunctionScope(cx, instance, funcIndex));
4207 if (!scope) {
4208 return false;
4209 }
4210 } else {
4211 scope.set(frame.script()->innermostScope(pc));
4212 }
4213 return true;
4214 }
4215
4216 #ifdef DEBUG
4217
4218 using PropertyNameSet = HashSet<PropertyName*>;
4219
4220 static bool RemoveReferencedNames(JSContext* cx, HandleScript script,
4221 PropertyNameSet& remainingNames) {
4222 // Remove from remainingNames --- the closure variables in some outer
4223 // script --- any free variables in this script. This analysis isn't perfect:
4224 //
4225 // - It will not account for free variables in an inner script which are
4226 // actually accessing some name in an intermediate script between the
4227 // inner and outer scripts. This can cause remainingNames to be an
4228 // underapproximation.
4229 //
4230 // - It will not account for new names introduced via eval. This can cause
4231 // remainingNames to be an overapproximation. This would be easy to fix
4232 // but is nice to have as the eval will probably not access these
4233 // these names and putting eval in an inner script is bad news if you
4234 // care about entraining variables unnecessarily.
4235
4236 AllBytecodesIterable iter(script);
4237 for (BytecodeLocation loc : iter) {
4238 PropertyName* name;
4239
4240 switch (loc.getOp()) {
4241 case JSOp::GetName:
4242 case JSOp::SetName:
4243 case JSOp::StrictSetName:
4244 name = script->getName(loc.toRawBytecode());
4245 break;
4246
4247 case JSOp::GetAliasedVar:
4248 case JSOp::SetAliasedVar:
4249 name = EnvironmentCoordinateNameSlow(script, loc.toRawBytecode());
4250 break;
4251
4252 default:
4253 name = nullptr;
4254 break;
4255 }
4256
4257 if (name) {
4258 remainingNames.remove(name);
4259 }
4260 }
4261
4262 RootedFunction fun(cx);
4263 RootedScript innerScript(cx);
4264 for (JS::GCCellPtr gcThing : script->gcthings()) {
4265 if (!gcThing.is<JSObject>()) {
4266 continue;
4267 }
4268 JSObject* obj = &gcThing.as<JSObject>();
4269
4270 if (!obj->is<JSFunction>()) {
4271 continue;
4272 }
4273 fun = &obj->as<JSFunction>();
4274
4275 if (!fun->isInterpreted()) {
4276 continue;
4277 }
4278
4279 innerScript = JSFunction::getOrCreateScript(cx, fun);
4280 if (!innerScript) {
4281 return false;
4282 }
4283
4284 if (!RemoveReferencedNames(cx, innerScript, remainingNames)) {
4285 return false;
4286 }
4287 }
4288
4289 return true;
4290 }
4291
4292 static bool AnalyzeEntrainedVariablesInScript(JSContext* cx,
4293 HandleScript script,
4294 HandleScript innerScript) {
4295 PropertyNameSet remainingNames(cx);
4296
4297 for (BindingIter bi(script); bi; bi++) {
4298 if (bi.closedOver()) {
4299 PropertyName* name = bi.name()->asPropertyName();
4300 PropertyNameSet::AddPtr p = remainingNames.lookupForAdd(name);
4301 if (!p && !remainingNames.add(p, name)) {
4302 return false;
4303 }
4304 }
4305 }
4306
4307 if (!RemoveReferencedNames(cx, innerScript, remainingNames)) {
4308 return false;
4309 }
4310
4311 if (!remainingNames.empty()) {
4312 Sprinter buf(cx);
4313 if (!buf.init()) {
4314 return false;
4315 }
4316
4317 buf.printf("Script ");
4318
4319 if (JSAtom* name = script->function()->fullDisplayAtom()) {
4320 buf.putString(cx, name);
4321 buf.printf(" ");
4322 }
4323
4324 buf.printf("(%s:%u) has variables entrained by ", script->filename(),
4325 script->lineno());
4326
4327 if (JSAtom* name = innerScript->function()->fullDisplayAtom()) {
4328 buf.putString(cx, name);
4329 buf.printf(" ");
4330 }
4331
4332 buf.printf("(%s:%u) ::", innerScript->filename(), innerScript->lineno());
4333
4334 for (PropertyNameSet::Range r = remainingNames.all(); !r.empty();
4335 r.popFront()) {
4336 buf.printf(" ");
4337 buf.putString(cx, r.front());
4338 }
4339
4340 JS::UniqueChars str = buf.release();
4341 if (!str) {
4342 return false;
4343 }
4344 printf("%s\n", str.get());
4345 }
4346
4347 RootedFunction fun(cx);
4348 RootedScript innerInnerScript(cx);
4349 for (JS::GCCellPtr gcThing : script->gcthings()) {
4350 if (!gcThing.is<JSObject>()) {
4351 continue;
4352 }
4353 JSObject* obj = &gcThing.as<JSObject>();
4354
4355 if (!obj->is<JSFunction>()) {
4356 continue;
4357 }
4358 fun = &obj->as<JSFunction>();
4359
4360 if (!fun->isInterpreted()) {
4361 continue;
4362 }
4363
4364 innerInnerScript = JSFunction::getOrCreateScript(cx, fun);
4365 if (!innerInnerScript) {
4366 return false;
4367 }
4368
4369 if (!AnalyzeEntrainedVariablesInScript(cx, script, innerInnerScript)) {
4370 return false;
4371 }
4372 }
4373
4374 return true;
4375 }
4376
4377 // Look for local variables in script or any other script inner to it, which are
4378 // part of the script's call object and are unnecessarily entrained by their own
4379 // inner scripts which do not refer to those variables. An example is:
4380 //
4381 // function foo() {
4382 // var a, b;
4383 // function bar() { return a; }
4384 // function baz() { return b; }
4385 // }
4386 //
4387 // |bar| unnecessarily entrains |b|, and |baz| unnecessarily entrains |a|.
4388 bool js::AnalyzeEntrainedVariables(JSContext* cx, HandleScript script) {
4389 RootedFunction fun(cx);
4390 RootedScript innerScript(cx);
4391 for (JS::GCCellPtr gcThing : script->gcthings()) {
4392 if (!gcThing.is<JSObject>()) {
4393 continue;
4394 }
4395 JSObject* obj = &gcThing.as<JSObject>();
4396
4397 if (!obj->is<JSFunction>()) {
4398 continue;
4399 }
4400 fun = &obj->as<JSFunction>();
4401
4402 if (!fun->isInterpreted()) {
4403 continue;
4404 }
4405
4406 innerScript = JSFunction::getOrCreateScript(cx, fun);
4407 if (!innerScript) {
4408 return false;
4409 }
4410
4411 if (fun->needsCallObject()) {
4412 if (!AnalyzeEntrainedVariablesInScript(cx, script, innerScript)) {
4413 return false;
4414 }
4415 }
4416
4417 if (!AnalyzeEntrainedVariables(cx, innerScript)) {
4418 return false;
4419 }
4420 }
4421
4422 return true;
4423 }
4424 #endif
4425
4426 JSObject* js::MaybeOptimizeBindUnqualifiedGlobalName(GlobalObject* global,
4427 PropertyName* name) {
4428 // We can bind name to the global lexical scope if the binding already
4429 // exists, is initialized, and is writable (i.e., an initialized
4430 // 'let') at compile time.
4431 GlobalLexicalEnvironmentObject* env = &global->lexicalEnvironment();
4432 mozilla::Maybe<PropertyInfo> prop = env->lookupPure(name);
4433 if (prop.isSome()) {
4434 if (prop->writable() &&
4435 !env->getSlot(prop->slot()).isMagic(JS_UNINITIALIZED_LEXICAL)) {
4436 return env;
4437 }
4438 return nullptr;
4439 }
4440
4441 prop = global->lookupPure(name);
4442 if (prop.isSome()) {
4443 // If the property does not currently exist on the global lexical
4444 // scope, we can bind name to the global object if the property
4445 // exists on the global and is non-configurable, as then it cannot
4446 // be shadowed.
4447 if (!prop->configurable()) {
4448 return global;
4449 }
4450 }
4451
4452 return nullptr;
4453 }
4454
4455 const char* EnvironmentObject::typeString() const {
4456 if (is<CallObject>()) {
4457 return "CallObject";
4458 }
4459 if (is<VarEnvironmentObject>()) {
4460 return "VarEnvironmentObject";
4461 }
4462 if (is<ModuleEnvironmentObject>()) {
4463 return "ModuleEnvironmentObject";
4464 }
4465 if (is<WasmInstanceEnvironmentObject>()) {
4466 return "WasmInstanceEnvironmentObject";
4467 }
4468 if (is<WasmFunctionCallObject>()) {
4469 return "WasmFunctionCallObject";
4470 }
4471 if (is<LexicalEnvironmentObject>()) {
4472 if (is<ScopedLexicalEnvironmentObject>()) {
4473 if (is<BlockLexicalEnvironmentObject>()) {
4474 if (is<NamedLambdaObject>()) {
4475 return "NamedLambdaObject";
4476 }
4477 return "BlockLexicalEnvironmentObject";
4478 }
4479 if (is<ClassBodyLexicalEnvironmentObject>()) {
4480 return "ClassBodyLexicalEnvironmentObject";
4481 }
4482 return "ScopedLexicalEnvironmentObject";
4483 }
4484
4485 if (is<ExtensibleLexicalEnvironmentObject>()) {
4486 if (is<GlobalLexicalEnvironmentObject>()) {
4487 return "GlobalLexicalEnvironmentObject";
4488 }
4489 if (is<NonSyntacticLexicalEnvironmentObject>()) {
4490 return "NonSyntacticLexicalEnvironmentObject";
4491 }
4492 return "ExtensibleLexicalEnvironmentObject";
4493 }
4494
4495 return "LexicalEnvironmentObject";
4496 }
4497 if (is<NonSyntacticVariablesObject>()) {
4498 return "NonSyntacticVariablesObject";
4499 }
4500 if (is<WithEnvironmentObject>()) {
4501 return "WithEnvironmentObject";
4502 }
4503 if (is<RuntimeLexicalErrorObject>()) {
4504 return "RuntimeLexicalErrorObject";
4505 }
4506
4507 return "EnvironmentObject";
4508 }
4509
4510 #if defined(DEBUG) || defined(JS_JITSPEW)
4511 static void DumpEnvironmentObject(JSObject* unrootedEnvObj) {
4512 JSContext* cx = TlsContext.get();
4513 if (!cx) {
4514 fprintf(stderr, "*** can't get JSContext for current thread\n");
4515 return;
4516 }
4517
4518 Rooted<JSObject*> envObj(cx, unrootedEnvObj);
4519 while (envObj) {
4520 Rooted<EnvironmentObject*> env(cx);
4521 if (envObj->is<EnvironmentObject>()) {
4522 env = &envObj->as<EnvironmentObject>();
4523 } else if (envObj->is<DebugEnvironmentProxy>()) {
4524 fprintf(stderr, "[DebugProxy] ");
4525 env = &envObj->as<DebugEnvironmentProxy>().environment();
4526 } else {
4527 MOZ_ASSERT(envObj->is<GlobalObject>());
4528 fprintf(stderr, "global\n");
4529 break;
4530 }
4531
4532 fprintf(stderr, "%s", env->typeString());
4533
4534 Rooted<Scope*> scope(cx);
4535 if (env->is<VarEnvironmentObject>()) {
4536 scope = &env->as<VarEnvironmentObject>().scope();
4537 }
4538 if (env->is<WasmInstanceEnvironmentObject>()) {
4539 scope = &env->as<WasmInstanceEnvironmentObject>().scope();
4540 } else if (env->is<WasmFunctionCallObject>()) {
4541 scope = &env->as<WasmFunctionCallObject>().scope();
4542 } else if (env->is<ScopedLexicalEnvironmentObject>()) {
4543 scope = &env->as<ScopedLexicalEnvironmentObject>().scope();
4544 }
4545
4546 if (scope) {
4547 fprintf(stderr, " {\n");
4548 for (Rooted<BindingIter> bi(cx, BindingIter(scope)); bi; bi++) {
4549 if (bi.location().kind() == BindingLocation::Kind::Environment) {
4550 UniqueChars bytes = AtomToPrintableString(cx, bi.name());
4551 if (!bytes) {
4552 fprintf(stderr, " *** out of memory\n");
4553 return;
4554 }
4555
4556 fprintf(stderr, " %u: %s %s\n", bi.location().slot(),
4557 BindingKindString(bi.kind()), bytes.get());
4558 }
4559 }
4560 fprintf(stderr, "}");
4561 }
4562
4563 fprintf(stderr, "\n");
4564
4565 if (envObj->is<DebugEnvironmentProxy>()) {
4566 envObj = &envObj->as<DebugEnvironmentProxy>().enclosingEnvironment();
4567 } else {
4568 envObj = &env->enclosingEnvironment();
4569 }
4570
4571 if (envObj) {
4572 fprintf(stderr, "-> ");
4573 }
4574 }
4575 }
4576
4577 void EnvironmentObject::dump() { DumpEnvironmentObject(this); }
4578
4579 void DebugEnvironmentProxy::dump() { DumpEnvironmentObject(this); }
4580 #endif /* defined(DEBUG) || defined(JS_JITSPEW) */