Debian Codegraph @

js/src/debugger/Frame.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 "debugger/Frame-inl.h"
8
9 #include "mozilla/Assertions.h" // for MOZ_ASSERT, MOZ_ASSERT_IF, MOZ_CRASH
10 #include "mozilla/HashTable.h" // for HashMapEntry
11 #include "mozilla/Maybe.h" // for Maybe
12 #include "mozilla/Range.h" // for Range
13 #include "mozilla/RangedPtr.h" // for RangedPtr
14 #include "mozilla/Result.h" // for Result
15 #include "mozilla/ScopeExit.h" // for ScopeExit
16 #include "mozilla/ThreadLocal.h" // for ThreadLocal
17 #include "mozilla/Vector.h" // for Vector
18
19 #include <stddef.h> // for size_t
20 #include <stdint.h> // for int32_t
21 #include <string.h> // for strlen
22 #include <utility> // for std::move
23
24 #include "jsnum.h" // for Int32ToString
25
26 #include "builtin/Array.h" // for NewDenseCopiedArray
27 #include "debugger/Debugger.h" // for Completion, Debugger
28 #include "debugger/DebugScript.h"
29 #include "debugger/Environment.h" // for DebuggerEnvironment
30 #include "debugger/NoExecute.h" // for LeaveDebuggeeNoExecute
31 #include "debugger/Object.h" // for DebuggerObject
32 #include "debugger/Script.h" // for DebuggerScript
33 #include "frontend/BytecodeCompiler.h" // for CompileGlobalScript, CompileGlobalScriptWithExtraBindings, CompileEvalScript
34 #include "frontend/FrontendContext.h" // for AutoReportFrontendContext
35 #include "gc/Barrier.h" // for HeapPtr
36 #include "gc/GC.h" // for MemoryUse
37 #include "gc/GCContext.h" // for JS::GCContext
38 #include "gc/Marking.h" // for IsAboutToBeFinalized
39 #include "gc/Tracer.h" // for TraceCrossCompartmentEdge
40 #include "gc/ZoneAllocator.h" // for AddCellMemory
41 #include "jit/JSJitFrameIter.h" // for InlineFrameIterator
42 #include "jit/RematerializedFrame.h" // for RematerializedFrame
43 #include "js/CallArgs.h" // for CallArgs
44 #include "js/EnvironmentChain.h" // JS::EnvironmentChain
45 #include "js/friend/ErrorMessages.h" // for GetErrorMessage, JSMSG_*
46 #include "js/GCVector.h" // for JS::StackGCVector
47 #include "js/Object.h" // for SetReservedSlot
48 #include "js/Proxy.h" // for PrivateValue
49 #include "js/RootingAPI.h" // for JS::Rooted, JS::Handle, JS::MutableHandle
50 #include "js/SourceText.h" // for SourceText, SourceOwnership
51 #include "js/StableStringChars.h" // for AutoStableStringChars
52 #include "vm/ArgumentsObject.h" // for ArgumentsObject
53 #include "vm/ArrayObject.h" // for ArrayObject
54 #include "vm/AsyncFunction.h" // for AsyncFunctionGeneratorObject
55 #include "vm/AsyncIteration.h" // for AsyncGeneratorObject
56 #include "vm/BytecodeUtil.h" // for JSDVG_SEARCH_STACK
57 #include "vm/Compartment.h" // for Compartment
58 #include "vm/EnvironmentObject.h" // for GlobalLexicalEnvironmentObject
59 #include "vm/GeneratorObject.h" // for AbstractGeneratorObject
60 #include "vm/GlobalObject.h" // for GlobalObject
61 #include "vm/Interpreter.h" // for Call, ExecuteKernel
62 #include "vm/JSAtomUtils.h" // for Atomize, AtomizeUTF8Chars
63 #include "vm/JSContext.h" // for JSContext, ReportValueError
64 #include "vm/JSFunction.h" // for JSFunction, NewNativeFunction
65 #include "vm/JSObject.h" // for JSObject, RequireObject
66 #include "vm/JSScript.h" // for JSScript
67 #include "vm/NativeObject.h" // for NativeDefineDataProperty
68 #include "vm/Realm.h" // for AutoRealm
69 #include "vm/Runtime.h" // for JSAtomState
70 #include "vm/Scope.h" // for PositionalFormalParameterIter
71 #include "vm/Stack.h" // for AbstractFramePtr, FrameIter
72 #include "vm/StringType.h" // for PropertyName, JSString
73 #include "wasm/WasmDebug.h" // for DebugState
74 #include "wasm/WasmDebugFrame.h" // for DebugFrame
75 #include "wasm/WasmInstance.h" // for Instance
76 #include "wasm/WasmJS.h" // for WasmInstanceObject
77
78 #include "debugger/Debugger-inl.h" // for Debugger::fromJSObject
79 #include "gc/WeakMap-inl.h" // for WeakMap::remove
80 #include "vm/Compartment-inl.h" // for Compartment::wrap
81 #include "vm/JSContext-inl.h" // for JSContext::check
82 #include "vm/JSObject-inl.h" // for NewObjectWithGivenProto
83 #include "vm/NativeObject-inl.h" // for NativeObject::global
84 #include "vm/ObjectOperations-inl.h" // for GetProperty
85 #include "vm/Realm-inl.h" // for AutoRealm::AutoRealm
86 #include "vm/Stack-inl.h" // for AbstractFramePtr::script
87
88 namespace js {
89 namespace jit {
90 class JitFrameLayout;
91 } /* namespace jit */
92 } /* namespace js */
93
94 using namespace js;
95
96 using JS::AutoStableStringChars;
97 using JS::CompileOptions;
98 using JS::SourceOwnership;
99 using JS::SourceText;
100 using mozilla::Maybe;
101
102 ScriptedOnStepHandler::ScriptedOnStepHandler(JSObject* object)
103 : object_(object) {
104 MOZ_ASSERT(object_->isCallable());
105 }
106
107 JSObject* ScriptedOnStepHandler::object() const { return object_; }
108
109 void ScriptedOnStepHandler::hold(JSObject* owner) {
110 AddCellMemory(owner, allocSize(), MemoryUse::DebuggerOnStepHandler);
111 }
112
113 void ScriptedOnStepHandler::drop(JS::GCContext* gcx, JSObject* owner) {
114 gcx->delete_(owner, this, allocSize(), MemoryUse::DebuggerOnStepHandler);
115 }
116
117 void ScriptedOnStepHandler::trace(JSTracer* tracer) {
118 TraceEdge(tracer, &object_, "OnStepHandlerFunction.object");
119 }
120
121 bool ScriptedOnStepHandler::onStep(JSContext* cx, Handle<DebuggerFrame*> frame,
122 ResumeMode& resumeMode,
123 MutableHandleValue vp) {
124 RootedValue fval(cx, ObjectValue(*object_));
125 RootedValue rval(cx);
126 if (!js::Call(cx, fval, frame, &rval)) {
127 return false;
128 }
129
130 return ParseResumptionValue(cx, rval, resumeMode, vp);
131 };
132
133 size_t ScriptedOnStepHandler::allocSize() const { return sizeof(*this); }
134
135 ScriptedOnPopHandler::ScriptedOnPopHandler(JSObject* object) : object_(object) {
136 MOZ_ASSERT(object->isCallable());
137 }
138
139 JSObject* ScriptedOnPopHandler::object() const { return object_; }
140
141 void ScriptedOnPopHandler::hold(JSObject* owner) {
142 AddCellMemory(owner, allocSize(), MemoryUse::DebuggerOnPopHandler);
143 }
144
145 void ScriptedOnPopHandler::drop(JS::GCContext* gcx, JSObject* owner) {
146 gcx->delete_(owner, this, allocSize(), MemoryUse::DebuggerOnPopHandler);
147 }
148
149 void ScriptedOnPopHandler::trace(JSTracer* tracer) {
150 TraceEdge(tracer, &object_, "OnStepHandlerFunction.object");
151 }
152
153 bool ScriptedOnPopHandler::onPop(JSContext* cx, Handle<DebuggerFrame*> frame,
154 const Completion& completion,
155 ResumeMode& resumeMode,
156 MutableHandleValue vp) {
157 Debugger* dbg = frame->owner();
158
159 RootedValue completionValue(cx);
160 if (!completion.buildCompletionValue(cx, dbg, &completionValue)) {
161 return false;
162 }
163
164 RootedValue fval(cx, ObjectValue(*object_));
165 RootedValue rval(cx);
166 if (!js::Call(cx, fval, frame, completionValue, &rval)) {
167 return false;
168 }
169
170 return ParseResumptionValue(cx, rval, resumeMode, vp);
171 };
172
173 size_t ScriptedOnPopHandler::allocSize() const { return sizeof(*this); }
174
175 js::Debugger* js::DebuggerFrame::owner() const {
176 JSObject* dbgobj = &getReservedSlot(OWNER_SLOT).toObject();
177 return Debugger::fromJSObject(dbgobj);
178 }
179
180 const JSClassOps DebuggerFrame::classOps_ = {
181 nullptr, // addProperty
182 nullptr, // delProperty
183 nullptr, // enumerate
184 nullptr, // newEnumerate
185 nullptr, // resolve
186 nullptr, // mayResolve
187 finalize, // finalize
188 nullptr, // call
189 nullptr, // construct
190 CallTraceMethod<DebuggerFrame>, // trace
191 };
192
193 const JSClass DebuggerFrame::class_ = {
194 "Frame",
195 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS) |
196 // We require foreground finalization so we can destruct GeneratorInfo's
197 // HeapPtrs.
198 JSCLASS_FOREGROUND_FINALIZE,
199 &DebuggerFrame::classOps_,
200 };
201
202 enum { JSSLOT_DEBUGARGUMENTS_FRAME, JSSLOT_DEBUGARGUMENTS_COUNT };
203
204 const JSClass DebuggerArguments::class_ = {
205 "Arguments",
206 JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_DEBUGARGUMENTS_COUNT),
207 };
208
209 bool DebuggerFrame::resume(const FrameIter& iter) {
210 FrameIter::Data* data = iter.copyData();
211 if (!data) {
212 return false;
213 }
214 setFrameIterData(data);
215 return true;
216 }
217
218 void DebuggerFrame::suspendWasmFrame(JS::GCContext* gcx) {
219 freeFrameIterData(gcx);
220 }
221
222 bool DebuggerFrame::hasAnyHooks() const {
223 return !getReservedSlot(ONSTEP_HANDLER_SLOT).isUndefined() ||
224 !getReservedSlot(ONPOP_HANDLER_SLOT).isUndefined();
225 }
226
227 /* static */
228 NativeObject* DebuggerFrame::initClass(JSContext* cx,
229 Handle<GlobalObject*> global,
230 HandleObject dbgCtor) {
231 return InitClass(cx, dbgCtor, nullptr, nullptr, "Frame", construct, 0,
232 properties_, methods_, nullptr, nullptr);
233 }
234
235 /* static */
236 DebuggerFrame* DebuggerFrame::create(
237 JSContext* cx, HandleObject proto, Handle<NativeObject*> debugger,
238 const FrameIter* maybeIter,
239 Handle<AbstractGeneratorObject*> maybeGenerator) {
240 Rooted<DebuggerFrame*> frame(
241 cx, NewObjectWithGivenProto<DebuggerFrame>(cx, proto));
242 if (!frame) {
243 return nullptr;
244 }
245
246 frame->setReservedSlot(OWNER_SLOT, ObjectValue(*debugger));
247
248 if (maybeIter) {
249 FrameIter::Data* data = maybeIter->copyData();
250 if (!data) {
251 return nullptr;
252 }
253
254 frame->setFrameIterData(data);
255 }
256
257 if (maybeGenerator) {
258 if (!DebuggerFrame::setGeneratorInfo(cx, frame, maybeGenerator)) {
259 frame->freeFrameIterData(cx->gcContext());
260 return nullptr;
261 }
262 }
263
264 return frame;
265 }
266
267 /**
268 * Information held by a DebuggerFrame about a generator/async call. A
269 * Debugger.Frame's GENERATOR_INFO_SLOT, if set, holds a PrivateValue pointing
270 * to one of these.
271 *
272 * This is created and attached as soon as a generator object is created for a
273 * debuggee generator/async frame, retained across suspensions and resumptions,
274 * and cleared when the generator call ends permanently.
275 *
276 * It may seem like this information might belong in ordinary reserved slots on
277 * the DebuggerFrame object. But that isn't possible:
278 *
279 * 1) Slots cannot contain cross-compartment references directly.
280 * 2) Ordinary cross-compartment wrappers aren't good enough, because the
281 * debugger must create its own magic entries in the wrapper table for the GC
282 * to get zone collection groups right.
283 * 3) Even if we make debugger wrapper table entries by hand, hiding
284 * cross-compartment edges as PrivateValues doesn't call post-barriers, and
285 * the generational GC won't update our pointer when the generator object
286 * gets tenured.
287 *
288 * Yes, officer, I definitely knew all this in advance and designed it this way
289 * the first time.
290 *
291 * Note that it is not necessary to have a second cross-compartment wrapper
292 * table entry to cover the pointer to the generator's script. The wrapper table
293 * entries play two roles: they help the GC put a debugger zone in the same zone
294 * group as its debuggee, and they serve as roots when collecting the debuggee
295 * zone, but not the debugger zone. Since an AbstractGeneratorObject holds a
296 * strong reference to its callee's script (via the callee), and the AGO and the
297 * script are always in the same compartment, it suffices to add a
298 * cross-compartment wrapper table entry for the Debugger.Frame -> AGO edge.
299 */
300 class DebuggerFrame::GeneratorInfo {
301 // An unwrapped cross-compartment reference to the generator object.
302 //
303 // Always an object.
304 //
305 // This cannot be GCPtr because we are not always destructed during sweeping;
306 // a Debugger.Frame's generator is also cleared when the generator returns
307 // permanently.
308 const HeapPtr<Value> unwrappedGenerator_;
309
310 // A cross-compartment reference to the generator's script.
311 const HeapPtr<JSScript*> generatorScript_;
312
313 public:
314 GeneratorInfo(Handle<AbstractGeneratorObject*> unwrappedGenerator,
315 HandleScript generatorScript)
316 : unwrappedGenerator_(ObjectValue(*unwrappedGenerator)),
317 generatorScript_(generatorScript) {}
318
319 // Trace a rooted instance of this class, e.g. a Rooted<GeneratorInfo>.
320 void trace(JSTracer* tracer) {
321 TraceRoot(tracer, &unwrappedGenerator_, "Debugger.Frame generator object");
322 TraceRoot(tracer, &generatorScript_, "Debugger.Frame generator script");
323 }
324 // Trace a GeneratorInfo from a DebuggerFrame object.
325 void trace(JSTracer* tracer, DebuggerFrame& frameObj) {
326 TraceCrossCompartmentEdge(tracer, &frameObj, &unwrappedGenerator_,
327 "Debugger.Frame generator object");
328 TraceCrossCompartmentEdge(tracer, &frameObj, &generatorScript_,
329 "Debugger.Frame generator script");
330 }
331
332 AbstractGeneratorObject& unwrappedGenerator() const {
333 return unwrappedGenerator_.toObject().as<AbstractGeneratorObject>();
334 }
335
336 JSScript* generatorScript() { return generatorScript_; }
337
338 bool isGeneratorScriptAboutToBeFinalized() {
339 return IsAboutToBeFinalized(generatorScript_);
340 }
341 };
342
343 bool js::DebuggerFrame::isSuspended() const {
344 return hasGeneratorInfo() &&
345 generatorInfo()->unwrappedGenerator().isSuspended();
346 }
347
348 js::AbstractGeneratorObject& js::DebuggerFrame::unwrappedGenerator() const {
349 return generatorInfo()->unwrappedGenerator();
350 }
351
352 #ifdef DEBUG
353 JSScript* js::DebuggerFrame::generatorScript() const {
354 return generatorInfo()->generatorScript();
355 }
356 #endif
357
358 /* static */
359 bool DebuggerFrame::setGeneratorInfo(JSContext* cx,
360 Handle<DebuggerFrame*> frame,
361 Handle<AbstractGeneratorObject*> genObj) {
362 cx->check(frame);
363
364 MOZ_ASSERT(!frame->hasGeneratorInfo());
365 MOZ_ASSERT(!genObj->isClosed());
366
367 // When we initialize the generator information, we do not need to adjust
368 // the stepper increment, because either it was already incremented when
369 // the step hook was added, or we're setting this into on a new DebuggerFrame
370 // that has not yet had the chance for a hook to be added to it.
371 MOZ_ASSERT_IF(frame->onStepHandler(), frame->frameIterData());
372 MOZ_ASSERT_IF(!frame->frameIterData(), !frame->onStepHandler());
373
374 // There are two relations we must establish:
375 //
376 // 1) The DebuggerFrame must point to the AbstractGeneratorObject.
377 //
378 // 2) The generator's script's observer count must be bumped.
379
380 RootedScript script(cx, genObj->callee().nonLazyScript());
381 Rooted<UniquePtr<GeneratorInfo>> info(
382 cx, cx->make_unique<GeneratorInfo>(genObj, script));
383 if (!info) {
384 return false;
385 }
386
387 AutoRealm ar(cx, script);
388
389 // All frames running a debuggee script must themselves be marked as
390 // debuggee frames. Bumping a script's generator observer count makes it a
391 // debuggee, so we need to mark all frames on the stack running it as
392 // debuggees as well, not just this one. This call takes care of all that.
393 if (!Debugger::ensureExecutionObservabilityOfScript(cx, script)) {
394 return false;
395 }
396
397 if (!DebugScript::incrementGeneratorObserverCount(cx, script)) {
398 return false;
399 }
400
401 InitReservedSlot(frame, GENERATOR_INFO_SLOT, info.release(),
402 MemoryUse::DebuggerFrameGeneratorInfo);
403 return true;
404 }
405
406 void DebuggerFrame::terminate(JS::GCContext* gcx, AbstractFramePtr frame) {
407 if (frameIterData()) {
408 // If no frame pointer was provided to decrement the stepper counter,
409 // then we must be terminating a generator, otherwise the stepper count
410 // would have no way to synchronize properly.
411 MOZ_ASSERT_IF(!frame, hasGeneratorInfo());
412
413 freeFrameIterData(gcx);
414 if (frame && !hasGeneratorInfo() && onStepHandler()) {
415 // If we are terminating a non-generator frame that had a step handler,
416 // we need to decrement the counter to keep things in sync.
417 decrementStepperCounter(gcx, frame);
418 }
419 }
420
421 if (!hasGeneratorInfo()) {
422 return;
423 }
424
425 GeneratorInfo* info = generatorInfo();
426
427 // 3) The generator's script's observer count must be dropped.
428 //
429 // For ordinary calls, Debugger.Frame objects drop the script's stepper count
430 // when the frame is popped, but for generators, they leave the stepper count
431 // incremented across suspensions. This means that, whereas ordinary calls
432 // never need to drop the stepper count from the D.F finalizer, generator
433 // calls may.
434 if (!info->isGeneratorScriptAboutToBeFinalized()) {
435 JSScript* generatorScript = info->generatorScript();
436 DebugScript::decrementGeneratorObserverCount(gcx, generatorScript);
437 if (onStepHandler()) {
438 // If we are terminating a generator frame that had a step handler,
439 // we need to decrement the counter to keep things in sync.
440 decrementStepperCounter(gcx, generatorScript);
441 }
442 }
443
444 // 1) The DebuggerFrame must no longer point to the AbstractGeneratorObject.
445 setReservedSlot(GENERATOR_INFO_SLOT, UndefinedValue());
446 gcx->delete_(this, info, MemoryUse::DebuggerFrameGeneratorInfo);
447 }
448
449 void DebuggerFrame::onGeneratorClosed(JS::GCContext* gcx) {
450 GeneratorInfo* info = generatorInfo();
451
452 // If the generator is closed, eagerly drop the onStep handler, to make sure
453 // the stepper counter matches in the assertion in DebugAPI::onSingleStep.
454 // Also clear the slot in order to suppress the decrementStepperCounter in
455 // DebuggerFrame::terminate.
456 if (!info->isGeneratorScriptAboutToBeFinalized()) {
457 JSScript* generatorScript = info->generatorScript();
458 OnStepHandler* handler = onStepHandler();
459 if (handler) {
460 decrementStepperCounter(gcx, generatorScript);
461 setReservedSlot(ONSTEP_HANDLER_SLOT, UndefinedValue());
462 handler->drop(gcx, this);
463 }
464 }
465 }
466
467 void DebuggerFrame::suspend(JS::GCContext* gcx) {
468 // There must be generator info because otherwise this would be the same
469 // overall behavior as terminate() except that here we do not properly
470 // adjust stepper counts.
471 MOZ_ASSERT(hasGeneratorInfo());
472
473 freeFrameIterData(gcx);
474 }
475
476 /* static */
477 bool DebuggerFrame::getCallee(JSContext* cx, Handle<DebuggerFrame*> frame,
478 MutableHandle<DebuggerObject*> result) {
479 RootedObject callee(cx);
480 if (frame->isOnStack()) {
481 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
482 if (referent.isFunctionFrame()) {
483 callee = referent.callee();
484 }
485 } else {
486 MOZ_ASSERT(frame->isSuspended());
487
488 callee = &frame->generatorInfo()->unwrappedGenerator().callee();
489 }
490
491 return frame->owner()->wrapNullableDebuggeeObject(cx, callee, result);
492 }
493
494 /* static */
495 bool DebuggerFrame::getIsConstructing(JSContext* cx,
496 Handle<DebuggerFrame*> frame,
497 bool& result) {
498 if (frame->isOnStack()) {
499 FrameIter iter = frame->getFrameIter(cx);
500
501 result = iter.isFunctionFrame() && iter.isConstructing();
502 } else {
503 MOZ_ASSERT(frame->isSuspended());
504
505 // Generators and async functions can't be constructed.
506 result = false;
507 }
508 return true;
509 }
510
511 static void UpdateFrameIterPc(FrameIter& iter) {
512 if (iter.abstractFramePtr().isWasmDebugFrame()) {
513 // Wasm debug frames don't need their pc updated -- it's null.
514 return;
515 }
516
517 if (iter.abstractFramePtr().isRematerializedFrame()) {
518 #ifdef DEBUG
519 // Rematerialized frames don't need their pc updated. The reason we
520 // need to update pc is because we might get the same Debugger.Frame
521 // object for multiple re-entries into debugger code from debuggee
522 // code. This reentrancy is not possible with rematerialized frames,
523 // because when returning to debuggee code, we would have bailed out
524 // to baseline.
525 //
526 // We walk the stack to assert that it doesn't need updating.
527 jit::RematerializedFrame* frame =
528 iter.abstractFramePtr().asRematerializedFrame();
529 jit::JitFrameLayout* jsFrame = (jit::JitFrameLayout*)frame->top();
530 jit::JitActivation* activation = iter.activation()->asJit();
531
532 JSContext* cx = TlsContext.get();
533 MOZ_ASSERT(cx == activation->cx());
534
535 ActivationIterator activationIter(cx);
536 while (activationIter.activation() != activation) {
537 ++activationIter;
538 }
539
540 OnlyJSJitFrameIter jitIter(activationIter);
541 while (!jitIter.frame().isIonJS() || jitIter.frame().jsFrame() != jsFrame) {
542 ++jitIter;
543 }
544
545 jit::InlineFrameIterator ionInlineIter(cx, &jitIter.frame());
546 while (ionInlineIter.frameNo() != frame->frameNo()) {
547 ++ionInlineIter;
548 }
549
550 MOZ_ASSERT(ionInlineIter.pc() == iter.pc());
551 #endif
552 return;
553 }
554
555 iter.updatePcQuadratic();
556 }
557
558 /* static */
559 bool DebuggerFrame::getEnvironment(JSContext* cx, Handle<DebuggerFrame*> frame,
560 MutableHandle<DebuggerEnvironment*> result) {
561 Debugger* dbg = frame->owner();
562 Rooted<Env*> env(cx);
563
564 if (frame->isOnStack()) {
565 FrameIter iter = frame->getFrameIter(cx);
566
567 if (iter.hasScript() && iter.script()->selfHosted()) {
568 result.set(nullptr);
569 return true;
570 }
571
572 {
573 AutoRealm ar(cx, iter.abstractFramePtr().environmentChain());
574 UpdateFrameIterPc(iter);
575 env = GetDebugEnvironmentForFrame(cx, iter.abstractFramePtr(), iter.pc());
576 }
577 } else {
578 MOZ_ASSERT(frame->isSuspended());
579
580 AbstractGeneratorObject& genObj =
581 frame->generatorInfo()->unwrappedGenerator();
582 JSScript* script = frame->generatorInfo()->generatorScript();
583
584 if (script->selfHosted()) {
585 result.set(nullptr);
586 return true;
587 }
588
589 {
590 AutoRealm ar(cx, &genObj.environmentChain());
591 env = GetDebugEnvironmentForSuspendedGenerator(cx, script, genObj);
592 }
593 }
594
595 if (!env) {
596 return false;
597 }
598
599 return dbg->wrapEnvironment(cx, env, result);
600 }
601
602 /* static */
603 bool DebuggerFrame::getOffset(JSContext* cx, Handle<DebuggerFrame*> frame,
604 size_t& result) {
605 if (frame->isOnStack()) {
606 FrameIter iter = frame->getFrameIter(cx);
607
608 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
609 if (referent.isWasmDebugFrame()) {
610 iter.wasmUpdateBytecodeOffset();
611 result = iter.wasmBytecodeOffset();
612 } else {
613 JSScript* script = iter.script();
614 UpdateFrameIterPc(iter);
615 jsbytecode* pc = iter.pc();
616 result = script->pcToOffset(pc);
617 }
618 } else {
619 MOZ_ASSERT(frame->isSuspended());
620
621 AbstractGeneratorObject& genObj =
622 frame->generatorInfo()->unwrappedGenerator();
623 JSScript* script = frame->generatorInfo()->generatorScript();
624 result = script->resumeOffsets()[genObj.resumeIndex()];
625 }
626 return true;
627 }
628
629 /* static */
630 bool DebuggerFrame::getOlder(JSContext* cx, Handle<DebuggerFrame*> frame,
631 MutableHandle<DebuggerFrame*> result) {
632 if (frame->isOnStack()) {
633 Debugger* dbg = frame->owner();
634 FrameIter iter = frame->getFrameIter(cx);
635
636 while (true) {
637 Activation& activation = *iter.activation();
638 ++iter;
639
640 // If the parent frame crosses an explicit async stack boundary, we
641 // treat that as an indication to stop traversing sync frames, so that
642 // the on-stack Debugger.Frame instances align with what you would
643 // see in a stringified stack trace.
644 if (iter.activation() != &activation && activation.asyncStack() &&
645 activation.asyncCallIsExplicit()) {
646 break;
647 }
648
649 // If there is no parent frame, we're done.
650 if (iter.done()) {
651 break;
652 }
653
654 if (dbg->observesFrame(iter)) {
655 if (iter.isIon() && !iter.ensureHasRematerializedFrame(cx)) {
656 return false;
657 }
658 return dbg->getFrame(cx, iter, result);
659 }
660 }
661 } else {
662 MOZ_ASSERT(frame->isSuspended());
663
664 // If the frame is suspended, there is no older frame.
665 }
666
667 result.set(nullptr);
668 return true;
669 }
670
671 /* static */
672 bool DebuggerFrame::getAsyncPromise(JSContext* cx, Handle<DebuggerFrame*> frame,
673 MutableHandle<DebuggerObject*> result) {
674 MOZ_ASSERT(frame->isOnStack() || frame->isSuspended());
675
676 if (!frame->hasGeneratorInfo()) {
677 // An on-stack frame may not have an associated generator yet when the
678 // frame is initially entered.
679 result.set(nullptr);
680 return true;
681 }
682
683 RootedObject resultObject(cx);
684 AbstractGeneratorObject& generator = frame->unwrappedGenerator();
685 if (generator.is<AsyncFunctionGeneratorObject>()) {
686 resultObject = generator.as<AsyncFunctionGeneratorObject>().promise();
687 } else if (generator.is<AsyncGeneratorObject>()) {
688 Rooted<AsyncGeneratorObject*> asyncGen(
689 cx, &generator.as<AsyncGeneratorObject>());
690 // In initial function execution, there is no promise.
691 if (!asyncGen->isQueueEmpty()) {
692 resultObject = AsyncGeneratorObject::peekRequest(asyncGen)->promise();
693 }
694 } else {
695 MOZ_CRASH("Unknown async generator type");
696 }
697
698 return frame->owner()->wrapNullableDebuggeeObject(cx, resultObject, result);
699 }
700
701 /* static */
702 bool DebuggerFrame::getThis(JSContext* cx, Handle<DebuggerFrame*> frame,
703 MutableHandleValue result) {
704 Debugger* dbg = frame->owner();
705
706 if (frame->isOnStack()) {
707 if (!requireScriptReferent(cx, frame)) {
708 return false;
709 }
710 FrameIter iter = frame->getFrameIter(cx);
711
712 {
713 AbstractFramePtr frame = iter.abstractFramePtr();
714 AutoRealm ar(cx, frame.environmentChain());
715
716 UpdateFrameIterPc(iter);
717
718 if (!GetThisValueForDebuggerFrameMaybeOptimizedOut(cx, frame, iter.pc(),
719 result)) {
720 return false;
721 }
722 }
723 } else {
724 MOZ_ASSERT(frame->isSuspended());
725
726 AbstractGeneratorObject& genObj =
727 frame->generatorInfo()->unwrappedGenerator();
728 AutoRealm ar(cx, &genObj);
729 JSScript* script = frame->generatorInfo()->generatorScript();
730
731 if (!GetThisValueForDebuggerSuspendedGeneratorMaybeOptimizedOut(
732 cx, genObj, script, result)) {
733 return false;
734 }
735 }
736
737 return dbg->wrapDebuggeeValue(cx, result);
738 }
739
740 /* static */
741 DebuggerFrameType DebuggerFrame::getType(Handle<DebuggerFrame*> frame) {
742 if (frame->isOnStack()) {
743 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
744
745 // Indirect eval frames are both isGlobalFrame() and isEvalFrame(), so the
746 // order of checks here is significant.
747 if (referent.isEvalFrame()) {
748 return DebuggerFrameType::Eval;
749 }
750
751 if (referent.isGlobalFrame()) {
752 return DebuggerFrameType::Global;
753 }
754
755 if (referent.isFunctionFrame()) {
756 return DebuggerFrameType::Call;
757 }
758
759 if (referent.isModuleFrame()) {
760 return DebuggerFrameType::Module;
761 }
762
763 if (referent.isWasmDebugFrame()) {
764 return DebuggerFrameType::WasmCall;
765 }
766 } else {
767 MOZ_ASSERT(frame->isSuspended());
768
769 return DebuggerFrameType::Call;
770 }
771
772 MOZ_CRASH("Unknown frame type");
773 }
774
775 /* static */
776 DebuggerFrameImplementation DebuggerFrame::getImplementation(
777 Handle<DebuggerFrame*> frame) {
778 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
779
780 if (referent.isBaselineFrame()) {
781 return DebuggerFrameImplementation::Baseline;
782 }
783
784 if (referent.isRematerializedFrame()) {
785 return DebuggerFrameImplementation::Ion;
786 }
787
788 if (referent.isWasmDebugFrame()) {
789 return DebuggerFrameImplementation::Wasm;
790 }
791
792 return DebuggerFrameImplementation::Interpreter;
793 }
794
795 /*
796 * If succesful, transfers the ownership of the given `handler` to this
797 * Debugger.Frame. Note that on failure, the ownership of `handler` is not
798 * transferred, and the caller is responsible for cleaning it up.
799 */
800 /* static */
801 bool DebuggerFrame::setOnStepHandler(JSContext* cx,
802 Handle<DebuggerFrame*> frame,
803 UniquePtr<OnStepHandler> handlerArg) {
804 // Handler has never been successfully associated with the frame so allow
805 // UniquePtr to delete it rather than calling drop() if we return early from
806 // this method..
807 Rooted<UniquePtr<OnStepHandler>> handler(cx, std::move(handlerArg));
808
809 OnStepHandler* prior = frame->onStepHandler();
810 if (handler.get() == prior) {
811 return true;
812 }
813
814 JS::GCContext* gcx = cx->gcContext();
815 if (frame->isOnStack()) {
816 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
817
818 // Adjust execution observability and step counts on whatever code (JS or
819 // Wasm) this frame is running.
820 if (handler && !prior) {
821 if (!frame->incrementStepperCounter(cx, referent)) {
822 return false;
823 }
824 } else if (!handler && prior) {
825 frame->decrementStepperCounter(cx->gcContext(), referent);
826 }
827 } else if (frame->isSuspended()) {
828 RootedScript script(cx, frame->generatorInfo()->generatorScript());
829
830 if (handler && !prior) {
831 if (!frame->incrementStepperCounter(cx, script)) {
832 return false;
833 }
834 } else if (!handler && prior) {
835 frame->decrementStepperCounter(cx->gcContext(), script);
836 }
837 } else {
838 // If the frame is entirely dead, we still allow setting the onStep
839 // handler, but it has no effect.
840 }
841
842 // Now that the stepper counts and observability are set correctly, we can
843 // actually switch the handler.
844 if (prior) {
845 prior->drop(gcx, frame);
846 }
847
848 if (handler) {
849 handler->hold(frame);
850 frame->setReservedSlot(ONSTEP_HANDLER_SLOT,
851 PrivateValue(handler.get().release()));
852 } else {
853 frame->setReservedSlot(ONSTEP_HANDLER_SLOT, UndefinedValue());
854 }
855
856 return true;
857 }
858
859 bool DebuggerFrame::incrementStepperCounter(JSContext* cx,
860 AbstractFramePtr referent) {
861 if (!referent.isWasmDebugFrame()) {
862 RootedScript script(cx, referent.script());
863 return incrementStepperCounter(cx, script);
864 }
865
866 wasm::Instance* instance = referent.asWasmDebugFrame()->instance();
867 wasm::DebugFrame* wasmFrame = referent.asWasmDebugFrame();
868 // Single stepping toggled off->on.
869 if (!instance->debug().incrementStepperCount(cx, instance,
870 wasmFrame->funcIndex())) {
871 return false;
872 }
873
874 return true;
875 }
876
877 bool DebuggerFrame::incrementStepperCounter(JSContext* cx,
878 HandleScript script) {
879 // Single stepping toggled off->on.
880 AutoRealm ar(cx, script);
881 // Ensure observability *before* incrementing the step mode count.
882 // Calling this function after calling incrementStepperCount
883 // will make it a no-op.
884 if (!Debugger::ensureExecutionObservabilityOfScript(cx, script)) {
885 return false;
886 }
887 if (!DebugScript::incrementStepperCount(cx, script)) {
888 return false;
889 }
890
891 return true;
892 }
893
894 void DebuggerFrame::decrementStepperCounter(JS::GCContext* gcx,
895 AbstractFramePtr referent) {
896 if (!referent.isWasmDebugFrame()) {
897 decrementStepperCounter(gcx, referent.script());
898 return;
899 }
900
901 wasm::Instance* instance = referent.asWasmDebugFrame()->instance();
902 wasm::DebugFrame* wasmFrame = referent.asWasmDebugFrame();
903 // Single stepping toggled on->off.
904 instance->debug().decrementStepperCount(gcx, instance,
905 wasmFrame->funcIndex());
906 }
907
908 void DebuggerFrame::decrementStepperCounter(JS::GCContext* gcx,
909 JSScript* script) {
910 // Single stepping toggled on->off.
911 DebugScript::decrementStepperCount(gcx, script);
912 }
913
914 /* static */
915 bool DebuggerFrame::getArguments(JSContext* cx, Handle<DebuggerFrame*> frame,
916 MutableHandle<DebuggerArguments*> result) {
917 Value argumentsv = frame->getReservedSlot(ARGUMENTS_SLOT);
918 if (!argumentsv.isUndefined()) {
919 result.set(argumentsv.isObject()
920 ? &argumentsv.toObject().as<DebuggerArguments>()
921 : nullptr);
922 return true;
923 }
924
925 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
926
927 Rooted<DebuggerArguments*> arguments(cx);
928 if (referent.hasArgs()) {
929 Rooted<GlobalObject*> global(cx, &frame->global());
930 RootedObject proto(cx, GlobalObject::getOrCreateArrayPrototype(cx, global));
931 if (!proto) {
932 return false;
933 }
934 arguments = DebuggerArguments::create(cx, proto, frame);
935 if (!arguments) {
936 return false;
937 }
938 } else {
939 arguments = nullptr;
940 }
941
942 result.set(arguments);
943 frame->setReservedSlot(ARGUMENTS_SLOT, ObjectOrNullValue(result));
944 return true;
945 }
946
947 static WithEnvironmentObject* CreateBindingsEnv(
948 JSContext* cx, JS::Handle<JSObject*> enclosingEnv,
949 JS::Handle<JS::StackGCVector<JS::PropertyKey>> bindingKeys,
950 JS::Handle<JS::StackGCVector<JS::Value>> bindingValues) {
951 JS::Rooted<PlainObject*> bindingsObj(cx,
952 NewPlainObjectWithProto(cx, nullptr));
953 if (!bindingsObj) {
954 return nullptr;
955 }
956 JS::Rooted<JS::PropertyKey> id(cx);
957 JS::Rooted<JS::Value> val(cx);
958 for (size_t i = 0; i < bindingKeys.length(); i++) {
959 id = bindingKeys[i];
960 cx->markId(id);
961 val = bindingValues[i];
962 if (!cx->compartment()->wrap(cx, &val) ||
963 !NativeDefineDataProperty(cx, bindingsObj, id, val, 0)) {
964 return nullptr;
965 }
966 }
967
968 JS::EnvironmentChain envChain(cx, JS::SupportUnscopables::No);
969 if (!envChain.append(bindingsObj)) {
970 return nullptr;
971 }
972
973 return CreateObjectsForEnvironmentChain(cx, envChain, enclosingEnv);
974 }
975
976 /*
977 * Evaluate |chars| in the environment |envArg|, treating that source as
978 * appearing starting at |evalOptions.lineno()| in |evalOptions.filename()|.
979 * Store the return value in |*rval|.
980 *
981 * If |evalOptions.kind()| is either `Frame` or |FrameWithExtraBindings|,
982 * evaluate as for a direct eval in |frame|; |envArg| must be |frame|'s
983 * DebugScopeObject; either way,
984 * |frame|'s scope is where newly declared variables go. In this case,
985 * |frame| must have a computed 'this' value.
986 *
987 * If |evalOptions.kind()| is one of the following, |bindingKeys| and
988 * |bindingValues| should represent the bindings, and a new
989 * |WithEnvironmentObject| is created with |envArg| as enclosing environment,
990 * and used for the evaluation.
991 * - FrameWithExtraBindings
992 * - GlobalWithExtraInnerBindings
993 * - GlobalWithExtraOuterBindings
994 */
995 static bool EvaluateInEnv(
996 JSContext* cx, Handle<Env*> envArg, AbstractFramePtr frame,
997 mozilla::Range<const char16_t> chars, const EvalOptions& evalOptions,
998 JS::Handle<JS::StackGCVector<JS::PropertyKey>> bindingKeys,
999 JS::Handle<JS::StackGCVector<JS::Value>> bindingValues,
1000 MutableHandleValue rval) {
1001 #ifdef DEBUG
1002 switch (evalOptions.kind()) {
1003 case EvalOptions::EnvKind::Frame:
1004 case EvalOptions::EnvKind::FrameWithExtraBindings:
1005 MOZ_ASSERT(frame);
1006 break;
1007 case EvalOptions::EnvKind::Global:
1008 MOZ_ASSERT(!frame);
1009 break;
1010 case EvalOptions::EnvKind::GlobalWithExtraInnerBindings:
1011 case EvalOptions::EnvKind::GlobalWithExtraOuterBindings:
1012 MOZ_ASSERT(!frame);
1013 break;
1014 }
1015 #endif
1016
1017 cx->check(envArg, frame);
1018
1019 CompileOptions options(cx);
1020 const char* filename =
1021 evalOptions.filename() ? evalOptions.filename() : "debugger eval code";
1022 options.setIsRunOnce(true)
1023 .setNoScriptRval(false)
1024 .setFileAndLine(filename, evalOptions.lineno())
1025 .setHideScriptFromDebugger(evalOptions.hideFromDebugger())
1026 .setIntroductionType("debugger eval")
1027 /* Do not perform the Javascript filename validation security check for
1028 * javascript executions sent through the debugger. Besides making up
1029 * a filename for these codepaths, we must allow arbitrary JS execution
1030 * for the Browser toolbox to function. */
1031 .setSkipFilenameValidation(true)
1032 /* Don't lazy parse. We need full-parsing to correctly support bytecode
1033 * emission for private fields/methods. See EmitterScope::lookupPrivate.
1034 */
1035 .setForceFullParse();
1036
1037 if (frame && frame.hasScript() && frame.script()->strict()) {
1038 options.setForceStrictMode();
1039 }
1040
1041 SourceText<char16_t> srcBuf;
1042 if (!srcBuf.init(cx, chars.begin().get(), chars.length(),
1043 SourceOwnership::Borrowed)) {
1044 return false;
1045 }
1046
1047 // Compile the script and compute the environment object.
1048 JS::Rooted<JSScript*> script(cx);
1049 JS::Rooted<JSObject*> env(cx);
1050 switch (evalOptions.kind()) {
1051 case EvalOptions::EnvKind::FrameWithExtraBindings: {
1052 env = CreateBindingsEnv(cx, envArg, bindingKeys, bindingValues);
1053 if (!env) {
1054 return false;
1055 }
1056 [[fallthrough]];
1057 }
1058 case EvalOptions::EnvKind::Frame: {
1059 // Default to |envArg| when no extra bindings are used.
1060 if (!env) {
1061 env = envArg;
1062 }
1063
1064 options.setNonSyntacticScope(true);
1065
1066 Rooted<Scope*> scope(
1067 cx, GlobalScope::createEmpty(cx, ScopeKind::NonSyntactic));
1068 if (!scope) {
1069 return false;
1070 }
1071
1072 script = frontend::CompileEvalScript(cx, options, srcBuf, scope, env);
1073 if (!script) {
1074 return false;
1075 }
1076 break;
1077 }
1078 case EvalOptions::EnvKind::Global: {
1079 AutoReportFrontendContext fc(cx);
1080 script = frontend::CompileGlobalScript(cx, &fc, options, srcBuf,
1081 ScopeKind::Global);
1082 if (!script) {
1083 return false;
1084 }
1085
1086 env = envArg;
1087 break;
1088 }
1089 case EvalOptions::EnvKind::GlobalWithExtraOuterBindings: {
1090 // Do not consider executeInGlobal{,WithBindings} as an eval, but instead
1091 // as executing a series of statements at the global level. This is to
1092 // circumvent the fresh lexical scope that all eval have, so that the
1093 // users of executeInGlobal{,WithBindings}, like the web console, may add
1094 // new bindings to the global scope.
1095
1096 MOZ_ASSERT(envArg == &cx->global()->lexicalEnvironment());
1097
1098 options.setNonSyntacticScope(true);
1099
1100 AutoReportFrontendContext fc(cx);
1101 script = frontend::CompileGlobalScriptWithExtraBindings(
1102 cx, &fc, options, srcBuf, bindingKeys, bindingValues, &env);
1103 if (!script) {
1104 return false;
1105 }
1106 break;
1107 }
1108 case EvalOptions::EnvKind::GlobalWithExtraInnerBindings: {
1109 env = CreateBindingsEnv(cx, envArg, bindingKeys, bindingValues);
1110 if (!env) {
1111 return false;
1112 }
1113
1114 options.setNonSyntacticScope(true);
1115
1116 AutoReportFrontendContext fc(cx);
1117 script = frontend::CompileGlobalScript(cx, &fc, options, srcBuf,
1118 ScopeKind::NonSyntactic);
1119 if (!script) {
1120 return false;
1121 }
1122 break;
1123 }
1124 }
1125
1126 return ExecuteKernel(cx, script, env, frame, rval);
1127 }
1128
1129 Result<Completion> js::DebuggerGenericEval(
1130 JSContext* cx, const mozilla::Range<const char16_t> chars,
1131 HandleObject bindings, const EvalOptions& options, Debugger* dbg,
1132 HandleObject envArg, FrameIter* iter) {
1133 #ifdef DEBUG
1134 switch (options.kind()) {
1135 case EvalOptions::EnvKind::Frame:
1136 MOZ_ASSERT(iter);
1137 MOZ_ASSERT(!envArg);
1138 MOZ_ASSERT(!bindings);
1139 break;
1140 case EvalOptions::EnvKind::FrameWithExtraBindings:
1141 MOZ_ASSERT(iter);
1142 MOZ_ASSERT(!envArg);
1143 MOZ_ASSERT(bindings);
1144 break;
1145 case EvalOptions::EnvKind::Global:
1146 MOZ_ASSERT(!iter);
1147 MOZ_ASSERT(envArg);
1148 MOZ_ASSERT(envArg->is<GlobalLexicalEnvironmentObject>());
1149 MOZ_ASSERT(!bindings);
1150 break;
1151 case EvalOptions::EnvKind::GlobalWithExtraInnerBindings:
1152 case EvalOptions::EnvKind::GlobalWithExtraOuterBindings:
1153 MOZ_ASSERT(!iter);
1154 MOZ_ASSERT(envArg);
1155 MOZ_ASSERT(envArg->is<GlobalLexicalEnvironmentObject>());
1156 MOZ_ASSERT(bindings);
1157 break;
1158 }
1159 #endif
1160
1161 // Gather keys and values of bindings, if any. This must be done in the
1162 // debugger compartment, since that is where any exceptions must be thrown.
1163 RootedIdVector keys(cx);
1164 RootedValueVector values(cx);
1165 if (bindings) {
1166 if (!GetPropertyKeys(cx, bindings, JSITER_OWNONLY, &keys) ||
1167 !values.growBy(keys.length())) {
1168 return cx->alreadyReportedError();
1169 }
1170 for (size_t i = 0; i < keys.length(); i++) {
1171 MutableHandleValue valp = values[i];
1172 if (!GetProperty(cx, bindings, bindings, keys[i], valp) ||
1173 !dbg->unwrapDebuggeeValue(cx, valp)) {
1174 return cx->alreadyReportedError();
1175 }
1176 }
1177 }
1178
1179 Maybe<AutoRealm> ar;
1180 if (iter) {
1181 ar.emplace(cx, iter->environmentChain(cx));
1182 } else {
1183 ar.emplace(cx, envArg);
1184 }
1185
1186 Rooted<Env*> env(cx);
1187 if (iter) {
1188 env = GetDebugEnvironmentForFrame(cx, iter->abstractFramePtr(), iter->pc());
1189 if (!env) {
1190 return cx->alreadyReportedError();
1191 }
1192 } else {
1193 env = envArg;
1194 }
1195
1196 if (iter && iter->hasScript() && iter->script()->allowRelazify()) {
1197 // This is a function that was first lazy, and delazified, and it's marked
1198 // as relazifyable because there was no inner function.
1199 //
1200 // Evaluating a script can create inner function, which should prevent the
1201 // relazification.
1202 iter->script()->clearAllowRelazify();
1203 }
1204
1205 // Note whether we are in an evaluation that might invoke the OnNativeCall
1206 // hook, so that the JITs will be disabled.
1207 Maybe<AutoNoteExclusiveDebuggerOnEval> noteEvaluation;
1208 if (dbg->isExclusiveDebuggerOnEval()) {
1209 noteEvaluation.emplace(cx, dbg);
1210 }
1211
1212 // Run the code and produce the completion value.
1213 LeaveDebuggeeNoExecute nnx(cx);
1214 RootedValue rval(cx);
1215 AbstractFramePtr frame = iter ? iter->abstractFramePtr() : NullFramePtr();
1216
1217 bool ok = EvaluateInEnv(cx, env, frame, chars, options, keys, values, &rval);
1218 Rooted<Completion> completion(cx, Completion::fromJSResult(cx, ok, rval));
1219 ar.reset();
1220 return completion.get();
1221 }
1222
1223 /* static */
1224 Result<Completion> DebuggerFrame::eval(JSContext* cx,
1225 Handle<DebuggerFrame*> frame,
1226 mozilla::Range<const char16_t> chars,
1227 HandleObject bindings,
1228 const EvalOptions& options) {
1229 MOZ_ASSERT(options.kind() == EvalOptions::EnvKind::Frame ||
1230 options.kind() == EvalOptions::EnvKind::FrameWithExtraBindings);
1231 MOZ_ASSERT(frame->isOnStack());
1232
1233 Debugger* dbg = frame->owner();
1234 FrameIter iter = frame->getFrameIter(cx);
1235
1236 UpdateFrameIterPc(iter);
1237
1238 return DebuggerGenericEval(cx, chars, bindings, options, dbg, nullptr, &iter);
1239 }
1240
1241 bool DebuggerFrame::isOnStack() const {
1242 // Note: this is equivalent to checking frameIterData() != nullptr.
1243 return !getFixedSlot(FRAME_ITER_SLOT).isUndefined();
1244 }
1245
1246 bool DebuggerFrame::isOnStackOrSuspendedWasmStack() const {
1247 // Note: this is equivalent to checking `frameIterData() != nullptr &&
1248 // !hasGeneratorInfo()`, but works also when called from the trace hook
1249 // during a moving GC.
1250 return !getFixedSlot(FRAME_ITER_SLOT).isUndefined() ||
1251 getFixedSlot(GENERATOR_INFO_SLOT).isUndefined();
1252 }
1253
1254 OnStepHandler* DebuggerFrame::onStepHandler() const {
1255 return maybePtrFromReservedSlot<OnStepHandler>(ONSTEP_HANDLER_SLOT);
1256 }
1257
1258 OnPopHandler* DebuggerFrame::onPopHandler() const {
1259 return maybePtrFromReservedSlot<OnPopHandler>(ONPOP_HANDLER_SLOT);
1260 }
1261
1262 void DebuggerFrame::setOnPopHandler(JSContext* cx, OnPopHandler* handler) {
1263 OnPopHandler* prior = onPopHandler();
1264 if (handler == prior) {
1265 return;
1266 }
1267
1268 JS::GCContext* gcx = cx->gcContext();
1269
1270 if (prior) {
1271 prior->drop(gcx, this);
1272 }
1273
1274 if (handler) {
1275 setReservedSlot(ONPOP_HANDLER_SLOT, PrivateValue(handler));
1276 handler->hold(this);
1277 } else {
1278 setReservedSlot(ONPOP_HANDLER_SLOT, UndefinedValue());
1279 }
1280 }
1281
1282 FrameIter::Data* DebuggerFrame::frameIterData() const {
1283 return maybePtrFromReservedSlot<FrameIter::Data>(FRAME_ITER_SLOT);
1284 }
1285
1286 /* static */
1287 AbstractFramePtr DebuggerFrame::getReferent(Handle<DebuggerFrame*> frame) {
1288 FrameIter iter(*frame->frameIterData());
1289 return iter.abstractFramePtr();
1290 }
1291
1292 FrameIter DebuggerFrame::getFrameIter(JSContext* cx) {
1293 FrameIter::Data* data = frameIterData();
1294 MOZ_ASSERT(data);
1295 MOZ_ASSERT(data->cx_ == cx);
1296
1297 return FrameIter(*data);
1298 }
1299
1300 /* static */
1301 bool DebuggerFrame::requireScriptReferent(JSContext* cx,
1302 Handle<DebuggerFrame*> frame) {
1303 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
1304 if (!referent.hasScript()) {
1305 RootedValue frameobj(cx, ObjectValue(*frame));
1306 ReportValueError(cx, JSMSG_DEBUG_BAD_REFERENT, JSDVG_SEARCH_STACK, frameobj,
1307 nullptr, "a script frame");
1308 return false;
1309 }
1310 return true;
1311 }
1312
1313 void DebuggerFrame::setFrameIterData(FrameIter::Data* data) {
1314 MOZ_ASSERT(data);
1315 MOZ_ASSERT(!frameIterData());
1316 InitReservedSlot(this, FRAME_ITER_SLOT, data,
1317 MemoryUse::DebuggerFrameIterData);
1318 }
1319
1320 void DebuggerFrame::freeFrameIterData(JS::GCContext* gcx) {
1321 if (FrameIter::Data* data = frameIterData()) {
1322 gcx->delete_(this, data, MemoryUse::DebuggerFrameIterData);
1323 setReservedSlot(FRAME_ITER_SLOT, UndefinedValue());
1324 }
1325 }
1326
1327 bool DebuggerFrame::replaceFrameIterData(JSContext* cx, const FrameIter& iter) {
1328 FrameIter::Data* data = iter.copyData();
1329 if (!data) {
1330 return false;
1331 }
1332 freeFrameIterData(cx->gcContext());
1333 setFrameIterData(data);
1334 return true;
1335 }
1336
1337 /* static */
1338 void DebuggerFrame::finalize(JS::GCContext* gcx, JSObject* obj) {
1339 MOZ_ASSERT(gcx->onMainThread());
1340
1341 DebuggerFrame& frameobj = obj->as<DebuggerFrame>();
1342
1343 // Connections between dying Debugger.Frames and their
1344 // AbstractGeneratorObjects, as well as the frame's stack data should have
1345 // been by a call to terminate() from sweepAll or some other place.
1346 MOZ_ASSERT(!frameobj.hasGeneratorInfo());
1347 MOZ_ASSERT(!frameobj.frameIterData());
1348 OnStepHandler* onStepHandler = frameobj.onStepHandler();
1349 if (onStepHandler) {
1350 onStepHandler->drop(gcx, &frameobj);
1351 }
1352 OnPopHandler* onPopHandler = frameobj.onPopHandler();
1353 if (onPopHandler) {
1354 onPopHandler->drop(gcx, &frameobj);
1355 }
1356 }
1357
1358 void DebuggerFrame::trace(JSTracer* trc) {
1359 OnStepHandler* onStepHandler = this->onStepHandler();
1360 if (onStepHandler) {
1361 onStepHandler->trace(trc);
1362 }
1363 OnPopHandler* onPopHandler = this->onPopHandler();
1364 if (onPopHandler) {
1365 onPopHandler->trace(trc);
1366 }
1367
1368 if (hasGeneratorInfo()) {
1369 generatorInfo()->trace(trc, *this);
1370 }
1371 }
1372
1373 /* static */
1374 DebuggerFrame* DebuggerFrame::check(JSContext* cx, HandleValue thisv) {
1375 JSObject* thisobj = RequireObject(cx, thisv);
1376 if (!thisobj) {
1377 return nullptr;
1378 }
1379 if (!thisobj->is<DebuggerFrame>()) {
1380 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1381 JSMSG_INCOMPATIBLE_PROTO, "Debugger.Frame",
1382 "method", thisobj->getClass()->name);
1383 return nullptr;
1384 }
1385
1386 return &thisobj->as<DebuggerFrame>();
1387 }
1388
1389 struct MOZ_STACK_CLASS DebuggerFrame::CallData {
1390 JSContext* cx;
1391 const CallArgs& args;
1392
1393 Handle<DebuggerFrame*> frame;
1394
1395 CallData(JSContext* cx, const CallArgs& args, Handle<DebuggerFrame*> frame)
1396 : cx(cx), args(args), frame(frame) {}
1397
1398 bool argumentsGetter();
1399 bool calleeGetter();
1400 bool constructingGetter();
1401 bool environmentGetter();
1402 bool generatorGetter();
1403 bool asyncPromiseGetter();
1404 bool olderSavedFrameGetter();
1405 bool liveGetter();
1406 bool onStackGetter();
1407 bool terminatedGetter();
1408 bool offsetGetter();
1409 bool olderGetter();
1410 bool getScript();
1411 bool thisGetter();
1412 bool typeGetter();
1413 bool implementationGetter();
1414 bool onStepGetter();
1415 bool onStepSetter();
1416 bool onPopGetter();
1417 bool onPopSetter();
1418 bool evalMethod();
1419 bool evalWithBindingsMethod();
1420
1421 using Method = bool (CallData::*)();
1422
1423 template <Method MyMethod>
1424 static bool ToNative(JSContext* cx, unsigned argc, Value* vp);
1425
1426 bool ensureOnStack() const;
1427 bool ensureOnStackOrSuspended() const;
1428 };
1429
1430 template <DebuggerFrame::CallData::Method MyMethod>
1431 /* static */
1432 bool DebuggerFrame::CallData::ToNative(JSContext* cx, unsigned argc,
1433 Value* vp) {
1434 CallArgs args = CallArgsFromVp(argc, vp);
1435
1436 Rooted<DebuggerFrame*> frame(cx, DebuggerFrame::check(cx, args.thisv()));
1437 if (!frame) {
1438 return false;
1439 }
1440
1441 CallData data(cx, args, frame);
1442 return (data.*MyMethod)();
1443 }
1444
1445 static bool EnsureOnStack(JSContext* cx, Handle<DebuggerFrame*> frame) {
1446 MOZ_ASSERT(frame);
1447 if (!frame->isOnStack()) {
1448 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1449 JSMSG_DEBUG_NOT_ON_STACK, "Debugger.Frame");
1450 return false;
1451 }
1452
1453 return true;
1454 }
1455 static bool EnsureOnStackOrSuspended(JSContext* cx,
1456 Handle<DebuggerFrame*> frame) {
1457 MOZ_ASSERT(frame);
1458 if (!frame->isOnStack() && !frame->isSuspended()) {
1459 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1460 JSMSG_DEBUG_NOT_ON_STACK_OR_SUSPENDED,
1461 "Debugger.Frame");
1462 return false;
1463 }
1464
1465 return true;
1466 }
1467
1468 bool DebuggerFrame::CallData::ensureOnStack() const {
1469 return EnsureOnStack(cx, frame);
1470 }
1471 bool DebuggerFrame::CallData::ensureOnStackOrSuspended() const {
1472 return EnsureOnStackOrSuspended(cx, frame);
1473 }
1474
1475 bool DebuggerFrame::CallData::typeGetter() {
1476 if (!ensureOnStackOrSuspended()) {
1477 return false;
1478 }
1479
1480 DebuggerFrameType type = DebuggerFrame::getType(frame);
1481
1482 JSString* str;
1483 switch (type) {
1484 case DebuggerFrameType::Eval:
1485 str = cx->names().eval;
1486 break;
1487 case DebuggerFrameType::Global:
1488 str = cx->names().global;
1489 break;
1490 case DebuggerFrameType::Call:
1491 str = cx->names().call;
1492 break;
1493 case DebuggerFrameType::Module:
1494 str = cx->names().module;
1495 break;
1496 case DebuggerFrameType::WasmCall:
1497 str = cx->names().wasmcall;
1498 break;
1499 default:
1500 MOZ_CRASH("bad DebuggerFrameType value");
1501 }
1502
1503 args.rval().setString(str);
1504 return true;
1505 }
1506
1507 bool DebuggerFrame::CallData::implementationGetter() {
1508 if (!ensureOnStack()) {
1509 return false;
1510 }
1511
1512 DebuggerFrameImplementation implementation =
1513 DebuggerFrame::getImplementation(frame);
1514
1515 const char* s;
1516 switch (implementation) {
1517 case DebuggerFrameImplementation::Baseline:
1518 s = "baseline";
1519 break;
1520 case DebuggerFrameImplementation::Ion:
1521 s = "ion";
1522 break;
1523 case DebuggerFrameImplementation::Interpreter:
1524 s = "interpreter";
1525 break;
1526 case DebuggerFrameImplementation::Wasm:
1527 s = "wasm";
1528 break;
1529 default:
1530 MOZ_CRASH("bad DebuggerFrameImplementation value");
1531 }
1532
1533 JSAtom* str = Atomize(cx, s, strlen(s));
1534 if (!str) {
1535 return false;
1536 }
1537
1538 args.rval().setString(str);
1539 return true;
1540 }
1541
1542 bool DebuggerFrame::CallData::environmentGetter() {
1543 if (!ensureOnStackOrSuspended()) {
1544 return false;
1545 }
1546
1547 Rooted<DebuggerEnvironment*> result(cx);
1548 if (!DebuggerFrame::getEnvironment(cx, frame, &result)) {
1549 return false;
1550 }
1551
1552 if (!result) {
1553 args.rval().setNull();
1554 return true;
1555 }
1556
1557 args.rval().setObject(*result);
1558 return true;
1559 }
1560
1561 bool DebuggerFrame::CallData::calleeGetter() {
1562 if (!ensureOnStackOrSuspended()) {
1563 return false;
1564 }
1565
1566 Rooted<DebuggerObject*> result(cx);
1567 if (!DebuggerFrame::getCallee(cx, frame, &result)) {
1568 return false;
1569 }
1570
1571 args.rval().setObjectOrNull(result);
1572 return true;
1573 }
1574
1575 bool DebuggerFrame::CallData::generatorGetter() {
1576 JS_ReportErrorASCII(cx,
1577 "Debugger.Frame.prototype.generator has been removed. "
1578 "Use frame.script.isGeneratorFunction instead.");
1579 return false;
1580 }
1581
1582 bool DebuggerFrame::CallData::constructingGetter() {
1583 if (!ensureOnStackOrSuspended()) {
1584 return false;
1585 }
1586
1587 bool result;
1588 if (!DebuggerFrame::getIsConstructing(cx, frame, result)) {
1589 return false;
1590 }
1591
1592 args.rval().setBoolean(result);
1593 return true;
1594 }
1595
1596 bool DebuggerFrame::CallData::asyncPromiseGetter() {
1597 if (!ensureOnStackOrSuspended()) {
1598 return false;
1599 }
1600
1601 RootedScript script(cx);
1602 if (frame->isOnStack()) {
1603 FrameIter iter = frame->getFrameIter(cx);
1604 AbstractFramePtr framePtr = iter.abstractFramePtr();
1605
1606 if (!framePtr.isWasmDebugFrame()) {
1607 script = framePtr.script();
1608 }
1609 } else {
1610 MOZ_ASSERT(frame->isSuspended());
1611 script = frame->generatorInfo()->generatorScript();
1612 }
1613 // The async promise value is only provided for async functions and
1614 // async generator functions.
1615 if (!script || !script->isAsync()) {
1616 args.rval().setUndefined();
1617 return true;
1618 }
1619
1620 Rooted<DebuggerObject*> result(cx);
1621 if (!DebuggerFrame::getAsyncPromise(cx, frame, &result)) {
1622 return false;
1623 }
1624
1625 args.rval().setObjectOrNull(result);
1626 return true;
1627 }
1628
1629 bool DebuggerFrame::CallData::olderSavedFrameGetter() {
1630 if (!ensureOnStackOrSuspended()) {
1631 return false;
1632 }
1633
1634 Rooted<SavedFrame*> result(cx);
1635 if (!DebuggerFrame::getOlderSavedFrame(cx, frame, &result)) {
1636 return false;
1637 }
1638
1639 args.rval().setObjectOrNull(result);
1640 return true;
1641 }
1642
1643 /* static */
1644 bool DebuggerFrame::getOlderSavedFrame(JSContext* cx,
1645 Handle<DebuggerFrame*> frame,
1646 MutableHandle<SavedFrame*> result) {
1647 if (frame->isOnStack()) {
1648 Debugger* dbg = frame->owner();
1649 FrameIter iter = frame->getFrameIter(cx);
1650
1651 while (true) {
1652 Activation& activation = *iter.activation();
1653 ++iter;
1654
1655 // If the parent frame crosses an explicit async stack boundary, or we
1656 // have hit the end of the synchronous frames, we want to switch over
1657 // to using SavedFrames.
1658 if (iter.activation() != &activation && activation.asyncStack() &&
1659 (activation.asyncCallIsExplicit() || iter.done())) {
1660 const char* cause = activation.asyncCause();
1661 Rooted<JSAtom*> causeAtom(cx,
1662 AtomizeUTF8Chars(cx, cause, strlen(cause)));
1663 if (!causeAtom) {
1664 return false;
1665 }
1666 Rooted<SavedFrame*> stackObj(cx, activation.asyncStack());
1667
1668 return cx->realm()->savedStacks().copyAsyncStack(
1669 cx, stackObj, causeAtom, result, mozilla::Nothing());
1670 }
1671
1672 // If there are no more parent frames, we're done.
1673 if (iter.done()) {
1674 break;
1675 }
1676
1677 // If we hit another frame that we observe, then there is no saved
1678 // frame that we'd want to return.
1679 if (dbg->observesFrame(iter)) {
1680 break;
1681 }
1682 }
1683 } else {
1684 MOZ_ASSERT(frame->isSuspended());
1685 }
1686
1687 result.set(nullptr);
1688 return true;
1689 }
1690
1691 bool DebuggerFrame::CallData::thisGetter() {
1692 if (!ensureOnStackOrSuspended()) {
1693 return false;
1694 }
1695
1696 return DebuggerFrame::getThis(cx, frame, args.rval());
1697 }
1698
1699 bool DebuggerFrame::CallData::olderGetter() {
1700 if (!ensureOnStackOrSuspended()) {
1701 return false;
1702 }
1703
1704 Rooted<DebuggerFrame*> result(cx);
1705 if (!DebuggerFrame::getOlder(cx, frame, &result)) {
1706 return false;
1707 }
1708
1709 args.rval().setObjectOrNull(result);
1710 return true;
1711 }
1712
1713 // The getter used for each element of frame.arguments.
1714 // See DebuggerFrame::getArguments.
1715 static bool DebuggerArguments_getArg(JSContext* cx, unsigned argc, Value* vp) {
1716 CallArgs args = CallArgsFromVp(argc, vp);
1717 int32_t i = args.callee().as<JSFunction>().getExtendedSlot(0).toInt32();
1718
1719 // Check that the this value is an Arguments object.
1720 RootedObject argsobj(cx, RequireObject(cx, args.thisv()));
1721 if (!argsobj) {
1722 return false;
1723 }
1724 if (argsobj->getClass() != &DebuggerArguments::class_) {
1725 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1726 JSMSG_INCOMPATIBLE_PROTO, "Arguments",
1727 "getArgument", argsobj->getClass()->name);
1728 return false;
1729 }
1730
1731 RootedValue framev(cx, argsobj->as<NativeObject>().getReservedSlot(
1732 JSSLOT_DEBUGARGUMENTS_FRAME));
1733 Rooted<DebuggerFrame*> thisobj(cx, DebuggerFrame::check(cx, framev));
1734 if (!thisobj || !EnsureOnStack(cx, thisobj)) {
1735 return false;
1736 }
1737
1738 FrameIter iter = thisobj->getFrameIter(cx);
1739 AbstractFramePtr frame = iter.abstractFramePtr();
1740
1741 // TODO handle wasm frame arguments -- they are not yet reflectable.
1742 MOZ_ASSERT(!frame.isWasmDebugFrame(), "a wasm frame args");
1743
1744 // Since getters can be extracted and applied to other objects,
1745 // there is no guarantee this object has an ith argument.
1746 MOZ_ASSERT(i >= 0);
1747 RootedValue arg(cx);
1748 RootedScript script(cx);
1749 if (unsigned(i) < frame.numActualArgs()) {
1750 script = frame.script();
1751 if (unsigned(i) < frame.numFormalArgs()) {
1752 for (PositionalFormalParameterIter fi(script); fi; fi++) {
1753 if (fi.argumentSlot() == unsigned(i)) {
1754 // We might've been called before the CallObject was created or
1755 // initialized in the prologue.
1756 if (fi.closedOver() && frame.hasInitialEnvironment() &&
1757 iter.pc() >= script->main()) {
1758 arg = frame.callObj().aliasedBinding(fi);
1759 } else {
1760 arg = frame.unaliasedActual(i, DONT_CHECK_ALIASING);
1761 }
1762 break;
1763 }
1764 }
1765 } else if (script->argsObjAliasesFormals() && frame.hasArgsObj()) {
1766 arg = frame.argsObj().arg(i);
1767 } else {
1768 arg = frame.unaliasedActual(i, DONT_CHECK_ALIASING);
1769 }
1770 } else {
1771 arg.setUndefined();
1772 }
1773
1774 if (!thisobj->owner()->wrapDebuggeeValue(cx, &arg)) {
1775 return false;
1776 }
1777 args.rval().set(arg);
1778 return true;
1779 }
1780
1781 /* static */
1782 DebuggerArguments* DebuggerArguments::create(JSContext* cx, HandleObject proto,
1783 Handle<DebuggerFrame*> frame) {
1784 AbstractFramePtr referent = DebuggerFrame::getReferent(frame);
1785
1786 Rooted<DebuggerArguments*> obj(
1787 cx, NewObjectWithGivenProto<DebuggerArguments>(cx, proto));
1788 if (!obj) {
1789 return nullptr;
1790 }
1791
1792 JS::SetReservedSlot(obj, FRAME_SLOT, ObjectValue(*frame));
1793
1794 MOZ_ASSERT(referent.numActualArgs() <= 0x7fffffff);
1795 unsigned fargc = referent.numActualArgs();
1796 RootedValue fargcVal(cx, Int32Value(fargc));
1797 if (!NativeDefineDataProperty(cx, obj, cx->names().length, fargcVal,
1798 JSPROP_PERMANENT | JSPROP_READONLY)) {
1799 return nullptr;
1800 }
1801
1802 Rooted<jsid> id(cx);
1803 for (unsigned i = 0; i < fargc; i++) {
1804 RootedFunction getobj(cx);
1805 getobj = NewNativeFunction(cx, DebuggerArguments_getArg, 0, nullptr,
1806 gc::AllocKind::FUNCTION_EXTENDED);
1807 if (!getobj) {
1808 return nullptr;
1809 }
1810 id = PropertyKey::Int(i);
1811 if (!NativeDefineAccessorProperty(cx, obj, id, getobj, nullptr,
1812 JSPROP_ENUMERATE)) {
1813 return nullptr;
1814 }
1815 getobj->setExtendedSlot(0, Int32Value(i));
1816 }
1817
1818 return obj;
1819 }
1820
1821 bool DebuggerFrame::CallData::argumentsGetter() {
1822 if (!ensureOnStack()) {
1823 return false;
1824 }
1825
1826 Rooted<DebuggerArguments*> result(cx);
1827 if (!DebuggerFrame::getArguments(cx, frame, &result)) {
1828 return false;
1829 }
1830
1831 args.rval().setObjectOrNull(result);
1832 return true;
1833 }
1834
1835 bool DebuggerFrame::CallData::getScript() {
1836 if (!ensureOnStackOrSuspended()) {
1837 return false;
1838 }
1839
1840 Rooted<DebuggerScript*> scriptObject(cx);
1841
1842 Debugger* debug = frame->owner();
1843 if (frame->isOnStack()) {
1844 FrameIter iter = frame->getFrameIter(cx);
1845 AbstractFramePtr framePtr = iter.abstractFramePtr();
1846
1847 if (framePtr.isWasmDebugFrame()) {
1848 Rooted<WasmInstanceObject*> instance(cx,
1849 framePtr.wasmInstance()->object());
1850 scriptObject = debug->wrapWasmScript(cx, instance);
1851 } else {
1852 RootedScript script(cx, framePtr.script());
1853 scriptObject = debug->wrapScript(cx, script);
1854 }
1855 } else {
1856 MOZ_ASSERT(frame->isSuspended());
1857 RootedScript script(cx, frame->generatorInfo()->generatorScript());
1858 scriptObject = debug->wrapScript(cx, script);
1859 }
1860 if (!scriptObject) {
1861 return false;
1862 }
1863
1864 args.rval().setObject(*scriptObject);
1865 return true;
1866 }
1867
1868 bool DebuggerFrame::CallData::offsetGetter() {
1869 if (!ensureOnStackOrSuspended()) {
1870 return false;
1871 }
1872
1873 size_t result;
1874 if (!DebuggerFrame::getOffset(cx, frame, result)) {
1875 return false;
1876 }
1877
1878 args.rval().setNumber(double(result));
1879 return true;
1880 }
1881
1882 bool DebuggerFrame::CallData::liveGetter() {
1883 JS_ReportErrorASCII(
1884 cx, "Debugger.Frame.prototype.live has been renamed to .onStack");
1885 return false;
1886 }
1887
1888 bool DebuggerFrame::CallData::onStackGetter() {
1889 args.rval().setBoolean(frame->isOnStack());
1890 return true;
1891 }
1892
1893 bool DebuggerFrame::CallData::terminatedGetter() {
1894 args.rval().setBoolean(!frame->isOnStack() && !frame->isSuspended());
1895 return true;
1896 }
1897
1898 static bool IsValidHook(const Value& v) {
1899 return v.isUndefined() || (v.isObject() && v.toObject().isCallable());
1900 }
1901
1902 bool DebuggerFrame::CallData::onStepGetter() {
1903 OnStepHandler* handler = frame->onStepHandler();
1904 RootedValue value(
1905 cx, handler ? ObjectOrNullValue(handler->object()) : UndefinedValue());
1906 MOZ_ASSERT(IsValidHook(value));
1907 args.rval().set(value);
1908 return true;
1909 }
1910
1911 bool DebuggerFrame::CallData::onStepSetter() {
1912 if (!args.requireAtLeast(cx, "Debugger.Frame.set onStep", 1)) {
1913 return false;
1914 }
1915 if (!IsValidHook(args[0])) {
1916 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1917 JSMSG_NOT_CALLABLE_OR_UNDEFINED);
1918 return false;
1919 }
1920
1921 UniquePtr<ScriptedOnStepHandler> handler;
1922 if (!args[0].isUndefined()) {
1923 handler = cx->make_unique<ScriptedOnStepHandler>(&args[0].toObject());
1924 if (!handler) {
1925 return false;
1926 }
1927 }
1928
1929 if (!DebuggerFrame::setOnStepHandler(cx, frame, std::move(handler))) {
1930 return false;
1931 }
1932
1933 args.rval().setUndefined();
1934 return true;
1935 }
1936
1937 bool DebuggerFrame::CallData::onPopGetter() {
1938 OnPopHandler* handler = frame->onPopHandler();
1939 RootedValue value(
1940 cx, handler ? ObjectValue(*handler->object()) : UndefinedValue());
1941 MOZ_ASSERT(IsValidHook(value));
1942 args.rval().set(value);
1943 return true;
1944 }
1945
1946 bool DebuggerFrame::CallData::onPopSetter() {
1947 if (!args.requireAtLeast(cx, "Debugger.Frame.set onPop", 1)) {
1948 return false;
1949 }
1950 if (!IsValidHook(args[0])) {
1951 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1952 JSMSG_NOT_CALLABLE_OR_UNDEFINED);
1953 return false;
1954 }
1955
1956 ScriptedOnPopHandler* handler = nullptr;
1957 if (!args[0].isUndefined()) {
1958 handler = cx->new_<ScriptedOnPopHandler>(&args[0].toObject());
1959 if (!handler) {
1960 return false;
1961 }
1962 }
1963
1964 frame->setOnPopHandler(cx, handler);
1965
1966 args.rval().setUndefined();
1967 return true;
1968 }
1969
1970 bool DebuggerFrame::CallData::evalMethod() {
1971 if (!ensureOnStack()) {
1972 return false;
1973 }
1974
1975 if (!args.requireAtLeast(cx, "Debugger.Frame.prototype.eval", 1)) {
1976 return false;
1977 }
1978
1979 AutoStableStringChars stableChars(cx);
1980 if (!ValueToStableChars(cx, "Debugger.Frame.prototype.eval", args[0],
1981 stableChars)) {
1982 return false;
1983 }
1984 mozilla::Range<const char16_t> chars = stableChars.twoByteRange();
1985
1986 EvalOptions options(EvalOptions::EnvKind::Frame);
1987 if (!ParseEvalOptions(cx, args.get(1), options)) {
1988 return false;
1989 }
1990
1991 Rooted<Completion> comp(cx);
1992 JS_TRY_VAR_OR_RETURN_FALSE(
1993 cx, comp, DebuggerFrame::eval(cx, frame, chars, nullptr, options));
1994 return comp.get().buildCompletionValue(cx, frame->owner(), args.rval());
1995 }
1996
1997 bool DebuggerFrame::CallData::evalWithBindingsMethod() {
1998 if (!ensureOnStack()) {
1999 return false;
2000 }
2001
2002 if (!args.requireAtLeast(cx, "Debugger.Frame.prototype.evalWithBindings",
2003 2)) {
2004 return false;
2005 }
2006
2007 AutoStableStringChars stableChars(cx);
2008 if (!ValueToStableChars(cx, "Debugger.Frame.prototype.evalWithBindings",
2009 args[0], stableChars)) {
2010 return false;
2011 }
2012 mozilla::Range<const char16_t> chars = stableChars.twoByteRange();
2013
2014 RootedObject bindings(cx, RequireObject(cx, args[1]));
2015 if (!bindings) {
2016 return false;
2017 }
2018
2019 EvalOptions options(EvalOptions::EnvKind::FrameWithExtraBindings);
2020 if (!ParseEvalOptions(cx, args.get(2), options)) {
2021 return false;
2022 }
2023
2024 Rooted<Completion> comp(cx);
2025 JS_TRY_VAR_OR_RETURN_FALSE(
2026 cx, comp, DebuggerFrame::eval(cx, frame, chars, bindings, options));
2027 return comp.get().buildCompletionValue(cx, frame->owner(), args.rval());
2028 }
2029
2030 /* static */
2031 bool DebuggerFrame::construct(JSContext* cx, unsigned argc, Value* vp) {
2032 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
2033 "Debugger.Frame");
2034 return false;
2035 }
2036
2037 const JSPropertySpec DebuggerFrame::properties_[] = {
2038 JS_DEBUG_PSG("arguments", argumentsGetter),
2039 JS_DEBUG_PSG("callee", calleeGetter),
2040 JS_DEBUG_PSG("constructing", constructingGetter),
2041 JS_DEBUG_PSG("environment", environmentGetter),
2042 JS_DEBUG_PSG("generator", generatorGetter),
2043 JS_DEBUG_PSG("live", liveGetter),
2044 JS_DEBUG_PSG("onStack", onStackGetter),
2045 JS_DEBUG_PSG("terminated", terminatedGetter),
2046 JS_DEBUG_PSG("offset", offsetGetter),
2047 JS_DEBUG_PSG("older", olderGetter),
2048 JS_DEBUG_PSG("olderSavedFrame", olderSavedFrameGetter),
2049 JS_DEBUG_PSG("script", getScript),
2050 JS_DEBUG_PSG("this", thisGetter),
2051 JS_DEBUG_PSG("asyncPromise", asyncPromiseGetter),
2052 JS_DEBUG_PSG("type", typeGetter),
2053 JS_DEBUG_PSG("implementation", implementationGetter),
2054 JS_DEBUG_PSGS("onStep", onStepGetter, onStepSetter),
2055 JS_DEBUG_PSGS("onPop", onPopGetter, onPopSetter),
2056 JS_PS_END,
2057 };
2058
2059 const JSFunctionSpec DebuggerFrame::methods_[] = {
2060 JS_DEBUG_FN("eval", evalMethod, 1),
2061 JS_DEBUG_FN("evalWithBindings", evalWithBindingsMethod, 1),
2062 JS_FS_END,
2063 };
2064
2065 JSObject* js::IdVectorToArray(JSContext* cx, HandleIdVector ids) {
2066 if (MOZ_UNLIKELY(ids.length() > UINT32_MAX)) {
2067 ReportAllocationOverflow(cx);
2068 return nullptr;
2069 }
2070
2071 Rooted<ArrayObject*> arr(cx, NewDenseFullyAllocatedArray(cx, ids.length()));
2072 if (!arr) {
2073 return nullptr;
2074 }
2075
2076 arr->ensureDenseInitializedLength(0, ids.length());
2077
2078 for (size_t i = 0, len = ids.length(); i < len; i++) {
2079 jsid id = ids[i];
2080 Value v;
2081 if (id.isInt()) {
2082 JSString* str = Int32ToString<CanGC>(cx, id.toInt());
2083 if (!str) {
2084 return nullptr;
2085 }
2086 v = StringValue(str);
2087 } else if (id.isAtom()) {
2088 v = StringValue(id.toAtom());
2089 } else if (id.isSymbol()) {
2090 v = SymbolValue(id.toSymbol());
2091 } else {
2092 MOZ_CRASH("IdVector must contain only string, int, and Symbol jsids");
2093 }
2094
2095 arr->initDenseElement(i, v);
2096 }
2097
2098 return arr;
2099 }