Debian Codegraph @

js/src/debugger/Debugger.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/Debugger-inl.h"
8
9 #include "mozilla/Attributes.h" // for MOZ_STACK_CLASS, MOZ_RAII
10 #include "mozilla/DebugOnly.h" // for DebugOnly
11 #include "mozilla/DoublyLinkedList.h" // for DoublyLinkedList<>::Iterator
12 #include "mozilla/HashTable.h" // for HashSet<>::Range, HashMapEntry
13 #include "mozilla/Maybe.h" // for Maybe, Nothing, Some
14 #include "mozilla/ScopeExit.h" // for MakeScopeExit, ScopeExit
15 #include "mozilla/Sprintf.h" // for SprintfLiteral
16 #include "mozilla/ThreadLocal.h" // for ThreadLocal
17 #include "mozilla/TimeStamp.h" // for TimeStamp
18 #include "mozilla/UniquePtr.h" // for UniquePtr
19 #include "mozilla/Variant.h" // for AsVariant, AsVariantTemporary
20 #include "mozilla/Vector.h" // for Vector, Vector<>::ConstRange
21
22 #include <algorithm> // for std::find, std::max
23 #include <functional> // for function
24 #include <stddef.h> // for size_t
25 #include <stdint.h> // for uint32_t, uint64_t, int32_t
26 #include <string.h> // for strlen, strcmp
27 #include <type_traits> // for std::underlying_type_t
28 #include <utility> // for std::move
29
30 #include "jsapi.h" // for CallArgs, CallArgsFromVp
31 #include "jstypes.h" // for JS_PUBLIC_API
32
33 #include "builtin/Array.h" // for NewDenseFullyAllocatedArray
34 #include "debugger/DebugAPI.h" // for ResumeMode, DebugAPI
35 #include "debugger/DebuggerMemory.h" // for DebuggerMemory
36 #include "debugger/DebugScript.h" // for DebugScript
37 #include "debugger/Environment.h" // for DebuggerEnvironment
38 #ifdef MOZ_EXECUTION_TRACING
39 # include "debugger/ExecutionTracer.h" // for ExecutionTracer::onEnterFrame, ExecutionTracer::onLeaveFrame
40 #endif
41 #include "debugger/Frame.h" // for DebuggerFrame
42 #include "debugger/NoExecute.h" // for EnterDebuggeeNoExecute
43 #include "debugger/Object.h" // for DebuggerObject
44 #include "debugger/Script.h" // for DebuggerScript
45 #include "debugger/Source.h" // for DebuggerSource
46 #include "frontend/CompilationStencil.h" // for CompilationStencil
47 #include "frontend/FrontendContext.h" // for AutoReportFrontendContext
48 #include "frontend/Parser.h" // for Parser
49 #include "gc/GC.h" // for IterateScripts
50 #include "gc/GCContext.h" // for JS::GCContext
51 #include "gc/GCMarker.h" // for GCMarker
52 #include "gc/GCRuntime.h" // for GCRuntime, AutoEnterIteration
53 #include "gc/HashUtil.h" // for DependentAddPtr
54 #include "gc/Marking.h" // for IsAboutToBeFinalized
55 #include "gc/PublicIterators.h" // for RealmsIter, CompartmentsIter
56 #include "gc/Statistics.h" // for Statistics::SliceData
57 #include "gc/Tracer.h" // for TraceEdge
58 #include "gc/Zone.h" // for Zone
59 #include "gc/ZoneAllocator.h" // for ZoneAllocPolicy
60 #include "jit/BaselineDebugModeOSR.h" // for RecompileOnStackBaselineScriptsForDebugMode
61 #include "jit/BaselineJIT.h" // for FinishDiscardBaselineScript
62 #include "jit/Invalidation.h" // for RecompileInfoVector
63 #include "jit/JitContext.h" // for JitContext
64 #include "jit/JitOptions.h" // for fuzzingSafe
65 #include "jit/JitScript.h" // for JitScript
66 #include "jit/JSJitFrameIter.h" // for InlineFrameIterator
67 #include "jit/RematerializedFrame.h" // for RematerializedFrame
68 #include "js/CallAndConstruct.h" // JS::IsCallable
69 #include "js/Conversions.h" // for ToBoolean, ToUint32
70 #include "js/Debug.h" // for Builder::Object, Builder
71 #include "js/friend/ErrorMessages.h" // for GetErrorMessage, JSMSG_*
72 #include "js/GCAPI.h" // for GarbageCollectionEvent
73 #include "js/GCVariant.h" // for GCVariant
74 #include "js/HeapAPI.h" // for ExposeObjectToActiveJS
75 #include "js/Promise.h" // for AutoDebuggerJobQueueInterruption
76 #include "js/PropertyAndElement.h" // for JS_GetProperty
77 #include "js/Proxy.h" // for PropertyDescriptor
78 #include "js/SourceText.h" // for SourceText
79 #include "js/StableStringChars.h" // for AutoStableStringChars
80 #include "js/UbiNode.h" // for Node, RootList, Edge
81 #include "js/UbiNodeBreadthFirst.h" // for BreadthFirst
82 #include "js/Wrapper.h" // for CheckedUnwrapStatic
83 #include "util/Identifier.h" // for IsIdentifier
84 #include "util/Text.h" // for DuplicateString, js_strlen
85 #include "vm/ArrayObject.h" // for ArrayObject
86 #include "vm/AsyncFunction.h" // for AsyncFunctionGeneratorObject
87 #include "vm/AsyncIteration.h" // for AsyncGeneratorObject
88 #include "vm/BytecodeUtil.h" // for JSDVG_IGNORE_STACK
89 #include "vm/Compartment.h" // for CrossCompartmentKey
90 #include "vm/EnvironmentObject.h" // for IsSyntacticEnvironment
91 #include "vm/ErrorReporting.h" // for ReportErrorToGlobal
92 #include "vm/GeneratorObject.h" // for AbstractGeneratorObject
93 #include "vm/GlobalObject.h" // for GlobalObject
94 #include "vm/Interpreter.h" // for Call, ReportIsNotFunction
95 #include "vm/Iteration.h" // for CreateIterResultObject
96 #include "vm/JSAtomUtils.h" // for Atomize, AtomizeUTF8Chars, AtomIsMarked, AtomToId, ClassName
97 #include "vm/JSContext.h" // for JSContext
98 #include "vm/JSFunction.h" // for JSFunction
99 #include "vm/JSObject.h" // for JSObject, RequireObject,
100 #include "vm/JSScript.h" // for BaseScript, ScriptSourceObject
101 #include "vm/ObjectOperations.h" // for DefineDataProperty
102 #include "vm/PlainObject.h" // for js::PlainObject
103 #include "vm/PromiseObject.h" // for js::PromiseObject
104 #include "vm/ProxyObject.h" // for ProxyObject, JSObject::is
105 #include "vm/Realm.h" // for AutoRealm, Realm
106 #include "vm/Runtime.h" // for ReportOutOfMemory, JSRuntime
107 #include "vm/SavedFrame.h" // for SavedFrame
108 #include "vm/SavedStacks.h" // for SavedStacks
109 #include "vm/Scope.h" // for Scope
110 #include "vm/StringType.h" // for JSString, PropertyName
111 #include "vm/WrapperObject.h" // for CrossCompartmentWrapperObject
112 #include "wasm/WasmDebug.h" // for DebugState
113 #include "wasm/WasmInstance.h" // for Instance
114 #include "wasm/WasmJS.h" // for WasmInstanceObject
115 #include "wasm/WasmRealm.h" // for Realm
116 #include "wasm/WasmTypeDecls.h" // for WasmInstanceObjectVector
117
118 #include "debugger/DebugAPI-inl.h"
119 #include "debugger/Environment-inl.h" // for DebuggerEnvironment::owner
120 #include "debugger/Frame-inl.h" // for DebuggerFrame::hasGeneratorInfo
121 #include "debugger/Object-inl.h" // for DebuggerObject::owner and isInstance.
122 #include "debugger/Script-inl.h" // for DebuggerScript::getReferent
123 #include "gc/GC-inl.h" // for ZoneCellIter
124 #include "gc/Marking-inl.h" // for MaybeForwarded
125 #include "gc/StableCellHasher-inl.h"
126 #include "gc/WeakMap-inl.h" // for DebuggerWeakMap::trace
127 #include "vm/Compartment-inl.h" // for Compartment::wrap
128 #include "vm/GeckoProfiler-inl.h" // for AutoSuppressProfilerSampling
129 #include "vm/JSAtomUtils-inl.h" // for AtomToId, ValueToId
130 #include "vm/JSContext-inl.h" // for JSContext::check
131 #include "vm/JSObject-inl.h" // for JSObject::isCallable, NewTenuredObjectWithGivenProto
132 #include "vm/JSScript-inl.h" // for JSScript::isDebuggee, JSScript
133 #include "vm/NativeObject-inl.h" // for NativeObject::ensureDenseInitializedLength
134 #include "vm/ObjectOperations-inl.h" // for GetProperty, HasProperty
135 #include "vm/Realm-inl.h" // for AutoRealm::AutoRealm
136 #include "vm/Stack-inl.h" // for AbstractFramePtr::script
137
138 namespace js {
139
140 namespace frontend {
141 class FullParseHandler;
142 }
143
144 namespace gc {
145 struct Cell;
146 }
147
148 namespace jit {
149 class BaselineFrame;
150 }
151
152 } /* namespace js */
153
154 using namespace js;
155
156 using JS::AutoStableStringChars;
157 using JS::CompileOptions;
158 using JS::dbg::Builder;
159 using mozilla::AsVariant;
160 using mozilla::DebugOnly;
161 using mozilla::MakeScopeExit;
162 using mozilla::Maybe;
163 using mozilla::Nothing;
164 using mozilla::Some;
165 using mozilla::TimeStamp;
166
167 /*** Utils ******************************************************************/
168
169 bool js::IsInterpretedNonSelfHostedFunction(JSFunction* fun) {
170 return fun->isInterpreted() && !fun->isSelfHostedBuiltin();
171 }
172
173 JSScript* js::GetOrCreateFunctionScript(JSContext* cx, HandleFunction fun) {
174 MOZ_ASSERT(IsInterpretedNonSelfHostedFunction(fun));
175 AutoRealm ar(cx, fun);
176 return JSFunction::getOrCreateScript(cx, fun);
177 }
178
179 ArrayObject* js::GetFunctionParameterNamesArray(JSContext* cx,
180 HandleFunction fun) {
181 RootedValueVector names(cx);
182
183 // The default value for each argument is |undefined|.
184 if (!names.growBy(fun->nargs())) {
185 return nullptr;
186 }
187
188 if (IsInterpretedNonSelfHostedFunction(fun) && fun->nargs() > 0) {
189 RootedScript script(cx, GetOrCreateFunctionScript(cx, fun));
190 if (!script) {
191 return nullptr;
192 }
193
194 MOZ_ASSERT(fun->nargs() == script->numArgs());
195
196 PositionalFormalParameterIter fi(script);
197 for (size_t i = 0; i < fun->nargs(); i++, fi++) {
198 MOZ_ASSERT(fi.argumentSlot() == i);
199 if (JSAtom* atom = fi.name()) {
200 // Skip any internal, non-identifier names, like for example ".args".
201 if (IsIdentifier(atom)) {
202 cx->markAtom(atom);
203 names[i].setString(atom);
204 }
205 }
206 }
207 }
208
209 return NewDenseCopiedArray(cx, names.length(), names.begin());
210 }
211
212 bool js::ValueToIdentifier(JSContext* cx, HandleValue v, MutableHandleId id) {
213 if (!ToPropertyKey(cx, v, id)) {
214 return false;
215 }
216 if (!id.isAtom() || !IsIdentifier(id.toAtom())) {
217 RootedValue val(cx, v);
218 ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, val,
219 nullptr, "not an identifier");
220 return false;
221 }
222 return true;
223 }
224
225 class js::AutoRestoreRealmDebugMode {
226 Realm* realm_;
227 unsigned bits_;
228
229 public:
230 explicit AutoRestoreRealmDebugMode(Realm* realm)
231 : realm_(realm), bits_(realm->debugModeBits_) {
232 MOZ_ASSERT(realm_);
233 }
234
235 ~AutoRestoreRealmDebugMode() {
236 if (realm_) {
237 realm_->debugModeBits_ = bits_;
238 }
239 }
240
241 void release() { realm_ = nullptr; }
242 };
243
244 /* static */
245 bool DebugAPI::slowPathCheckNoExecute(JSContext* cx, HandleScript script) {
246 MOZ_ASSERT(cx->realm()->isDebuggee());
247 MOZ_ASSERT(cx->noExecuteDebuggerTop);
248 return EnterDebuggeeNoExecute::reportIfFoundInStack(cx, script);
249 }
250
251 static void PropagateForcedReturn(JSContext* cx, AbstractFramePtr frame,
252 HandleValue rval) {
253 // The Debugger's hooks may return a value that affects the completion
254 // value of the given frame. For example, a hook may return `{ return: 42 }`
255 // to terminate the frame and return `42` as the final frame result.
256 // To accomplish this, the debugger treats these return values as if
257 // execution of the JS function has been terminated without a pending
258 // exception, but with a special flag. When the error is handled by the
259 // interpreter or JIT, the special flag and the error state will be cleared
260 // and execution will continue from the end of the frame.
261 MOZ_ASSERT(!cx->isExceptionPending());
262 cx->setPropagatingForcedReturn();
263 frame.setReturnValue(rval);
264 }
265
266 [[nodiscard]] static bool AdjustGeneratorResumptionValue(JSContext* cx,
267 AbstractFramePtr frame,
268 ResumeMode& resumeMode,
269 MutableHandleValue vp);
270
271 [[nodiscard]] static bool ApplyFrameResumeMode(JSContext* cx,
272 AbstractFramePtr frame,
273 ResumeMode resumeMode,
274 HandleValue rv,
275 Handle<SavedFrame*> exnStack) {
276 RootedValue rval(cx, rv);
277
278 // The value passed in here is unwrapped and has no guarantees about what
279 // compartment it may be associated with, so we explicitly wrap it into the
280 // debuggee compartment.
281 if (!cx->compartment()->wrap(cx, &rval)) {
282 return false;
283 }
284
285 if (!AdjustGeneratorResumptionValue(cx, frame, resumeMode, &rval)) {
286 return false;
287 }
288
289 switch (resumeMode) {
290 case ResumeMode::Continue:
291 break;
292
293 case ResumeMode::Throw:
294 // If we have a stack from the original throw, use it instead of
295 // associating the throw with the current execution point.
296 if (exnStack) {
297 cx->setPendingException(rval, exnStack);
298 } else {
299 cx->setPendingException(rval, ShouldCaptureStack::Always);
300 }
301 return false;
302
303 case ResumeMode::Terminate:
304 cx->reportUncatchableException();
305 return false;
306
307 case ResumeMode::Return:
308 PropagateForcedReturn(cx, frame, rval);
309 return false;
310
311 default:
312 MOZ_CRASH("bad Debugger::onEnterFrame resume mode");
313 }
314
315 return true;
316 }
317 static bool ApplyFrameResumeMode(JSContext* cx, AbstractFramePtr frame,
318 ResumeMode resumeMode, HandleValue rval) {
319 Rooted<SavedFrame*> nullStack(cx);
320 return ApplyFrameResumeMode(cx, frame, resumeMode, rval, nullStack);
321 }
322
323 bool js::ValueToStableChars(JSContext* cx, const char* fnname,
324 HandleValue value,
325 AutoStableStringChars& stableChars) {
326 if (!value.isString()) {
327 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
328 JSMSG_NOT_EXPECTED_TYPE, fnname, "string",
329 InformalValueTypeName(value));
330 return false;
331 }
332 Rooted<JSLinearString*> linear(cx, value.toString()->ensureLinear(cx));
333 if (!linear) {
334 return false;
335 }
336 if (!stableChars.initTwoByte(cx, linear)) {
337 return false;
338 }
339 return true;
340 }
341
342 bool EvalOptions::setFilename(JSContext* cx, const char* filename) {
343 JS::UniqueChars copy;
344 if (filename) {
345 copy = DuplicateString(cx, filename);
346 if (!copy) {
347 return false;
348 }
349 }
350
351 filename_ = std::move(copy);
352 return true;
353 }
354
355 bool js::ParseEvalOptions(JSContext* cx, HandleValue value,
356 EvalOptions& options) {
357 if (!value.isObject()) {
358 return true;
359 }
360
361 RootedObject opts(cx, &value.toObject());
362
363 RootedValue v(cx);
364 if (!JS_GetProperty(cx, opts, "url", &v)) {
365 return false;
366 }
367 if (!v.isUndefined()) {
368 RootedString url_str(cx, ToString<CanGC>(cx, v));
369 if (!url_str) {
370 return false;
371 }
372 UniqueChars url_bytes = JS_EncodeStringToUTF8(cx, url_str);
373 if (!url_bytes) {
374 return false;
375 }
376 if (!options.setFilename(cx, url_bytes.get())) {
377 return false;
378 }
379 }
380
381 if (!JS_GetProperty(cx, opts, "lineNumber", &v)) {
382 return false;
383 }
384 if (!v.isUndefined()) {
385 uint32_t lineno;
386 if (!ToUint32(cx, v, &lineno)) {
387 return false;
388 }
389 options.setLineno(lineno);
390 }
391
392 if (!JS_GetProperty(cx, opts, "hideFromDebugger", &v)) {
393 return false;
394 }
395 options.setHideFromDebugger(ToBoolean(v));
396
397 if (options.kind() == EvalOptions::EnvKind::GlobalWithExtraOuterBindings) {
398 if (!JS_GetProperty(cx, opts, "useInnerBindings", &v)) {
399 return false;
400 }
401 if (ToBoolean(v)) {
402 options.setUseInnerBindings();
403 }
404 }
405
406 return true;
407 }
408
409 /*** Breakpoints ************************************************************/
410
411 bool BreakpointSite::isEmpty() const { return breakpoints.isEmpty(); }
412
413 void BreakpointSite::trace(JSTracer* trc) {
414 for (auto p = breakpoints.begin(); p; p++) {
415 p->trace(trc);
416 }
417 }
418
419 void BreakpointSite::finalize(JS::GCContext* gcx) {
420 while (!breakpoints.isEmpty()) {
421 breakpoints.begin()->delete_(gcx);
422 }
423 }
424
425 Breakpoint* BreakpointSite::firstBreakpoint() const {
426 if (isEmpty()) {
427 return nullptr;
428 }
429 return &(*breakpoints.begin());
430 }
431
432 bool BreakpointSite::hasBreakpoint(Breakpoint* toFind) {
433 const BreakpointList::Iterator bp(toFind);
434 for (auto p = breakpoints.begin(); p; p++) {
435 if (p == bp) {
436 return true;
437 }
438 }
439 return false;
440 }
441
442 Breakpoint::Breakpoint(Debugger* debugger, HandleObject wrappedDebugger,
443 BreakpointSite* site, HandleObject handler)
444 : debugger(debugger),
445 wrappedDebugger(wrappedDebugger),
446 site(site),
447 handler(handler) {
448 MOZ_ASSERT(UncheckedUnwrap(wrappedDebugger) == debugger->object);
449 MOZ_ASSERT(handler->compartment() == wrappedDebugger->compartment());
450
451 debugger->breakpoints.pushBack(this);
452 site->breakpoints.pushBack(this);
453 }
454
455 void Breakpoint::trace(JSTracer* trc) {
456 MOZ_ASSERT_IF(trc->kind() != JS::TracerKind::Moving,
457 !IsDeadProxyObject(wrappedDebugger));
458 TraceEdge(trc, &wrappedDebugger, "breakpoint owner");
459
460 TraceEdge(trc, &handler, "breakpoint handler");
461 }
462
463 void Breakpoint::delete_(JS::GCContext* gcx) {
464 debugger->breakpoints.remove(this);
465 site->breakpoints.remove(this);
466 gc::Cell* cell = site->owningCell();
467 gcx->delete_(cell, this, MemoryUse::Breakpoint);
468 }
469
470 void Breakpoint::remove(JS::GCContext* gcx) {
471 BreakpointSite* savedSite = site;
472 delete_(gcx);
473
474 savedSite->destroyIfEmpty(gcx);
475 }
476
477 Breakpoint* Breakpoint::nextInDebugger() { return debuggerLink.mNext; }
478
479 Breakpoint* Breakpoint::nextInSite() { return siteLink.mNext; }
480
481 JSBreakpointSite::JSBreakpointSite(JSScript* script, jsbytecode* pc)
482 : script(script), pc(pc) {
483 MOZ_ASSERT(!DebugAPI::hasBreakpointsAt(script, pc));
484 }
485
486 void JSBreakpointSite::remove(JS::GCContext* gcx) {
487 DebugScript::destroyBreakpointSite(gcx, script, pc);
488 }
489
490 void JSBreakpointSite::trace(JSTracer* trc) {
491 BreakpointSite::trace(trc);
492 TraceEdge(trc, &script, "breakpoint script");
493 }
494
495 void JSBreakpointSite::delete_(JS::GCContext* gcx) {
496 BreakpointSite::finalize(gcx);
497
498 gcx->delete_(script, this, MemoryUse::BreakpointSite);
499 }
500
501 gc::Cell* JSBreakpointSite::owningCell() { return script; }
502
503 Realm* JSBreakpointSite::realm() const { return script->realm(); }
504
505 WasmBreakpointSite::WasmBreakpointSite(WasmInstanceObject* instanceObject_,
506 uint32_t offset_)
507 : instanceObject(instanceObject_), offset(offset_) {
508 MOZ_ASSERT(instanceObject_);
509 MOZ_ASSERT(instanceObject_->instance().debugEnabled());
510 }
511
512 void WasmBreakpointSite::trace(JSTracer* trc) {
513 BreakpointSite::trace(trc);
514 TraceEdge(trc, &instanceObject, "breakpoint Wasm instance");
515 }
516
517 void WasmBreakpointSite::remove(JS::GCContext* gcx) {
518 instanceObject->instance().destroyBreakpointSite(gcx, offset);
519 }
520
521 void WasmBreakpointSite::delete_(JS::GCContext* gcx) {
522 BreakpointSite::finalize(gcx);
523
524 gcx->delete_(instanceObject, this, MemoryUse::BreakpointSite);
525 }
526
527 gc::Cell* WasmBreakpointSite::owningCell() { return instanceObject; }
528
529 Realm* WasmBreakpointSite::realm() const { return instanceObject->realm(); }
530
531 /*** Debugger hook dispatch *************************************************/
532
533 Debugger::Debugger(JSContext* cx, NativeObject* dbg)
534 : object(dbg),
535 debuggees(cx->zone()),
536 uncaughtExceptionHook(nullptr),
537 allowUnobservedAsmJS(false),
538 allowUnobservedWasm(false),
539 exclusiveDebuggerOnEval(false),
540 inspectNativeCallArguments(false),
541 collectCoverageInfo(false),
542 shouldAvoidSideEffects(false),
543 observedGCs(cx->zone()),
544 allocationsLog(cx),
545 trackingAllocationSites(false),
546 allocationSamplingProbability(1.0),
547 maxAllocationsLogLength(DEFAULT_MAX_LOG_LENGTH),
548 allocationsLogOverflowed(false),
549 frames(cx->zone()),
550 generatorFrames(cx),
551 scripts(cx),
552 sources(cx),
553 objects(cx),
554 environments(cx),
555 wasmInstanceScripts(cx),
556 wasmInstanceSources(cx) {
557 cx->check(dbg);
558
559 cx->runtime()->debuggerList().insertBack(this);
560 }
561
562 template <typename ElementAccess>
563 static void RemoveDebuggerEntry(
564 mozilla::DoublyLinkedList<Debugger, ElementAccess>& list, Debugger* dbg) {
565 // The "probably" here is because there could technically be multiple lists
566 // with this type signature and theoretically the debugger could be an entry
567 // in a different one. That is not actually possible however because there
568 // is only one list the debugger could be in.
569 if (list.ElementProbablyInList(dbg)) {
570 list.remove(dbg);
571 }
572 }
573
574 Debugger::~Debugger() {
575 MOZ_ASSERT(debuggees.empty());
576 allocationsLog.clear();
577
578 // Breakpoints should hold us alive, so any breakpoints remaining must be set
579 // in dying JSScripts. We should clean them up, but this never asserts. I'm
580 // not sure why.
581 MOZ_ASSERT(breakpoints.isEmpty());
582
583 // We don't have to worry about locking here since Debugger is not
584 // background finalized.
585 JSContext* cx = TlsContext.get();
586 RemoveDebuggerEntry(cx->runtime()->onNewGlobalObjectWatchers(), this);
587 RemoveDebuggerEntry(cx->runtime()->onGarbageCollectionWatchers(), this);
588 }
589
590 #ifdef DEBUG
591 /* static */
592 bool Debugger::isChildJSObject(JSObject* obj) {
593 return obj->getClass() == &DebuggerFrame::class_ ||
594 obj->getClass() == &DebuggerScript::class_ ||
595 obj->getClass() == &DebuggerSource::class_ ||
596 obj->getClass() == &DebuggerObject::class_ ||
597 obj->getClass() == &DebuggerEnvironment::class_;
598 }
599 #endif
600
601 bool Debugger::hasMemory() const {
602 return object->getReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE).isObject();
603 }
604
605 DebuggerMemory& Debugger::memory() const {
606 MOZ_ASSERT(hasMemory());
607 return object->getReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE)
608 .toObject()
609 .as<DebuggerMemory>();
610 }
611
612 /*** Debugger accessors *******************************************************/
613
614 bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
615 MutableHandleValue vp) {
616 Rooted<DebuggerFrame*> result(cx);
617 if (!Debugger::getFrame(cx, iter, &result)) {
618 return false;
619 }
620 vp.setObject(*result);
621 return true;
622 }
623
624 bool Debugger::getFrame(JSContext* cx, MutableHandle<DebuggerFrame*> result) {
625 RootedObject proto(
626 cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
627 Rooted<NativeObject*> debugger(cx, object);
628
629 // Since there is no frame/generator data to associate with this frame, this
630 // will create a new, "terminated" Debugger.Frame object.
631 Rooted<DebuggerFrame*> frame(
632 cx, DebuggerFrame::create(cx, proto, debugger, nullptr, nullptr));
633 if (!frame) {
634 return false;
635 }
636
637 result.set(frame);
638 return true;
639 }
640
641 bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
642 MutableHandle<DebuggerFrame*> result) {
643 AbstractFramePtr referent = iter.abstractFramePtr();
644 MOZ_ASSERT_IF(referent.hasScript(), !referent.script()->selfHosted());
645
646 FrameMap::AddPtr p = frames.lookupForAdd(referent);
647 if (!p) {
648 Rooted<AbstractGeneratorObject*> genObj(cx);
649 if (referent.isGeneratorFrame()) {
650 if (referent.isFunctionFrame()) {
651 AutoRealm ar(cx, referent.callee());
652 genObj = GetGeneratorObjectForFrame(cx, referent);
653 } else {
654 MOZ_ASSERT(referent.isModuleFrame());
655 AutoRealm ar(cx, referent.script()->module());
656 genObj = GetGeneratorObjectForFrame(cx, referent);
657 }
658
659 // If this frame has a generator associated with it, but no on-stack
660 // Debugger.Frame object was found, there should not be a suspended
661 // Debugger.Frame either because otherwise slowPathOnResumeFrame would
662 // have already populated the "frames" map with a Debugger.Frame.
663 MOZ_ASSERT_IF(genObj, !generatorFrames.has(genObj));
664
665 // If the frame's generator is closed, there is no way to associate the
666 // generator with the frame successfully because there is no way to
667 // get the generator's callee script, and even if we could, having it
668 // there would in no way affect the behavior of the frame.
669 if (genObj && genObj->isClosed()) {
670 genObj = nullptr;
671 }
672
673 // If no AbstractGeneratorObject exists yet, we create a Debugger.Frame
674 // below anyway, and Debugger::onNewGenerator() will associate it
675 // with the AbstractGeneratorObject later when we hit JSOp::Generator.
676 }
677
678 // Create and populate the Debugger.Frame object.
679 RootedObject proto(
680 cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
681 Rooted<NativeObject*> debugger(cx, object);
682
683 Rooted<DebuggerFrame*> frame(
684 cx, DebuggerFrame::create(cx, proto, debugger, &iter, genObj));
685 if (!frame) {
686 return false;
687 }
688
689 auto terminateDebuggerFrameGuard = MakeScopeExit([&] {
690 terminateDebuggerFrame(cx->gcContext(), this, frame, referent);
691 });
692
693 if (genObj) {
694 DependentAddPtr<GeneratorWeakMap> genPtr(cx, generatorFrames, genObj);
695 if (!genPtr.add(cx, generatorFrames, genObj, frame)) {
696 return false;
697 }
698 }
699
700 if (!ensureExecutionObservabilityOfFrame(cx, referent)) {
701 return false;
702 }
703
704 if (!frames.add(p, referent, frame)) {
705 ReportOutOfMemory(cx);
706 return false;
707 }
708
709 terminateDebuggerFrameGuard.release();
710 }
711
712 result.set(p->value());
713 return true;
714 }
715
716 bool Debugger::getFrame(JSContext* cx, Handle<AbstractGeneratorObject*> genObj,
717 MutableHandle<DebuggerFrame*> result) {
718 // To create a Debugger.Frame for a running generator, we'd also need a
719 // FrameIter for its stack frame. We could make this work by searching the
720 // stack for the generator's frame, but for the moment, we only need this
721 // function to handle generators we've found on promises' reaction records,
722 // which should always be suspended.
723 MOZ_ASSERT(genObj->isSuspended());
724
725 // Do we have an existing Debugger.Frame for this generator?
726 DependentAddPtr<GeneratorWeakMap> p(cx, generatorFrames, genObj);
727 if (p) {
728 MOZ_ASSERT(&p->value()->unwrappedGenerator() == genObj);
729 result.set(p->value());
730 return true;
731 }
732
733 // Create a new Debugger.Frame.
734 RootedObject proto(
735 cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
736 Rooted<NativeObject*> debugger(cx, object);
737
738 result.set(DebuggerFrame::create(cx, proto, debugger, nullptr, genObj));
739 if (!result) {
740 return false;
741 }
742
743 if (!p.add(cx, generatorFrames, genObj, result)) {
744 terminateDebuggerFrame(cx->gcContext(), this, result, NullFramePtr());
745 return false;
746 }
747
748 return true;
749 }
750
751 static bool DebuggerExists(
752 GlobalObject* global, const std::function<bool(Debugger* dbg)>& predicate) {
753 // The GC analysis can't determine that the predicate can't GC, so let it know
754 // explicitly.
755 JS::AutoSuppressGCAnalysis nogc;
756
757 for (Realm::DebuggerVectorEntry& entry : global->getDebuggers(nogc)) {
758 // Callbacks should not create new references to the debugger, so don't
759 // use a barrier. This allows this method to be called during GC.
760 if (predicate(entry.dbg.unbarrieredGet())) {
761 return true;
762 }
763 }
764 return false;
765 }
766
767 /* static */
768 bool Debugger::hasLiveHook(GlobalObject* global, Hook which) {
769 return DebuggerExists(global,
770 [=](Debugger* dbg) { return dbg->getHook(which); });
771 }
772
773 /* static */
774 bool DebugAPI::debuggerObservesAllExecution(GlobalObject* global) {
775 return DebuggerExists(
776 global, [=](Debugger* dbg) { return dbg->observesAllExecution(); });
777 }
778
779 /* static */
780 bool DebugAPI::debuggerObservesCoverage(GlobalObject* global) {
781 return DebuggerExists(global,
782 [=](Debugger* dbg) { return dbg->observesCoverage(); });
783 }
784
785 /* static */
786 bool DebugAPI::debuggerObservesAsmJS(GlobalObject* global) {
787 return DebuggerExists(global,
788 [=](Debugger* dbg) { return dbg->observesAsmJS(); });
789 }
790
791 /* static */
792 bool DebugAPI::debuggerObservesWasm(GlobalObject* global) {
793 return DebuggerExists(global,
794 [=](Debugger* dbg) { return dbg->observesWasm(); });
795 }
796
797 /* static */
798 bool DebugAPI::debuggerObservesNativeCall(GlobalObject* global) {
799 return DebuggerExists(
800 global, [=](Debugger* dbg) { return dbg->observesNativeCalls(); });
801 }
802
803 /* static */
804 bool DebugAPI::hasExceptionUnwindHook(GlobalObject* global) {
805 return Debugger::hasLiveHook(global, Debugger::OnExceptionUnwind);
806 }
807
808 /* static */
809 bool DebugAPI::hasDebuggerStatementHook(GlobalObject* global) {
810 return Debugger::hasLiveHook(global, Debugger::OnDebuggerStatement);
811 }
812
813 template <typename HookIsEnabledFun /* bool (Debugger*) */>
814 bool DebuggerList<HookIsEnabledFun>::init(JSContext* cx) {
815 // Determine which debuggers will receive this event, and in what order.
816 // Make a copy of the list, since the original is mutable and we will be
817 // calling into arbitrary JS.
818 Handle<GlobalObject*> global = cx->global();
819 JS::AutoAssertNoGC nogc;
820 for (Realm::DebuggerVectorEntry& entry : global->getDebuggers(nogc)) {
821 Debugger* dbg = entry.dbg;
822 if (dbg->isHookCallAllowed(cx) && hookIsEnabled(dbg)) {
823 if (!debuggers.append(ObjectValue(*dbg->toJSObject()))) {
824 return false;
825 }
826 }
827 }
828 return true;
829 }
830
831 template <typename HookIsEnabledFun /* bool (Debugger*) */>
832 template <typename FireHookFun /* bool (Debugger*) */>
833 bool DebuggerList<HookIsEnabledFun>::dispatchHook(JSContext* cx,
834 FireHookFun fireHook) {
835 // Preserve the debuggee's microtask event queue while we run the hooks, so
836 // the debugger's microtask checkpoints don't run from the debuggee's
837 // microtasks, and vice versa.
838 JS::AutoDebuggerJobQueueInterruption adjqi;
839 if (!adjqi.init(cx)) {
840 return false;
841 }
842
843 // Deliver the event to each debugger, checking again to make sure it
844 // should still be delivered.
845 Handle<GlobalObject*> global = cx->global();
846 for (Value* p = debuggers.begin(); p != debuggers.end(); p++) {
847 Debugger* dbg = Debugger::fromJSObject(&p->toObject());
848 EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
849 if (dbg->debuggees.has(global) && hookIsEnabled(dbg)) {
850 bool result =
851 dbg->enterDebuggerHook(cx, [&]() -> bool { return fireHook(dbg); });
852 adjqi.runJobs();
853 if (!result) {
854 return false;
855 }
856 }
857 }
858 return true;
859 }
860
861 template <typename HookIsEnabledFun /* bool (Debugger*) */>
862 template <typename FireHookFun /* bool (Debugger*) */>
863 void DebuggerList<HookIsEnabledFun>::dispatchQuietHook(JSContext* cx,
864 FireHookFun fireHook) {
865 bool result =
866 dispatchHook(cx, [&](Debugger* dbg) -> bool { return fireHook(dbg); });
867
868 // dispatchHook may fail due to OOM. This OOM is not handlable at the
869 // callsites of dispatchQuietHook in the engine.
870 if (!result) {
871 cx->clearPendingException();
872 }
873 }
874
875 template <typename HookIsEnabledFun /* bool (Debugger*) */>
876 template <typename FireHookFun /* bool (Debugger*, ResumeMode&, MutableHandleValue vp) */>
877 bool DebuggerList<HookIsEnabledFun>::dispatchResumptionHook(
878 JSContext* cx, AbstractFramePtr frame, FireHookFun fireHook) {
879 ResumeMode resumeMode = ResumeMode::Continue;
880 RootedValue rval(cx);
881 return dispatchHook(cx,
882 [&](Debugger* dbg) -> bool {
883 return fireHook(dbg, resumeMode, &rval);
884 }) &&
885 ApplyFrameResumeMode(cx, frame, resumeMode, rval);
886 }
887
888 JSObject* Debugger::getHook(Hook hook) const {
889 MOZ_ASSERT(hook >= 0 && hook < HookCount);
890 const Value& v = object->getReservedSlot(JSSLOT_DEBUG_HOOK_START +
891 std::underlying_type_t<Hook>(hook));
892 return v.isUndefined() ? nullptr : &v.toObject();
893 }
894
895 bool Debugger::hasAnyLiveHooks() const {
896 // A onNewGlobalObject hook does not hold its Debugger live, so its behavior
897 // is nondeterministic. This behavior is not satisfying, but it is at least
898 // documented.
899 if (getHook(OnDebuggerStatement) || getHook(OnExceptionUnwind) ||
900 getHook(OnNewScript) || getHook(OnEnterFrame)) {
901 return true;
902 }
903
904 return false;
905 }
906
907 /* static */
908 bool DebugAPI::slowPathOnEnterFrame(JSContext* cx, AbstractFramePtr frame) {
909 #ifdef MOZ_EXECUTION_TRACING
910 if (cx->hasExecutionTracer()) {
911 cx->getExecutionTracer().onEnterFrame(cx, frame);
912 }
913 #endif
914 return Debugger::dispatchResumptionHook(
915 cx, frame,
916 [frame](Debugger* dbg) -> bool {
917 return dbg->observesFrame(frame) && dbg->observesEnterFrame();
918 },
919 [&](Debugger* dbg, ResumeMode& resumeMode, MutableHandleValue vp)
920 -> bool { return dbg->fireEnterFrame(cx, resumeMode, vp); });
921 }
922
923 /* static */
924 bool DebugAPI::slowPathOnResumeFrame(JSContext* cx, AbstractFramePtr frame) {
925 #ifdef MOZ_EXECUTION_TRACING
926 if (cx->hasExecutionTracer()) {
927 cx->getExecutionTracer().onEnterFrame(cx, frame);
928 }
929 #endif
930 // Don't count on this method to be called every time a generator is
931 // resumed! This is called only if the frame's debuggee bit is set,
932 // i.e. the script has breakpoints or the frame is stepping.
933 MOZ_ASSERT(frame.isGeneratorFrame());
934 MOZ_ASSERT(frame.isDebuggee());
935
936 Rooted<AbstractGeneratorObject*> genObj(
937 cx, GetGeneratorObjectForFrame(cx, frame));
938 MOZ_ASSERT(genObj);
939
940 // If there is an OOM, we mark all of the Debugger.Frame objects terminated
941 // because we want to ensure that none of the frames are in a partially
942 // initialized state where they are in "generatorFrames" but not "frames".
943 auto terminateDebuggerFramesGuard = MakeScopeExit([&] {
944 Debugger::terminateDebuggerFrames(cx, frame);
945
946 MOZ_ASSERT(!DebugAPI::inFrameMaps(frame));
947 });
948
949 // For each debugger, if there is an existing Debugger.Frame object for the
950 // resumed `frame`, update it with the new frame pointer and make sure the
951 // frame is observable.
952 FrameIter iter(cx);
953 MOZ_ASSERT(iter.abstractFramePtr() == frame);
954 {
955 JS::AutoAssertNoGC nogc;
956 for (Realm::DebuggerVectorEntry& entry :
957 frame.global()->getDebuggers(nogc)) {
958 Debugger* dbg = entry.dbg;
959 if (Debugger::GeneratorWeakMap::Ptr generatorEntry =
960 dbg->generatorFrames.lookup(genObj)) {
961 DebuggerFrame* frameObj = generatorEntry->value();
962 MOZ_ASSERT(&frameObj->unwrappedGenerator() == genObj);
963 if (!dbg->frames.putNew(frame, frameObj)) {
964 ReportOutOfMemory(cx);
965 return false;
966 }
967 if (!frameObj->resume(iter)) {
968 return false;
969 }
970 }
971 }
972 }
973
974 terminateDebuggerFramesGuard.release();
975
976 return slowPathOnEnterFrame(cx, frame);
977 }
978
979 /* static */
980 NativeResumeMode DebugAPI::slowPathOnNativeCall(JSContext* cx,
981 const CallArgs& args,
982 CallReason reason) {
983 if (!cx->realm()->debuggerObservesNativeCall()) {
984 return NativeResumeMode::Continue;
985 }
986
987 DebuggerList debuggerList(cx, [](Debugger* dbg) -> bool {
988 return dbg->getHook(Debugger::OnNativeCall);
989 });
990
991 if (!debuggerList.init(cx)) {
992 return NativeResumeMode::Abort;
993 }
994
995 if (debuggerList.empty()) {
996 return NativeResumeMode::Continue;
997 }
998
999 // The onNativeCall hook is fired when self hosted functions are called,
1000 // and any other self hosted function or C++ native that is directly called
1001 // by the self hosted function is considered to be part of the same
1002 // native call, except for the following 4 cases:
1003 //
1004 // * callContentFunction and constructContentFunction,
1005 // which uses CallReason::CallContent
1006 // * Function.prototype.call and Function.prototype.apply,
1007 // which uses CallReason::FunCall
1008 // * Getter call which uses CallReason::Getter
1009 // * Setter call which uses CallReason::Setter
1010 //
1011 // We check this only after checking that debuggerList has items in order
1012 // to avoid unnecessary calls to cx->currentScript(), which can be expensive
1013 // when the top frame is in jitcode.
1014 JSScript* script = cx->currentScript();
1015 if (script && script->selfHosted() && reason != CallReason::CallContent &&
1016 reason != CallReason::FunCall && reason != CallReason::Getter &&
1017 reason != CallReason::Setter) {
1018 return NativeResumeMode::Continue;
1019 }
1020
1021 RootedValue rval(cx);
1022 ResumeMode resumeMode = ResumeMode::Continue;
1023 bool result = debuggerList.dispatchHook(cx, [&](Debugger* dbg) -> bool {
1024 return dbg->fireNativeCall(cx, args, reason, resumeMode, &rval);
1025 });
1026 if (!result) {
1027 return NativeResumeMode::Abort;
1028 }
1029
1030 // Hook must follow normal native function conventions and not return
1031 // primitive values.
1032 if (resumeMode == ResumeMode::Return) {
1033 if (args.isConstructing() && !rval.isObject()) {
1034 JS_ReportErrorASCII(
1035 cx, "onNativeCall hook must return an object for constructor call");
1036 return NativeResumeMode::Abort;
1037 }
1038 }
1039
1040 // The value is not in any particular compartment, so it needs to be
1041 // explicitly wrapped into the debuggee compartment.
1042 if (!cx->compartment()->wrap(cx, &rval)) {
1043 return NativeResumeMode::Abort;
1044 }
1045
1046 switch (resumeMode) {
1047 case ResumeMode::Continue:
1048 break;
1049
1050 case ResumeMode::Throw:
1051 cx->setPendingException(rval, ShouldCaptureStack::Always);
1052 return NativeResumeMode::Abort;
1053
1054 case ResumeMode::Terminate:
1055 cx->reportUncatchableException();
1056 return NativeResumeMode::Abort;
1057
1058 case ResumeMode::Return:
1059 args.rval().set(rval);
1060 return NativeResumeMode::Override;
1061 }
1062
1063 return NativeResumeMode::Continue;
1064 }
1065
1066 /* static */
1067 bool DebugAPI::slowPathShouldAvoidSideEffects(JSContext* cx) {
1068 return DebuggerExists(
1069 cx->global(), [=](Debugger* dbg) { return dbg->shouldAvoidSideEffects; });
1070 }
1071
1072 /*
1073 * RAII class to mark a generator as "running" temporarily while running
1074 * debugger code.
1075 *
1076 * When Debugger::slowPathOnLeaveFrame is called for a frame that is yielding
1077 * or awaiting, its generator is in the "suspended" state. Letting script
1078 * observe this state, with the generator on stack yet also reenterable, would
1079 * be bad, so we mark it running while we fire events.
1080 */
1081 class MOZ_RAII AutoSetGeneratorRunning {
1082 int32_t resumeIndex_;
1083 AsyncGeneratorObject::State asyncGenState_;
1084 Rooted<AbstractGeneratorObject*> genObj_;
1085
1086 public:
1087 AutoSetGeneratorRunning(JSContext* cx,
1088 Handle<AbstractGeneratorObject*> genObj)
1089 : resumeIndex_(0),
1090 asyncGenState_(static_cast<AsyncGeneratorObject::State>(0)),
1091 genObj_(cx, genObj) {
1092 if (genObj) {
1093 if (!genObj->isClosed() && !genObj->isBeforeInitialYield() &&
1094 genObj->isSuspended()) {
1095 // Yielding or awaiting.
1096 resumeIndex_ = genObj->resumeIndex();
1097 genObj->setRunning();
1098
1099 // Async generators have additionally bookkeeping which must be
1100 // adjusted when switching over to the running state.
1101 if (genObj->is<AsyncGeneratorObject>()) {
1102 auto* generator = &genObj->as<AsyncGeneratorObject>();
1103 asyncGenState_ = generator->state();
1104 generator->setExecuting();
1105 }
1106 } else {
1107 // Returning or throwing. The generator is already closed, if
1108 // it was ever exposed at all.
1109 genObj_ = nullptr;
1110 }
1111 }
1112 }
1113
1114 ~AutoSetGeneratorRunning() {
1115 if (genObj_) {
1116 MOZ_ASSERT(genObj_->isRunning());
1117 genObj_->setResumeIndex(resumeIndex_);
1118 if (genObj_->is<AsyncGeneratorObject>()) {
1119 genObj_->as<AsyncGeneratorObject>().setState(asyncGenState_);
1120 }
1121 }
1122 }
1123 };
1124
1125 /*
1126 * Handle leaving a frame with debuggers watching. |frameOk| indicates whether
1127 * the frame is exiting normally or abruptly. Set |cx|'s exception and/or
1128 * |cx->fp()|'s return value, and return a new success value.
1129 */
1130 /* static */
1131 bool DebugAPI::slowPathOnLeaveFrame(JSContext* cx, AbstractFramePtr frame,
1132 const jsbytecode* pc, bool frameOk) {
1133 #ifdef MOZ_EXECUTION_TRACING
1134 if (cx->hasExecutionTracer()) {
1135 cx->getExecutionTracer().onLeaveFrame(cx, frame);
1136 }
1137 #endif
1138 MOZ_ASSERT_IF(!frame.isWasmDebugFrame(), pc);
1139
1140 mozilla::DebugOnly<Handle<GlobalObject*>> debuggeeGlobal = cx->global();
1141
1142 // These are updated below, but consulted by the cleanup code we register now,
1143 // so declare them here, initialized to quiescent values.
1144 Rooted<Completion> completion(cx);
1145 bool success = false;
1146
1147 auto frameMapsGuard = MakeScopeExit([&] {
1148 // Clean up all Debugger.Frame instances on exit. On suspending, pass the
1149 // flag that says to leave those frames `.live`. Note that if the completion
1150 // is a suspension but success is false, the generator gets closed, not
1151 // suspended.
1152 if (success && completion.get().suspending()) {
1153 Debugger::suspendGeneratorDebuggerFrames(cx, frame);
1154 } else {
1155 if (frame.isWasmDebugFrame()) {
1156 DebugEnvironments::onPopWasm(cx, frame);
1157 }
1158 Debugger::terminateDebuggerFrames(cx, frame);
1159 }
1160 });
1161
1162 // The onPop handler and associated clean up logic should not run multiple
1163 // times on the same frame. If slowPathOnLeaveFrame has already been
1164 // called, the frame will not be present in the Debugger frame maps.
1165 Rooted<Debugger::DebuggerFrameVector> frames(cx);
1166 if (!Debugger::getDebuggerFrames(frame, &frames)) {
1167 // There is at least one match Debugger.Frame we failed to process, so drop
1168 // the pending exception and raise an out-of-memory instead.
1169 if (!frameOk) {
1170 cx->clearPendingException();
1171 }
1172 ReportOutOfMemory(cx);
1173 return false;
1174 }
1175 if (frames.empty()) {
1176 return frameOk;
1177 }
1178
1179 // Convert current exception state into a Completion and clear exception off
1180 // of the JSContext.
1181 completion = Completion::fromJSFramePop(cx, frame, pc, frameOk);
1182
1183 ResumeMode resumeMode = ResumeMode::Continue;
1184 RootedValue rval(cx);
1185
1186 {
1187 // Preserve the debuggee's microtask event queue while we run the hooks, so
1188 // the debugger's microtask checkpoints don't run from the debuggee's
1189 // microtasks, and vice versa.
1190 JS::AutoDebuggerJobQueueInterruption adjqi;
1191 if (!adjqi.init(cx)) {
1192 return false;
1193 }
1194
1195 // This path can be hit via unwinding the stack due to over-recursion or
1196 // OOM. In those cases, don't fire the frames' onPop handlers, because
1197 // invoking JS will only trigger the same condition. See
1198 // slowPathOnExceptionUnwind.
1199 if (!cx->isThrowingOverRecursed() && !cx->isThrowingOutOfMemory()) {
1200 Rooted<AbstractGeneratorObject*> genObj(
1201 cx, frame.isGeneratorFrame() ? GetGeneratorObjectForFrame(cx, frame)
1202 : nullptr);
1203
1204 // For each Debugger.Frame, fire its onPop handler, if any.
1205 for (size_t i = 0; i < frames.length(); i++) {
1206 Handle<DebuggerFrame*> frameobj = frames[i];
1207 Debugger* dbg = frameobj->owner();
1208 EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
1209
1210 // Removing a global from a Debugger's debuggee set kills all of that
1211 // Debugger's D.Fs in that global. This means that one D.F's onPop can
1212 // kill the next D.F. So we have to check whether frameobj is still "on
1213 // the stack".
1214 if (frameobj->isOnStack() && frameobj->onPopHandler()) {
1215 OnPopHandler* handler = frameobj->onPopHandler();
1216
1217 bool result = dbg->enterDebuggerHook(cx, [&]() -> bool {
1218 ResumeMode nextResumeMode = ResumeMode::Continue;
1219 RootedValue nextValue(cx);
1220
1221 // Call the onPop handler.
1222 bool success;
1223 {
1224 // Mark the generator as running, to prevent reentrance.
1225 //
1226 // At certain points in a generator's lifetime,
1227 // GetGeneratorObjectForFrame can return null even when the
1228 // generator exists, but at those points the generator has not yet
1229 // been exposed to JavaScript, so reentrance isn't possible
1230 // anyway. So there's no harm done if this has no effect in that
1231 // case.
1232 AutoSetGeneratorRunning asgr(cx, genObj);
1233 success = handler->onPop(cx, frameobj, completion, nextResumeMode,
1234 &nextValue);
1235 }
1236
1237 return dbg->processParsedHandlerResult(cx, frame, pc, success,
1238 nextResumeMode, nextValue,
1239 resumeMode, &rval);
1240 });
1241 adjqi.runJobs();
1242
1243 if (!result) {
1244 return false;
1245 }
1246
1247 // At this point, we are back in the debuggee compartment, and
1248 // any error has been wrapped up as a completion value.
1249 MOZ_ASSERT(!cx->isExceptionPending());
1250 }
1251 }
1252 }
1253 }
1254
1255 completion.get().updateFromHookResult(resumeMode, rval);
1256
1257 // Now that we've run all the handlers, extract the final resumption mode. */
1258 ResumeMode completionResumeMode;
1259 RootedValue completionValue(cx);
1260 Rooted<SavedFrame*> completionStack(cx);
1261 completion.get().toResumeMode(completionResumeMode, &completionValue,
1262 &completionStack);
1263
1264 // If we are returning the original value used to create the completion, then
1265 // we don't want to treat the resumption value as a Return completion, because
1266 // that would cause us to apply AdjustGeneratorResumptionValue to the
1267 // already-adjusted value that the generator actually returned.
1268 if (resumeMode == ResumeMode::Continue &&
1269 completionResumeMode == ResumeMode::Return) {
1270 completionResumeMode = ResumeMode::Continue;
1271 }
1272
1273 if (!ApplyFrameResumeMode(cx, frame, completionResumeMode, completionValue,
1274 completionStack)) {
1275 if (!cx->isPropagatingForcedReturn()) {
1276 // If this is an exception or termination, we just propagate that along.
1277 return false;
1278 }
1279
1280 // Since we are leaving the frame here, we can convert a forced return
1281 // into a normal return right away.
1282 cx->clearPropagatingForcedReturn();
1283 }
1284 success = true;
1285 return true;
1286 }
1287
1288 /* static */
1289 bool DebugAPI::slowPathOnNewGenerator(JSContext* cx, AbstractFramePtr frame,
1290 Handle<AbstractGeneratorObject*> genObj) {
1291 // This is called from JSOp::Generator, after default parameter expressions
1292 // are evaluated and well after onEnterFrame, so Debugger.Frame objects for
1293 // `frame` may already have been exposed to debugger code. The
1294 // AbstractGeneratorObject for this generator call, though, has just been
1295 // created. It must be associated with any existing Debugger.Frames.
1296
1297 // Initializing frames with their associated generator is critical to the
1298 // functionality of the debugger, so if there is an OOM, we want to
1299 // cleanly terminate all of the frames.
1300 auto terminateDebuggerFramesGuard =
1301 MakeScopeExit([&] { Debugger::terminateDebuggerFrames(cx, frame); });
1302
1303 bool ok = true;
1304 gc::AutoSuppressGC nogc(cx);
1305 Debugger::forEachOnStackDebuggerFrame(
1306 frame, nogc, [&](Debugger* dbg, DebuggerFrame* frameObjPtr) {
1307 if (!ok) {
1308 return;
1309 }
1310
1311 Rooted<DebuggerFrame*> frameObj(cx, frameObjPtr);
1312
1313 AutoRealm ar(cx, frameObj);
1314
1315 if (!DebuggerFrame::setGeneratorInfo(cx, frameObj, genObj)) {
1316 // This leaves `genObj` and `frameObj` unassociated. It's OK
1317 // because we won't pause again with this generator on the stack:
1318 // the caller will immediately discard `genObj` and unwind `frame`.
1319 ok = false;
1320 return;
1321 }
1322
1323 DependentAddPtr<Debugger::GeneratorWeakMap> genPtr(
1324 cx, dbg->generatorFrames, genObj);
1325 if (!genPtr.add(cx, dbg->generatorFrames, genObj, frameObj)) {
1326 ok = false;
1327 }
1328 });
1329
1330 if (!ok) {
1331 return false;
1332 }
1333
1334 terminateDebuggerFramesGuard.release();
1335 return true;
1336 }
1337
1338 /* static */
1339 bool DebugAPI::slowPathOnDebuggerStatement(JSContext* cx,
1340 AbstractFramePtr frame) {
1341 return Debugger::dispatchResumptionHook(
1342 cx, frame,
1343 [](Debugger* dbg) -> bool {
1344 return dbg->getHook(Debugger::OnDebuggerStatement);
1345 },
1346 [&](Debugger* dbg, ResumeMode& resumeMode, MutableHandleValue vp)
1347 -> bool { return dbg->fireDebuggerStatement(cx, resumeMode, vp); });
1348 }
1349
1350 /* static */
1351 bool DebugAPI::slowPathOnExceptionUnwind(JSContext* cx,
1352 AbstractFramePtr frame) {
1353 // Invoking more JS on an over-recursed stack or after OOM is only going
1354 // to result in more of the same error.
1355 if (cx->isThrowingOverRecursed() || cx->isThrowingOutOfMemory()) {
1356 return true;
1357 }
1358
1359 // The Debugger API mustn't muck with frames from self-hosted scripts.
1360 if (frame.hasScript() && frame.script()->selfHosted()) {
1361 return true;
1362 }
1363
1364 DebuggerList debuggerList(cx, [](Debugger* dbg) -> bool {
1365 return dbg->getHook(Debugger::OnExceptionUnwind);
1366 });
1367
1368 if (!debuggerList.init(cx)) {
1369 return false;
1370 }
1371
1372 if (debuggerList.empty()) {
1373 return true;
1374 }
1375
1376 // We save and restore the exception once up front to avoid having to do it
1377 // for each 'onExceptionUnwind' hook that has been registered, and we also
1378 // only do it if the debuggerList contains items in order to avoid extra work.
1379 RootedValue exc(cx);
1380 Rooted<SavedFrame*> stack(cx, cx->getPendingExceptionStack());
1381 if (!cx->getPendingException(&exc)) {
1382 return false;
1383 }
1384 cx->clearPendingException();
1385
1386 bool result = debuggerList.dispatchResumptionHook(
1387 cx, frame,
1388 [&](Debugger* dbg, ResumeMode& resumeMode,
1389 MutableHandleValue vp) -> bool {
1390 return dbg->fireExceptionUnwind(cx, exc, resumeMode, vp);
1391 });
1392 if (!result) {
1393 return false;
1394 }
1395
1396 cx->setPendingException(exc, stack);
1397 return true;
1398 }
1399
1400 // TODO: Remove Remove this function when all properties/methods returning a
1401 /// DebuggerEnvironment have been given a C++ interface (bug 1271649).
1402 bool Debugger::wrapEnvironment(JSContext* cx, Handle<Env*> env,
1403 MutableHandleValue rval) {
1404 if (!env) {
1405 rval.setNull();
1406 return true;
1407 }
1408
1409 Rooted<DebuggerEnvironment*> envobj(cx);
1410
1411 if (!wrapEnvironment(cx, env, &envobj)) {
1412 return false;
1413 }
1414
1415 rval.setObject(*envobj);
1416 return true;
1417 }
1418
1419 bool Debugger::wrapEnvironment(JSContext* cx, Handle<Env*> env,
1420 MutableHandle<DebuggerEnvironment*> result) {
1421 MOZ_ASSERT(env);
1422
1423 // DebuggerEnv should only wrap a debug scope chain obtained (transitively)
1424 // from GetDebugEnvironmentFor(Frame|Function).
1425 MOZ_ASSERT(!IsSyntacticEnvironment(env));
1426
1427 DependentAddPtr<EnvironmentWeakMap> p(cx, environments, env);
1428 if (p) {
1429 result.set(&p->value()->as<DebuggerEnvironment>());
1430 } else {
1431 // Create a new Debugger.Environment for env.
1432 RootedObject proto(
1433 cx, &object->getReservedSlot(JSSLOT_DEBUG_ENV_PROTO).toObject());
1434 Rooted<NativeObject*> debugger(cx, object);
1435
1436 Rooted<DebuggerEnvironment*> envobj(
1437 cx, DebuggerEnvironment::create(cx, proto, env, debugger));
1438 if (!envobj) {
1439 return false;
1440 }
1441
1442 if (!p.add(cx, environments, env, envobj)) {
1443 // We need to destroy the edge to the referent, to avoid trying to trace
1444 // it during untimely collections.
1445 envobj->clearReferent();
1446 return false;
1447 }
1448
1449 result.set(envobj);
1450 }
1451
1452 return true;
1453 }
1454
1455 bool Debugger::wrapDebuggeeValue(JSContext* cx, MutableHandleValue vp) {
1456 cx->check(object.get());
1457
1458 if (vp.isObject()) {
1459 RootedObject obj(cx, &vp.toObject());
1460 Rooted<DebuggerObject*> dobj(cx);
1461
1462 if (!wrapDebuggeeObject(cx, obj, &dobj)) {
1463 return false;
1464 }
1465
1466 vp.setObject(*dobj);
1467 } else if (vp.isMagic()) {
1468 Rooted<PlainObject*> optObj(cx, NewPlainObject(cx));
1469 if (!optObj) {
1470 return false;
1471 }
1472
1473 // We handle three sentinel values: missing arguments
1474 // (JS_MISSING_ARGUMENTS), optimized out slots (JS_OPTIMIZED_OUT),
1475 // and uninitialized bindings (JS_UNINITIALIZED_LEXICAL).
1476 //
1477 // Other magic values should not have escaped.
1478 PropertyName* name;
1479 switch (vp.whyMagic()) {
1480 case JS_MISSING_ARGUMENTS:
1481 name = cx->names().missingArguments;
1482 break;
1483 case JS_OPTIMIZED_OUT:
1484 name = cx->names().optimizedOut;
1485 break;
1486 case JS_UNINITIALIZED_LEXICAL:
1487 name = cx->names().uninitialized;
1488 break;
1489 default:
1490 MOZ_CRASH("Unsupported magic value escaped to Debugger");
1491 }
1492
1493 RootedValue trueVal(cx, BooleanValue(true));
1494 if (!DefineDataProperty(cx, optObj, name, trueVal)) {
1495 return false;
1496 }
1497
1498 vp.setObject(*optObj);
1499 } else if (!cx->compartment()->wrap(cx, vp)) {
1500 vp.setUndefined();
1501 return false;
1502 }
1503
1504 return true;
1505 }
1506
1507 bool Debugger::wrapNullableDebuggeeObject(
1508 JSContext* cx, HandleObject obj, MutableHandle<DebuggerObject*> result) {
1509 if (!obj) {
1510 result.set(nullptr);
1511 return true;
1512 }
1513
1514 return wrapDebuggeeObject(cx, obj, result);
1515 }
1516
1517 bool Debugger::wrapDebuggeeObject(JSContext* cx, HandleObject obj,
1518 MutableHandle<DebuggerObject*> result) {
1519 MOZ_ASSERT(obj);
1520
1521 DependentAddPtr<ObjectWeakMap> p(cx, objects, obj);
1522 if (p) {
1523 result.set(&p->value()->as<DebuggerObject>());
1524 } else {
1525 // Create a new Debugger.Object for obj.
1526 Rooted<NativeObject*> debugger(cx, object);
1527 RootedObject proto(
1528 cx, &object->getReservedSlot(JSSLOT_DEBUG_OBJECT_PROTO).toObject());
1529 Rooted<DebuggerObject*> dobj(
1530 cx, DebuggerObject::create(cx, proto, obj, debugger));
1531 if (!dobj) {
1532 return false;
1533 }
1534
1535 if (!p.add(cx, objects, obj, dobj)) {
1536 // We need to destroy the edge to the referent, to avoid trying to trace
1537 // it during untimely collections.
1538 dobj->clearReferent();
1539 return false;
1540 }
1541
1542 result.set(dobj);
1543 }
1544
1545 return true;
1546 }
1547
1548 static DebuggerObject* ToNativeDebuggerObject(JSContext* cx,
1549 MutableHandleObject obj) {
1550 if (!obj->is<DebuggerObject>()) {
1551 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1552 JSMSG_NOT_EXPECTED_TYPE, "Debugger",
1553 "Debugger.Object", obj->getClass()->name);
1554 return nullptr;
1555 }
1556
1557 return &obj->as<DebuggerObject>();
1558 }
1559
1560 bool Debugger::unwrapDebuggeeObject(JSContext* cx, MutableHandleObject obj) {
1561 DebuggerObject* ndobj = ToNativeDebuggerObject(cx, obj);
1562 if (!ndobj) {
1563 return false;
1564 }
1565
1566 if (ndobj->owner() != Debugger::fromJSObject(object)) {
1567 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1568 JSMSG_DEBUG_WRONG_OWNER, "Debugger.Object");
1569 return false;
1570 }
1571
1572 obj.set(ndobj->referent());
1573 return true;
1574 }
1575
1576 bool Debugger::unwrapDebuggeeValue(JSContext* cx, MutableHandleValue vp) {
1577 cx->check(object.get(), vp);
1578 if (vp.isObject()) {
1579 RootedObject dobj(cx, &vp.toObject());
1580 if (!unwrapDebuggeeObject(cx, &dobj)) {
1581 return false;
1582 }
1583 vp.setObject(*dobj);
1584 }
1585 return true;
1586 }
1587
1588 static bool CheckArgCompartment(JSContext* cx, JSObject* obj, JSObject* arg,
1589 const char* methodname, const char* propname) {
1590 if (arg->compartment() != obj->compartment()) {
1591 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1592 JSMSG_DEBUG_COMPARTMENT_MISMATCH, methodname,
1593 propname);
1594 return false;
1595 }
1596 return true;
1597 }
1598
1599 static bool CheckArgCompartment(JSContext* cx, JSObject* obj, HandleValue v,
1600 const char* methodname, const char* propname) {
1601 if (v.isObject()) {
1602 return CheckArgCompartment(cx, obj, &v.toObject(), methodname, propname);
1603 }
1604 return true;
1605 }
1606
1607 bool Debugger::unwrapPropertyDescriptor(
1608 JSContext* cx, HandleObject obj, MutableHandle<PropertyDescriptor> desc) {
1609 if (desc.hasValue()) {
1610 RootedValue value(cx, desc.value());
1611 if (!unwrapDebuggeeValue(cx, &value) ||
1612 !CheckArgCompartment(cx, obj, value, "defineProperty", "value")) {
1613 return false;
1614 }
1615 desc.setValue(value);
1616 }
1617
1618 if (desc.hasGetter()) {
1619 RootedObject get(cx, desc.getter());
1620 if (get) {
1621 if (!unwrapDebuggeeObject(cx, &get)) {
1622 return false;
1623 }
1624 if (!CheckArgCompartment(cx, obj, get, "defineProperty", "get")) {
1625 return false;
1626 }
1627 }
1628 desc.setGetter(get);
1629 }
1630
1631 if (desc.hasSetter()) {
1632 RootedObject set(cx, desc.setter());
1633 if (set) {
1634 if (!unwrapDebuggeeObject(cx, &set)) {
1635 return false;
1636 }
1637 if (!CheckArgCompartment(cx, obj, set, "defineProperty", "set")) {
1638 return false;
1639 }
1640 }
1641 desc.setSetter(set);
1642 }
1643
1644 return true;
1645 }
1646
1647 /*** Debuggee resumption values and debugger error handling *****************/
1648
1649 static bool GetResumptionProperty(JSContext* cx, HandleObject obj,
1650 Handle<PropertyName*> name,
1651 ResumeMode namedMode, ResumeMode& resumeMode,
1652 MutableHandleValue vp, int* hits) {
1653 bool found;
1654 if (!HasProperty(cx, obj, name, &found)) {
1655 return false;
1656 }
1657 if (found) {
1658 ++*hits;
1659 resumeMode = namedMode;
1660 if (!GetProperty(cx, obj, obj, name, vp)) {
1661 return false;
1662 }
1663 }
1664 return true;
1665 }
1666
1667 bool js::ParseResumptionValue(JSContext* cx, HandleValue rval,
1668 ResumeMode& resumeMode, MutableHandleValue vp) {
1669 if (rval.isUndefined()) {
1670 resumeMode = ResumeMode::Continue;
1671 vp.setUndefined();
1672 return true;
1673 }
1674 if (rval.isNull()) {
1675 resumeMode = ResumeMode::Terminate;
1676 vp.setUndefined();
1677 return true;
1678 }
1679
1680 int hits = 0;
1681 if (rval.isObject()) {
1682 RootedObject obj(cx, &rval.toObject());
1683 if (!GetResumptionProperty(cx, obj, cx->names().return_, ResumeMode::Return,
1684 resumeMode, vp, &hits)) {
1685 return false;
1686 }
1687 if (!GetResumptionProperty(cx, obj, cx->names().throw_, ResumeMode::Throw,
1688 resumeMode, vp, &hits)) {
1689 return false;
1690 }
1691 }
1692
1693 if (hits != 1) {
1694 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1695 JSMSG_DEBUG_BAD_RESUMPTION);
1696 return false;
1697 }
1698 return true;
1699 }
1700
1701 static bool CheckResumptionValue(JSContext* cx, AbstractFramePtr frame,
1702 const jsbytecode* pc, ResumeMode resumeMode,
1703 MutableHandleValue vp) {
1704 // Only forced returns from a frame need to be validated because forced
1705 // throw values behave just like debuggee `throw` statements. Since
1706 // forced-return is all custom logic within SpiderMonkey itself, we need
1707 // our own custom validation for it to conform with what is expected.
1708 if (resumeMode != ResumeMode::Return || !frame) {
1709 return true;
1710 }
1711
1712 // This replicates the ECMA spec's behavior for [[Construct]] in derived
1713 // class constructors (section 9.2.2 of ECMA262-2020), where returning a
1714 // non-undefined primitive causes an exception tobe thrown.
1715 if (frame.debuggerNeedsCheckPrimitiveReturn() && vp.isPrimitive()) {
1716 if (!vp.isUndefined()) {
1717 ReportValueError(cx, JSMSG_BAD_DERIVED_RETURN, JSDVG_IGNORE_STACK, vp,
1718 nullptr);
1719 return false;
1720 }
1721
1722 RootedValue thisv(cx);
1723 {
1724 AutoRealm ar(cx, frame.environmentChain());
1725 if (!GetThisValueForDebuggerFrameMaybeOptimizedOut(cx, frame, pc,
1726 &thisv)) {
1727 return false;
1728 }
1729 }
1730
1731 if (thisv.isMagic(JS_UNINITIALIZED_LEXICAL)) {
1732 return ThrowUninitializedThis(cx);
1733 }
1734 MOZ_ASSERT(!thisv.isMagic());
1735
1736 if (!cx->compartment()->wrap(cx, &thisv)) {
1737 return false;
1738 }
1739 vp.set(thisv);
1740 }
1741
1742 // Check for forcing return from a generator before the initial yield. This
1743 // is not supported because some engine-internal code assumes a call to a
1744 // generator will return a GeneratorObject; see bug 1477084.
1745 if (frame.isFunctionFrame() && frame.callee()->isGenerator()) {
1746 Rooted<AbstractGeneratorObject*> genObj(cx);
1747 {
1748 AutoRealm ar(cx, frame.callee());
1749 genObj = GetGeneratorObjectForFrame(cx, frame);
1750 }
1751
1752 if (!genObj || genObj->isBeforeInitialYield()) {
1753 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1754 JSMSG_DEBUG_FORCED_RETURN_DISALLOWED);
1755 return false;
1756 }
1757 }
1758
1759 return true;
1760 }
1761
1762 // Last-minute sanity adjustments to resumption.
1763 //
1764 // This is called last, as we leave the debugger. It must happen outside the
1765 // control of the uncaughtExceptionHook, because this code assumes we won't
1766 // change our minds and continue execution--we must not close the generator
1767 // object unless we're really going to force-return.
1768 [[nodiscard]] static bool AdjustGeneratorResumptionValue(
1769 JSContext* cx, AbstractFramePtr frame, ResumeMode& resumeMode,
1770 MutableHandleValue vp) {
1771 if (resumeMode != ResumeMode::Return && resumeMode != ResumeMode::Throw) {
1772 return true;
1773 }
1774
1775 if (!frame) {
1776 return true;
1777 }
1778 // Async modules need to be handled separately, as they do not have a callee.
1779 // frame.callee will throw if it is called on a moduleFrame.
1780 bool isAsyncModule = frame.isModuleFrame() && frame.script()->isAsync();
1781 if (!frame.isFunctionFrame() && !isAsyncModule) {
1782 return true;
1783 }
1784
1785 // Treat `{return: <value>}` like a `return` statement. Simulate what the
1786 // debuggee would do for an ordinary `return` statement, using a few bytecode
1787 // instructions. It's simpler to do the work manually than to count on that
1788 // bytecode sequence existing in the debuggee, somehow jump to it, and then
1789 // avoid re-entering the debugger from it.
1790 //
1791 // Similarly treat `{throw: <value>}` like a `throw` statement.
1792 //
1793 // Note: Async modules use the same handling as async functions.
1794 if (frame.isFunctionFrame() && frame.callee()->isGenerator()) {
1795 // Throw doesn't require any special processing for (async) generators.
1796 if (resumeMode == ResumeMode::Throw) {
1797 return true;
1798 }
1799
1800 // Forcing return from a (possibly async) generator.
1801 Rooted<AbstractGeneratorObject*> genObj(
1802 cx, GetGeneratorObjectForFrame(cx, frame));
1803
1804 // We already went through CheckResumptionValue, which would have replaced
1805 // this invalid resumption value with an error if we were trying to force
1806 // return before the initial yield.
1807 MOZ_RELEASE_ASSERT(genObj && !genObj->isBeforeInitialYield());
1808
1809 // 1. `return <value>` creates and returns a new object,
1810 // `{value: <value>, done: true}`.
1811 //
1812 // For non-async generators, the iterator result object is created in
1813 // bytecode, so we have to simulate that here. For async generators, our
1814 // C++ implementation of AsyncGeneratorResolve will do this. So don't do it
1815 // twice:
1816 if (!genObj->is<AsyncGeneratorObject>()) {
1817 PlainObject* pair = CreateIterResultObject(cx, vp, true);
1818 if (!pair) {
1819 return false;
1820 }
1821 vp.setObject(*pair);
1822 }
1823
1824 // 2. The generator must be closed.
1825 genObj->setClosed(cx);
1826
1827 // Async generators have additionally bookkeeping which must be adjusted
1828 // when switching over to the closed state.
1829 if (genObj->is<AsyncGeneratorObject>()) {
1830 genObj->as<AsyncGeneratorObject>().setCompleted();
1831 }
1832 } else if (isAsyncModule || frame.callee()->isAsync()) {
1833 if (AbstractGeneratorObject* genObj =
1834 GetGeneratorObjectForFrame(cx, frame)) {
1835 // Throw doesn't require any special processing for async functions when
1836 // the internal generator object is already present.
1837 if (resumeMode == ResumeMode::Throw) {
1838 return true;
1839 }
1840
1841 Rooted<AsyncFunctionGeneratorObject*> generator(
1842 cx, &genObj->as<AsyncFunctionGeneratorObject>());
1843
1844 // 1. `return <value>` fulfills and returns the async function's promise.
1845 Rooted<PromiseObject*> promise(cx, generator->promise());
1846 if (promise->state() == JS::PromiseState::Pending) {
1847 if (!AsyncFunctionResolve(cx, generator, vp)) {
1848 return false;
1849 }
1850 }
1851 vp.setObject(*promise);
1852
1853 // 2. The generator must be closed.
1854 generator->setClosed(cx);
1855 } else {
1856 // We're before entering the actual function code.
1857
1858 // 1. `throw <value>` creates a promise rejected with the value *vp.
1859 // 1. `return <value>` creates a promise resolved with the value *vp.
1860 JSObject* promise = resumeMode == ResumeMode::Throw
1861 ? PromiseObject::unforgeableReject(cx, vp)
1862 : PromiseObject::unforgeableResolve(cx, vp);
1863 if (!promise) {
1864 return false;
1865 }
1866 vp.setObject(*promise);
1867
1868 // 2. Return normally in both cases.
1869 resumeMode = ResumeMode::Return;
1870 }
1871 }
1872
1873 return true;
1874 }
1875
1876 bool Debugger::processParsedHandlerResult(JSContext* cx, AbstractFramePtr frame,
1877 const jsbytecode* pc, bool success,
1878 ResumeMode resumeMode,
1879 HandleValue value,
1880 ResumeMode& resultMode,
1881 MutableHandleValue vp) {
1882 RootedValue rootValue(cx, value);
1883 if (!success || !prepareResumption(cx, frame, pc, resumeMode, &rootValue)) {
1884 RootedValue exceptionRv(cx);
1885 if (!callUncaughtExceptionHandler(cx, &exceptionRv) ||
1886 !ParseResumptionValue(cx, exceptionRv, resumeMode, &rootValue) ||
1887 !prepareResumption(cx, frame, pc, resumeMode, &rootValue)) {
1888 return false;
1889 }
1890 }
1891
1892 // Since debugger hooks accumulate into the same final value handle, we
1893 // use that to throw if multiple hooks try to set a resumption value.
1894 if (resumeMode != ResumeMode::Continue) {
1895 if (resultMode != ResumeMode::Continue) {
1896 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
1897 JSMSG_DEBUG_RESUMPTION_CONFLICT);
1898 return false;
1899 }
1900
1901 vp.set(rootValue);
1902 resultMode = resumeMode;
1903 }
1904
1905 return true;
1906 }
1907
1908 bool Debugger::processHandlerResult(JSContext* cx, bool success, HandleValue rv,
1909 AbstractFramePtr frame, jsbytecode* pc,
1910 ResumeMode& resultMode,
1911 MutableHandleValue vp) {
1912 ResumeMode resumeMode = ResumeMode::Continue;
1913 RootedValue value(cx);
1914 if (success) {
1915 success = ParseResumptionValue(cx, rv, resumeMode, &value);
1916 }
1917 return processParsedHandlerResult(cx, frame, pc, success, resumeMode, value,
1918 resultMode, vp);
1919 }
1920
1921 bool Debugger::prepareResumption(JSContext* cx, AbstractFramePtr frame,
1922 const jsbytecode* pc, ResumeMode& resumeMode,
1923 MutableHandleValue vp) {
1924 return unwrapDebuggeeValue(cx, vp) &&
1925 CheckResumptionValue(cx, frame, pc, resumeMode, vp);
1926 }
1927
1928 bool Debugger::callUncaughtExceptionHandler(JSContext* cx,
1929 MutableHandleValue vp) {
1930 // Uncaught exceptions arise from Debugger code, and so we must already be in
1931 // an NX section. This also establishes that we are already within the scope
1932 // of an AutoDebuggerJobQueueInterruption object.
1933 MOZ_ASSERT(EnterDebuggeeNoExecute::isLockedInStack(cx, *this));
1934
1935 if (cx->isExceptionPending() && uncaughtExceptionHook) {
1936 RootedValue exc(cx);
1937 if (!cx->getPendingException(&exc)) {
1938 return false;
1939 }
1940 cx->clearPendingException();
1941
1942 RootedValue fval(cx, ObjectValue(*uncaughtExceptionHook));
1943 if (js::Call(cx, fval, object, exc, vp)) {
1944 return true;
1945 }
1946 }
1947 return false;
1948 }
1949
1950 bool Debugger::handleUncaughtException(JSContext* cx) {
1951 RootedValue rv(cx);
1952
1953 return callUncaughtExceptionHandler(cx, &rv);
1954 }
1955
1956 void Debugger::reportUncaughtException(JSContext* cx) {
1957 // Uncaught exceptions arise from Debugger code, and so we must already be
1958 // in an NX section.
1959 MOZ_ASSERT(EnterDebuggeeNoExecute::isLockedInStack(cx, *this));
1960
1961 if (cx->isExceptionPending()) {
1962 // We want to report the pending exception, but we want to let the
1963 // embedding handle it however it wants to. So pretend like we're
1964 // starting a new script execution on our current compartment (which
1965 // is the debugger compartment, so reported errors won't get
1966 // reported to various onerror handlers in debuggees) and as part of
1967 // that "execution" simply throw our exception so the embedding can
1968 // deal.
1969 RootedValue exn(cx);
1970 if (cx->getPendingException(&exn)) {
1971 // Clear the exception, because ReportErrorToGlobal will assert that
1972 // we don't have one.
1973 cx->clearPendingException();
1974 ReportErrorToGlobal(cx, cx->global(), exn);
1975 }
1976
1977 // And if not, or if PrepareScriptEnvironmentAndInvoke somehow left an
1978 // exception on cx (which it totally shouldn't do), just give up.
1979 cx->clearPendingException();
1980 }
1981 }
1982
1983 /*** Debuggee completion values *********************************************/
1984
1985 /* static */
1986 Completion Completion::fromJSResult(JSContext* cx, bool ok, const Value& rv) {
1987 MOZ_ASSERT_IF(ok, !cx->isExceptionPending());
1988
1989 if (ok) {
1990 return Completion(Return(rv));
1991 }
1992
1993 if (!cx->isExceptionPending()) {
1994 return Completion(Terminate());
1995 }
1996
1997 RootedValue exception(cx);
1998 Rooted<SavedFrame*> stack(cx, cx->getPendingExceptionStack());
1999 bool getSucceeded = cx->getPendingException(&exception);
2000 cx->clearPendingException();
2001 if (!getSucceeded) {
2002 return Completion(Terminate());
2003 }
2004
2005 return Completion(Throw(exception, stack));
2006 }
2007
2008 /* static */
2009 Completion Completion::fromJSFramePop(JSContext* cx, AbstractFramePtr frame,
2010 const jsbytecode* pc, bool ok) {
2011 // Only Wasm frames get a null pc.
2012 MOZ_ASSERT_IF(!frame.isWasmDebugFrame(), pc);
2013
2014 // If this isn't a generator suspension, then that's already handled above.
2015 if (!ok || !frame.isGeneratorFrame()) {
2016 return fromJSResult(cx, ok, frame.returnValue());
2017 }
2018
2019 // A generator is being suspended or returning.
2020
2021 // Since generators are never wasm, we can assume pc is not nullptr, and
2022 // that analyzing bytecode is meaningful.
2023 MOZ_ASSERT(!frame.isWasmDebugFrame());
2024
2025 // If we're leaving successfully at a yield opcode, we're probably
2026 // suspending; the `isClosed()` check detects a debugger forced return from
2027 // an `onStep` handler, which looks almost the same.
2028 //
2029 // GetGeneratorObjectForFrame can return nullptr even when a generator
2030 // object does exist, if the frame is paused between the Generator and
2031 // SetAliasedVar opcodes.
2032 Rooted<AbstractGeneratorObject*> generatorObj(
2033 cx, GetGeneratorObjectForFrame(cx, frame));
2034
2035 if (generatorObj && !generatorObj->isClosed()) {
2036 switch (JSOp(*pc)) {
2037 case JSOp::InitialYield:
2038 return Completion(InitialYield(generatorObj));
2039
2040 case JSOp::Yield:
2041 return Completion(Yield(generatorObj, frame.returnValue()));
2042
2043 case JSOp::Await:
2044 return Completion(Await(generatorObj, frame.returnValue()));
2045
2046 default:
2047 break;
2048 }
2049 }
2050
2051 return Completion(Return(frame.returnValue()));
2052 }
2053
2054 void Completion::trace(JSTracer* trc) {
2055 variant.match([=](auto& var) { var.trace(trc); });
2056 }
2057
2058 struct MOZ_STACK_CLASS Completion::BuildValueMatcher {
2059 JSContext* cx;
2060 Debugger* dbg;
2061 MutableHandleValue result;
2062
2063 BuildValueMatcher(JSContext* cx, Debugger* dbg, MutableHandleValue result)
2064 : cx(cx), dbg(dbg), result(result) {
2065 cx->check(dbg->toJSObject());
2066 }
2067
2068 bool operator()(const Completion::Return& ret) {
2069 Rooted<NativeObject*> obj(cx, newObject());
2070 RootedValue retval(cx, ret.value);
2071 if (!obj || !wrap(&retval) || !add(obj, cx->names().return_, retval)) {
2072 return false;
2073 }
2074 result.setObject(*obj);
2075 return true;
2076 }
2077
2078 bool operator()(const Completion::Throw& thr) {
2079 Rooted<NativeObject*> obj(cx, newObject());
2080 RootedValue exc(cx, thr.exception);
2081 if (!obj || !wrap(&exc) || !add(obj, cx->names().throw_, exc)) {
2082 return false;
2083 }
2084 if (thr.stack) {
2085 RootedValue stack(cx, ObjectValue(*thr.stack));
2086 if (!wrapStack(&stack) || !add(obj, cx->names().stack, stack)) {
2087 return false;
2088 }
2089 }
2090 result.setObject(*obj);
2091 return true;
2092 }
2093
2094 bool operator()(const Completion::Terminate& term) {
2095 result.setNull();
2096 return true;
2097 }
2098
2099 bool operator()(const Completion::InitialYield& initialYield) {
2100 Rooted<NativeObject*> obj(cx, newObject());
2101 RootedValue gen(cx, ObjectValue(*initialYield.generatorObject));
2102 if (!obj || !wrap(&gen) || !add(obj, cx->names().return_, gen) ||
2103 !add(obj, cx->names().yield, TrueHandleValue) ||
2104 !add(obj, cx->names().initial, TrueHandleValue)) {
2105 return false;
2106 }
2107 result.setObject(*obj);
2108 return true;
2109 }
2110
2111 bool operator()(const Completion::Yield& yield) {
2112 Rooted<NativeObject*> obj(cx, newObject());
2113 RootedValue iteratorResult(cx, yield.iteratorResult);
2114 if (!obj || !wrap(&iteratorResult) ||
2115 !add(obj, cx->names().return_, iteratorResult) ||
2116 !add(obj, cx->names().yield, TrueHandleValue)) {
2117 return false;
2118 }
2119 result.setObject(*obj);
2120 return true;
2121 }
2122
2123 bool operator()(const Completion::Await& await) {
2124 Rooted<NativeObject*> obj(cx, newObject());
2125 RootedValue awaitee(cx, await.awaitee);
2126 if (!obj || !wrap(&awaitee) || !add(obj, cx->names().return_, awaitee) ||
2127 !add(obj, cx->names().await, TrueHandleValue)) {
2128 return false;
2129 }
2130 result.setObject(*obj);
2131 return true;
2132 }
2133
2134 private:
2135 NativeObject* newObject() const { return NewPlainObject(cx); }
2136
2137 bool add(Handle<NativeObject*> obj, PropertyName* name,
2138 HandleValue value) const {
2139 return NativeDefineDataProperty(cx, obj, name, value, JSPROP_ENUMERATE);
2140 }
2141
2142 bool wrap(MutableHandleValue v) const {
2143 return dbg->wrapDebuggeeValue(cx, v);
2144 }
2145
2146 // Saved stacks are wrapped for direct consumption by debugger code.
2147 bool wrapStack(MutableHandleValue stack) const {
2148 return cx->compartment()->wrap(cx, stack);
2149 }
2150 };
2151
2152 bool Completion::buildCompletionValue(JSContext* cx, Debugger* dbg,
2153 MutableHandleValue result) const {
2154 return variant.match(BuildValueMatcher(cx, dbg, result));
2155 }
2156
2157 void Completion::updateFromHookResult(ResumeMode resumeMode,
2158 HandleValue value) {
2159 switch (resumeMode) {
2160 case ResumeMode::Continue:
2161 // No change to how we'll resume.
2162 break;
2163
2164 case ResumeMode::Throw:
2165 // Since this is a new exception, the stack for the old one may not apply.
2166 // If we extend resumption values to specify stacks, we could revisit
2167 // this.
2168 variant = Variant(Throw(value, nullptr));
2169 break;
2170
2171 case ResumeMode::Terminate:
2172 variant = Variant(Terminate());
2173 break;
2174
2175 case ResumeMode::Return:
2176 variant = Variant(Return(value));
2177 break;
2178
2179 default:
2180 MOZ_CRASH("invalid resumeMode value");
2181 }
2182 }
2183
2184 struct MOZ_STACK_CLASS Completion::ToResumeModeMatcher {
2185 MutableHandleValue value;
2186 MutableHandle<SavedFrame*> exnStack;
2187 ToResumeModeMatcher(MutableHandleValue value,
2188 MutableHandle<SavedFrame*> exnStack)
2189 : value(value), exnStack(exnStack) {}
2190
2191 ResumeMode operator()(const Return& ret) {
2192 value.set(ret.value);
2193 return ResumeMode::Return;
2194 }
2195
2196 ResumeMode operator()(const Throw& thr) {
2197 value.set(thr.exception);
2198 exnStack.set(thr.stack);
2199 return ResumeMode::Throw;
2200 }
2201
2202 ResumeMode operator()(const Terminate& term) {
2203 value.setUndefined();
2204 return ResumeMode::Terminate;
2205 }
2206
2207 ResumeMode operator()(const InitialYield& initialYield) {
2208 value.setObject(*initialYield.generatorObject);
2209 return ResumeMode::Return;
2210 }
2211
2212 ResumeMode operator()(const Yield& yield) {
2213 value.set(yield.iteratorResult);
2214 return ResumeMode::Return;
2215 }
2216
2217 ResumeMode operator()(const Await& await) {
2218 value.set(await.awaitee);
2219 return ResumeMode::Return;
2220 }
2221 };
2222
2223 void Completion::toResumeMode(ResumeMode& resumeMode, MutableHandleValue value,
2224 MutableHandle<SavedFrame*> exnStack) const {
2225 resumeMode = variant.match(ToResumeModeMatcher(value, exnStack));
2226 }
2227
2228 /*** Firing debugger hooks **************************************************/
2229
2230 static bool CallMethodIfPresent(JSContext* cx, HandleObject obj,
2231 const char* name, size_t argc, Value* argv,
2232 MutableHandleValue rval) {
2233 rval.setUndefined();
2234 JSAtom* atom = Atomize(cx, name, strlen(name));
2235 if (!atom) {
2236 return false;
2237 }
2238
2239 RootedId id(cx, AtomToId(atom));
2240 RootedValue fval(cx);
2241 if (!GetProperty(cx, obj, obj, id, &fval)) {
2242 return false;
2243 }
2244
2245 if (!IsCallable(fval)) {
2246 return true;
2247 }
2248
2249 InvokeArgs args(cx);
2250 if (!args.init(cx, argc)) {
2251 return false;
2252 }
2253
2254 for (size_t i = 0; i < argc; i++) {
2255 args[i].set(argv[i]);
2256 }
2257
2258 rval.setObject(*obj); // overwritten by successful Call
2259 return js::Call(cx, fval, rval, args, rval);
2260 }
2261
2262 bool Debugger::fireDebuggerStatement(JSContext* cx, ResumeMode& resumeMode,
2263 MutableHandleValue vp) {
2264 RootedObject hook(cx, getHook(OnDebuggerStatement));
2265 MOZ_ASSERT(hook);
2266 MOZ_ASSERT(hook->isCallable());
2267
2268 ScriptFrameIter iter(cx);
2269 RootedValue scriptFrame(cx);
2270 if (!getFrame(cx, iter, &scriptFrame)) {
2271 return false;
2272 }
2273
2274 RootedValue fval(cx, ObjectValue(*hook));
2275 RootedValue rv(cx);
2276 bool ok = js::Call(cx, fval, object, scriptFrame, &rv);
2277 return processHandlerResult(cx, ok, rv, iter.abstractFramePtr(), iter.pc(),
2278 resumeMode, vp);
2279 }
2280
2281 bool Debugger::fireExceptionUnwind(JSContext* cx, HandleValue exc,
2282 ResumeMode& resumeMode,
2283 MutableHandleValue vp) {
2284 RootedObject hook(cx, getHook(OnExceptionUnwind));
2285 MOZ_ASSERT(hook);
2286 MOZ_ASSERT(hook->isCallable());
2287
2288 RootedValue scriptFrame(cx);
2289 RootedValue wrappedExc(cx, exc);
2290
2291 FrameIter iter(cx);
2292 if (!getFrame(cx, iter, &scriptFrame) ||
2293 !wrapDebuggeeValue(cx, &wrappedExc)) {
2294 return false;
2295 }
2296
2297 RootedValue fval(cx, ObjectValue(*hook));
2298 RootedValue rv(cx);
2299 bool ok = js::Call(cx, fval, object, scriptFrame, wrappedExc, &rv);
2300 return processHandlerResult(cx, ok, rv, iter.abstractFramePtr(), iter.pc(),
2301 resumeMode, vp);
2302 }
2303
2304 bool Debugger::fireEnterFrame(JSContext* cx, ResumeMode& resumeMode,
2305 MutableHandleValue vp) {
2306 RootedObject hook(cx, getHook(OnEnterFrame));
2307 MOZ_ASSERT(hook);
2308 MOZ_ASSERT(hook->isCallable());
2309
2310 RootedValue scriptFrame(cx);
2311
2312 FrameIter iter(cx);
2313
2314 #if DEBUG
2315 // Assert that the hook won't be able to re-enter the generator.
2316 if (iter.hasScript() && JSOp(*iter.pc()) == JSOp::AfterYield) {
2317 AutoRealm ar(cx, iter.script());
2318 auto* genObj = GetGeneratorObjectForFrame(cx, iter.abstractFramePtr());
2319 MOZ_ASSERT(genObj->isRunning());
2320 }
2321 #endif
2322
2323 if (!getFrame(cx, iter, &scriptFrame)) {
2324 return false;
2325 }
2326
2327 RootedValue fval(cx, ObjectValue(*hook));
2328 RootedValue rv(cx);
2329 bool ok = js::Call(cx, fval, object, scriptFrame, &rv);
2330
2331 return processHandlerResult(cx, ok, rv, iter.abstractFramePtr(), iter.pc(),
2332 resumeMode, vp);
2333 }
2334
2335 bool Debugger::fireNativeCall(JSContext* cx, const CallArgs& args,
2336 CallReason reason, ResumeMode& resumeMode,
2337 MutableHandleValue vp) {
2338 RootedObject hook(cx, getHook(OnNativeCall));
2339 MOZ_ASSERT(hook);
2340 MOZ_ASSERT(hook->isCallable());
2341
2342 RootedValue fval(cx, ObjectValue(*hook));
2343 RootedValue calleeval(cx, args.calleev());
2344 if (!wrapDebuggeeValue(cx, &calleeval)) {
2345 return false;
2346 }
2347
2348 JSAtom* reasonAtom = nullptr;
2349 switch (reason) {
2350 case CallReason::Call:
2351 reasonAtom = cx->names().call;
2352 break;
2353 case CallReason::CallContent:
2354 reasonAtom = cx->names().call;
2355 break;
2356 case CallReason::FunCall:
2357 reasonAtom = cx->names().call;
2358 break;
2359 case CallReason::Getter:
2360 reasonAtom = cx->names().get;
2361 break;
2362 case CallReason::Setter:
2363 reasonAtom = cx->names().set;
2364 break;
2365 }
2366 MOZ_ASSERT(AtomIsMarked(cx->zone(), reasonAtom));
2367
2368 RootedValue reasonval(cx, StringValue(reasonAtom));
2369
2370 bool ok = false;
2371 RootedValue rv(cx);
2372 if (inspectNativeCallArguments) {
2373 RootedValue thisVal(cx, args.thisv());
2374 // Ignore anything that may make wrapDebuggeeValue to throw
2375 if (thisVal.isMagic() && thisVal.whyMagic() != JS_MISSING_ARGUMENTS &&
2376 thisVal.whyMagic() != JS_UNINITIALIZED_LEXICAL) {
2377 thisVal.setMagic(JS_OPTIMIZED_OUT);
2378 }
2379 if (!wrapDebuggeeValue(cx, &thisVal)) {
2380 return false;
2381 }
2382
2383 unsigned arrsize = args.length();
2384 Rooted<ArrayObject*> arrobj(cx, NewDenseFullyAllocatedArray(cx, arrsize));
2385 if (!arrobj) {
2386 return false;
2387 }
2388 arrobj->ensureDenseInitializedLength(0, arrsize);
2389 for (unsigned i = 0; i < arrsize; i++) {
2390 RootedValue v(cx, args.get(i));
2391 if (!wrapDebuggeeValue(cx, &v)) {
2392 return false;
2393 }
2394 arrobj->setDenseElement(i, v);
2395 }
2396 RootedValue arrayval(cx, ObjectValue(*arrobj));
2397 if (!wrapDebuggeeValue(cx, &arrayval)) {
2398 return false;
2399 }
2400
2401 FixedInvokeArgs<4> iargs(cx);
2402 iargs[0].set(calleeval);
2403 iargs[1].set(reasonval);
2404 iargs[2].set(thisVal);
2405 iargs[3].set(arrayval);
2406
2407 RootedValue thisv(cx, ObjectOrNullValue(object));
2408 ok = js::Call(cx, fval, thisv, iargs, &rv);
2409 } else {
2410 ok = js::Call(cx, fval, object, calleeval, reasonval, &rv);
2411 }
2412
2413 return processHandlerResult(cx, ok, rv, NullFramePtr(), nullptr, resumeMode,
2414 vp);
2415 }
2416
2417 bool Debugger::fireNewScript(JSContext* cx,
2418 Handle<DebuggerScriptReferent> scriptReferent) {
2419 RootedObject hook(cx, getHook(OnNewScript));
2420 MOZ_ASSERT(hook);
2421 MOZ_ASSERT(hook->isCallable());
2422
2423 JSObject* dsobj = wrapVariantReferent(cx, scriptReferent);
2424 if (!dsobj) {
2425 return false;
2426 }
2427
2428 RootedValue fval(cx, ObjectValue(*hook));
2429 RootedValue dsval(cx, ObjectValue(*dsobj));
2430 RootedValue rv(cx);
2431 return js::Call(cx, fval, object, dsval, &rv) || handleUncaughtException(cx);
2432 }
2433
2434 bool Debugger::fireOnGarbageCollectionHook(
2435 JSContext* cx, const JS::dbg::GarbageCollectionEvent::Ptr& gcData) {
2436 MOZ_ASSERT(observedGC(gcData->majorGCNumber()));
2437 observedGCs.remove(gcData->majorGCNumber());
2438
2439 RootedObject hook(cx, getHook(OnGarbageCollection));
2440 MOZ_ASSERT(hook);
2441 MOZ_ASSERT(hook->isCallable());
2442
2443 JSObject* dataObj = gcData->toJSObject(cx);
2444 if (!dataObj) {
2445 return false;
2446 }
2447
2448 RootedValue fval(cx, ObjectValue(*hook));
2449 RootedValue dataVal(cx, ObjectValue(*dataObj));
2450 RootedValue rv(cx);
2451 return js::Call(cx, fval, object, dataVal, &rv) ||
2452 handleUncaughtException(cx);
2453 }
2454
2455 template <typename HookIsEnabledFun /* bool (Debugger*) */,
2456 typename FireHookFun /* bool (Debugger*) */>
2457 /* static */
2458 void Debugger::dispatchQuietHook(JSContext* cx, HookIsEnabledFun hookIsEnabled,
2459 FireHookFun fireHook) {
2460 DebuggerList<HookIsEnabledFun> debuggerList(cx, hookIsEnabled);
2461
2462 if (!debuggerList.init(cx)) {
2463 // init may fail due to OOM. This OOM is not handlable at the
2464 // callsites of dispatchQuietHook in the engine.
2465 cx->clearPendingException();
2466 return;
2467 }
2468
2469 debuggerList.dispatchQuietHook(cx, fireHook);
2470 }
2471
2472 template <typename HookIsEnabledFun /* bool (Debugger*) */, typename FireHookFun /* bool (Debugger*, ResumeMode&, MutableHandleValue vp) */>
2473 /* static */
2474 bool Debugger::dispatchResumptionHook(JSContext* cx, AbstractFramePtr frame,
2475 HookIsEnabledFun hookIsEnabled,
2476 FireHookFun fireHook) {
2477 DebuggerList<HookIsEnabledFun> debuggerList(cx, hookIsEnabled);
2478
2479 if (!debuggerList.init(cx)) {
2480 return false;
2481 }
2482
2483 return debuggerList.dispatchResumptionHook(cx, frame, fireHook);
2484 }
2485
2486 // Maximum length for source URLs that can be remembered.
2487 static const size_t SourceURLMaxLength = 1024;
2488
2489 // Maximum number of source URLs that can be remembered in a realm.
2490 static const size_t SourceURLRealmLimit = 100;
2491
2492 static bool RememberSourceURL(JSContext* cx, HandleScript script) {
2493 cx->check(script);
2494
2495 // Sources introduced dynamically are not remembered.
2496 if (script->sourceObject()->unwrappedIntroductionScript()) {
2497 return true;
2498 }
2499
2500 const char* filename = script->filename();
2501 if (!filename ||
2502 strnlen(filename, SourceURLMaxLength + 1) > SourceURLMaxLength) {
2503 return true;
2504 }
2505
2506 Rooted<ArrayObject*> holder(cx, script->global().getSourceURLsHolder());
2507 if (!holder) {
2508 holder = NewDenseEmptyArray(cx);
2509 if (!holder) {
2510 return false;
2511 }
2512 script->global().setSourceURLsHolder(holder);
2513 }
2514
2515 if (holder->length() >= SourceURLRealmLimit) {
2516 return true;
2517 }
2518
2519 RootedString filenameString(cx,
2520 AtomizeUTF8Chars(cx, filename, strlen(filename)));
2521 if (!filenameString) {
2522 return false;
2523 }
2524
2525 // The source URLs holder never escapes to script, so we can treat it as a
2526 // newborn array for the purpose of adding elements.
2527 return NewbornArrayPush(cx, holder, StringValue(filenameString));
2528 }
2529
2530 void DebugAPI::onNewScript(JSContext* cx, HandleScript script) {
2531 if (!script->realm()->isDebuggee()) {
2532 // Remember the URLs associated with scripts in non-system realms,
2533 // in case the debugger is attached later.
2534 if (!script->realm()->isSystem()) {
2535 if (!RememberSourceURL(cx, script)) {
2536 cx->clearPendingException();
2537 }
2538 }
2539 return;
2540 }
2541
2542 Debugger::dispatchQuietHook(
2543 cx,
2544 [script](Debugger* dbg) -> bool {
2545 return dbg->observesNewScript() && dbg->observesScript(script);
2546 },
2547 [&](Debugger* dbg) -> bool {
2548 BaseScript* base = script.get();
2549 Rooted<DebuggerScriptReferent> scriptReferent(cx, base);
2550 return dbg->fireNewScript(cx, scriptReferent);
2551 });
2552 }
2553
2554 /* static */
2555 void DebugAPI::onSuspendWasmFrame(JSContext* cx, wasm::DebugFrame* debugFrame) {
2556 AbstractFramePtr frame = AbstractFramePtr(debugFrame);
2557 JS::AutoAssertNoGC nogc;
2558 for (Realm::DebuggerVectorEntry& entry : frame.global()->getDebuggers(nogc)) {
2559 Debugger* dbg = entry.dbg;
2560 if (Debugger::FrameMap::Ptr p = dbg->frames.lookup(frame)) {
2561 DebuggerFrame* frameObj = p->value();
2562 frameObj->suspendWasmFrame(cx->gcContext());
2563 }
2564 }
2565 }
2566
2567 /* static */
2568 void DebugAPI::onResumeWasmFrame(JSContext* cx, const FrameIter& iter) {
2569 AbstractFramePtr frame = iter.abstractFramePtr();
2570 MOZ_RELEASE_ASSERT(frame.isWasmDebugFrame());
2571 JS::AutoAssertNoGC nogc;
2572 for (Realm::DebuggerVectorEntry& entry : frame.global()->getDebuggers(nogc)) {
2573 Debugger* dbg = entry.dbg;
2574 if (Debugger::FrameMap::Ptr p = dbg->frames.lookup(frame)) {
2575 DebuggerFrame* frameObj = p->value();
2576 AutoEnterOOMUnsafeRegion oomUnsafe;
2577 if (!frameObj->resume(iter)) {
2578 oomUnsafe.crash("DebugAPI::onResumeWasmFrame");
2579 }
2580 }
2581 }
2582 }
2583
2584 void DebugAPI::slowPathOnNewWasmInstance(
2585 JSContext* cx, Handle<WasmInstanceObject*> wasmInstance) {
2586 Debugger::dispatchQuietHook(
2587 cx,
2588 [wasmInstance](Debugger* dbg) -> bool {
2589 return dbg->observesNewScript() &&
2590 dbg->observesGlobal(&wasmInstance->global());
2591 },
2592 [&](Debugger* dbg) -> bool {
2593 Rooted<DebuggerScriptReferent> scriptReferent(cx, wasmInstance.get());
2594 return dbg->fireNewScript(cx, scriptReferent);
2595 });
2596 }
2597
2598 /* static */
2599 bool DebugAPI::onTrap(JSContext* cx) {
2600 FrameIter iter(cx);
2601 JS::AutoSaveExceptionState savedExc(cx);
2602 Rooted<GlobalObject*> global(cx);
2603 BreakpointSite* site;
2604 bool isJS; // true when iter.hasScript(), false when iter.isWasm()
2605 jsbytecode* pc; // valid when isJS == true
2606 uint32_t bytecodeOffset; // valid when isJS == false
2607 if (iter.hasScript()) {
2608 RootedScript script(cx, iter.script());
2609 MOZ_ASSERT(script->isDebuggee());
2610 global.set(&script->global());
2611 isJS = true;
2612 pc = iter.pc();
2613 bytecodeOffset = 0;
2614 site = DebugScript::getBreakpointSite(script, pc);
2615 } else {
2616 MOZ_ASSERT(iter.isWasm());
2617 global.set(&iter.wasmInstance()->object()->global());
2618 isJS = false;
2619 pc = nullptr;
2620 bytecodeOffset = iter.wasmBytecodeOffset();
2621 site = iter.wasmInstance()->debug().getBreakpointSite(bytecodeOffset);
2622 }
2623
2624 // Build list of breakpoint handlers.
2625 //
2626 // This does not need to be rooted: since the JSScript/WasmInstance is on the
2627 // stack, the Breakpoints will not be GC'd. However, they may be deleted, and
2628 // we check for that case below.
2629 Vector<Breakpoint*> triggered(cx);
2630 for (Breakpoint* bp = site->firstBreakpoint(); bp; bp = bp->nextInSite()) {
2631 if (!triggered.append(bp)) {
2632 return false;
2633 }
2634 }
2635
2636 ResumeMode resumeMode = ResumeMode::Continue;
2637 RootedValue rval(cx);
2638
2639 if (triggered.length() > 0) {
2640 // Preserve the debuggee's microtask event queue while we run the hooks, so
2641 // the debugger's microtask checkpoints don't run from the debuggee's
2642 // microtasks, and vice versa.
2643 JS::AutoDebuggerJobQueueInterruption adjqi;
2644 if (!adjqi.init(cx)) {
2645 return false;
2646 }
2647
2648 for (Breakpoint* bp : triggered) {
2649 // Handlers can clear breakpoints. Check that bp still exists.
2650 if (!site || !site->hasBreakpoint(bp)) {
2651 continue;
2652 }
2653
2654 // We have to check whether dbg is debugging this global here: a
2655 // breakpoint handler can disable other Debuggers or remove debuggees.
2656 Debugger* dbg = bp->debugger;
2657 if (dbg->debuggees.has(global)) {
2658 EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
2659
2660 bool result = dbg->enterDebuggerHook(cx, [&]() -> bool {
2661 RootedValue scriptFrame(cx);
2662 if (!dbg->getFrame(cx, iter, &scriptFrame)) {
2663 return false;
2664 }
2665
2666 // Re-wrap the breakpoint's handler for the Debugger's compartment.
2667 // When the handler and the Debugger are in the same compartment (the
2668 // usual case), this actually unwraps it, but there's no requirement
2669 // that they be in the same compartment, so we can't be sure.
2670 Rooted<JSObject*> handler(cx, bp->handler);
2671 if (!cx->compartment()->wrap(cx, &handler)) {
2672 return false;
2673 }
2674
2675 RootedValue rv(cx);
2676 bool ok = CallMethodIfPresent(cx, handler, "hit", 1,
2677 scriptFrame.address(), &rv);
2678
2679 return dbg->processHandlerResult(cx, ok, rv, iter.abstractFramePtr(),
2680 iter.pc(), resumeMode, &rval);
2681 });
2682 adjqi.runJobs();
2683
2684 if (!result) {
2685 return false;
2686 }
2687
2688 // Calling JS code invalidates site. Reload it.
2689 if (isJS) {
2690 site = DebugScript::getBreakpointSite(iter.script(), pc);
2691 } else {
2692 site = iter.wasmInstance()->debug().getBreakpointSite(bytecodeOffset);
2693 }
2694 }
2695 }
2696 }
2697
2698 if (!ApplyFrameResumeMode(cx, iter.abstractFramePtr(), resumeMode, rval)) {
2699 savedExc.drop();
2700 return false;
2701 }
2702 return true;
2703 }
2704
2705 /* static */
2706 bool DebugAPI::onSingleStep(JSContext* cx) {
2707 FrameIter iter(cx);
2708
2709 // We may be stepping over a JSOp::Exception, that pushes the context's
2710 // pending exception for a 'catch' clause to handle. Don't let the onStep
2711 // handlers mess with that (other than by returning a resumption value).
2712 JS::AutoSaveExceptionState savedExc(cx);
2713
2714 // Build list of Debugger.Frame instances referring to this frame with
2715 // onStep handlers.
2716 Rooted<Debugger::DebuggerFrameVector> frames(cx);
2717 if (!Debugger::getDebuggerFrames(iter.abstractFramePtr(), &frames)) {
2718 ReportOutOfMemory(cx);
2719 return false;
2720 }
2721
2722 #ifdef DEBUG
2723 // Validate the single-step count on this frame's script, to ensure that
2724 // we're not receiving traps we didn't ask for. Even when frames is
2725 // non-empty (and thus we know this trap was requested), do the check
2726 // anyway, to make sure the count has the correct non-zero value.
2727 //
2728 // The converse --- ensuring that we do receive traps when we should --- can
2729 // be done with unit tests.
2730 if (iter.hasScript()) {
2731 uint32_t liveStepperCount = 0;
2732 uint32_t suspendedStepperCount = 0;
2733 JSScript* trappingScript = iter.script();
2734 JS::AutoAssertNoGC nogc;
2735 for (Realm::DebuggerVectorEntry& entry : cx->global()->getDebuggers(nogc)) {
2736 Debugger* dbg = entry.dbg;
2737 for (Debugger::FrameMap::Range r = dbg->frames.all(); !r.empty();
2738 r.popFront()) {
2739 AbstractFramePtr frame = r.front().key();
2740 NativeObject* frameobj = r.front().value();
2741 if (frame.isWasmDebugFrame()) {
2742 continue;
2743 }
2744 if (frame.script() == trappingScript &&
2745 !frameobj->getReservedSlot(DebuggerFrame::ONSTEP_HANDLER_SLOT)
2746 .isUndefined()) {
2747 liveStepperCount++;
2748 }
2749 }
2750
2751 // Also count hooks set on suspended generator frames.
2752 for (Debugger::GeneratorWeakMap::Range r = dbg->generatorFrames.all();
2753 !r.empty(); r.popFront()) {
2754 AbstractGeneratorObject& genObj = *r.front().key();
2755 DebuggerFrame& frameObj = *r.front().value();
2756 MOZ_ASSERT(&frameObj.unwrappedGenerator() == &genObj);
2757
2758 // Live Debugger.Frames were already counted in dbg->frames loop.
2759 if (frameObj.isOnStack()) {
2760 continue;
2761 }
2762
2763 // A closed generator no longer has a callee so it will not be able to
2764 // compare with the trappingScript.
2765 if (genObj.isClosed()) {
2766 continue;
2767 }
2768
2769 // If a frame isn't live, but it has an entry in generatorFrames,
2770 // it had better be suspended.
2771 MOZ_ASSERT(genObj.isSuspended());
2772
2773 if (genObj.callee().hasBaseScript() &&
2774 genObj.callee().baseScript() == trappingScript &&
2775 !frameObj.getReservedSlot(DebuggerFrame::ONSTEP_HANDLER_SLOT)
2776 .isUndefined()) {
2777 suspendedStepperCount++;
2778 }
2779 }
2780 }
2781
2782 MOZ_ASSERT(liveStepperCount + suspendedStepperCount ==
2783 DebugScript::getStepperCount(trappingScript));
2784 }
2785 #endif
2786
2787 RootedValue rval(cx);
2788 ResumeMode resumeMode = ResumeMode::Continue;
2789
2790 if (frames.length() > 0) {
2791 // Preserve the debuggee's microtask event queue while we run the hooks, so
2792 // the debugger's microtask checkpoints don't run from the debuggee's
2793 // microtasks, and vice versa.
2794 JS::AutoDebuggerJobQueueInterruption adjqi;
2795 if (!adjqi.init(cx)) {
2796 return false;
2797 }
2798
2799 // Call onStep for frames that have the handler set.
2800 for (size_t i = 0; i < frames.length(); i++) {
2801 Handle<DebuggerFrame*> frame = frames[i];
2802 OnStepHandler* handler = frame->onStepHandler();
2803 if (!handler) {
2804 continue;
2805 }
2806
2807 Debugger* dbg = frame->owner();
2808 EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
2809
2810 bool result = dbg->enterDebuggerHook(cx, [&]() -> bool {
2811 ResumeMode nextResumeMode = ResumeMode::Continue;
2812 RootedValue nextValue(cx);
2813
2814 bool success = handler->onStep(cx, frame, nextResumeMode, &nextValue);
2815 return dbg->processParsedHandlerResult(
2816 cx, iter.abstractFramePtr(), iter.pc(), success, nextResumeMode,
2817 nextValue, resumeMode, &rval);
2818 });
2819 adjqi.runJobs();
2820
2821 if (!result) {
2822 return false;
2823 }
2824 }
2825 }
2826
2827 if (!ApplyFrameResumeMode(cx, iter.abstractFramePtr(), resumeMode, rval)) {
2828 savedExc.drop();
2829 return false;
2830 }
2831 return true;
2832 }
2833
2834 bool Debugger::fireNewGlobalObject(JSContext* cx,
2835 Handle<GlobalObject*> global) {
2836 RootedObject hook(cx, getHook(OnNewGlobalObject));
2837 MOZ_ASSERT(hook);
2838 MOZ_ASSERT(hook->isCallable());
2839
2840 RootedValue wrappedGlobal(cx, ObjectValue(*global));
2841 if (!wrapDebuggeeValue(cx, &wrappedGlobal)) {
2842 return false;
2843 }
2844
2845 // onNewGlobalObject is infallible, and thus is only allowed to return
2846 // undefined as a resumption value. If it returns anything else, we throw.
2847 // And if that happens, or if the hook itself throws, we invoke the
2848 // uncaughtExceptionHook so that we never leave an exception pending on the
2849 // cx. This allows JS_NewGlobalObject to avoid handling failures from
2850 // debugger hooks.
2851 RootedValue rv(cx);
2852 RootedValue fval(cx, ObjectValue(*hook));
2853 bool ok = js::Call(cx, fval, object, wrappedGlobal, &rv);
2854 if (ok && !rv.isUndefined()) {
2855 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2856 JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED);
2857 ok = false;
2858 }
2859
2860 return ok || handleUncaughtException(cx);
2861 }
2862
2863 void DebugAPI::slowPathOnNewGlobalObject(JSContext* cx,
2864 Handle<GlobalObject*> global) {
2865 MOZ_ASSERT(!cx->runtime()->onNewGlobalObjectWatchers().isEmpty());
2866 if (global->realm()->creationOptions().invisibleToDebugger()) {
2867 return;
2868 }
2869
2870 // Make a copy of the runtime's onNewGlobalObjectWatchers before running the
2871 // handlers. Since one Debugger's handler can disable another's, the list
2872 // can be mutated while we're walking it.
2873 RootedObjectVector watchers(cx);
2874 for (auto& dbg : cx->runtime()->onNewGlobalObjectWatchers()) {
2875 MOZ_ASSERT(dbg.observesNewGlobalObject());
2876 JSObject* obj = dbg.object;
2877 JS::ExposeObjectToActiveJS(obj);
2878 if (!watchers.append(obj)) {
2879 if (cx->isExceptionPending()) {
2880 cx->clearPendingException();
2881 }
2882 return;
2883 }
2884 }
2885
2886 // Preserve the debuggee's microtask event queue while we run the hooks, so
2887 // the debugger's microtask checkpoints don't run from the debuggee's
2888 // microtasks, and vice versa.
2889 JS::AutoDebuggerJobQueueInterruption adjqi;
2890 if (!adjqi.init(cx)) {
2891 cx->clearPendingException();
2892 return;
2893 }
2894
2895 for (size_t i = 0; i < watchers.length(); i++) {
2896 Debugger* dbg = Debugger::fromJSObject(watchers[i]);
2897 EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
2898
2899 if (dbg->observesNewGlobalObject()) {
2900 bool result = dbg->enterDebuggerHook(
2901 cx, [&]() -> bool { return dbg->fireNewGlobalObject(cx, global); });
2902 adjqi.runJobs();
2903
2904 if (!result) {
2905 // Like other quiet hooks using dispatchQuietHook, this hook
2906 // silently ignores all errors that propagate out of it and aren't
2907 // already handled by the hook error reporting.
2908 cx->clearPendingException();
2909 break;
2910 }
2911 }
2912 }
2913 MOZ_ASSERT(!cx->isExceptionPending());
2914 }
2915
2916 /* static */
2917 void DebugAPI::slowPathOnGeneratorClosed(JSContext* cx,
2918 AbstractGeneratorObject* genObj) {
2919 JS::AutoAssertNoGC nogc;
2920 for (Realm::DebuggerVectorEntry& entry : cx->global()->getDebuggers(nogc)) {
2921 Debugger* dbg = entry.dbg;
2922 if (Debugger::GeneratorWeakMap::Ptr frameEntry =
2923 dbg->generatorFrames.lookup(genObj)) {
2924 DebuggerFrame* frameObj = frameEntry->value();
2925 frameObj->onGeneratorClosed(cx->gcContext());
2926 }
2927 }
2928 }
2929
2930 /* static */
2931 void DebugAPI::slowPathNotifyParticipatesInGC(uint64_t majorGCNumber,
2932 Realm::DebuggerVector& dbgs,
2933 const JS::AutoRequireNoGC& nogc) {
2934 for (Realm::DebuggerVector::Range r = dbgs.all(); !r.empty(); r.popFront()) {
2935 if (!r.front().dbg.unbarrieredGet()->debuggeeIsBeingCollected(
2936 majorGCNumber)) {
2937 #ifdef DEBUG
2938 fprintf(stderr,
2939 "OOM while notifying observing Debuggers of a GC: The "
2940 "onGarbageCollection\n"
2941 "hook will not be fired for this GC for some Debuggers!\n");
2942 #endif
2943 return;
2944 }
2945 }
2946 }
2947
2948 /* static */
2949 Maybe<double> DebugAPI::allocationSamplingProbability(GlobalObject* global) {
2950 JS::AutoAssertNoGC nogc;
2951 Realm::DebuggerVector& dbgs = global->getDebuggers(nogc);
2952 if (dbgs.empty()) {
2953 return Nothing();
2954 }
2955
2956 DebugOnly<Realm::DebuggerVectorEntry*> begin = dbgs.begin();
2957
2958 double probability = 0;
2959 bool foundAnyDebuggers = false;
2960 for (auto p = dbgs.begin(); p < dbgs.end(); p++) {
2961 // The set of debuggers had better not change while we're iterating,
2962 // such that the vector gets reallocated.
2963 MOZ_ASSERT(dbgs.begin() == begin);
2964 // Use unbarrieredGet() to prevent triggering read barrier while collecting,
2965 // this is safe as long as dbgp does not escape.
2966 Debugger* dbgp = p->dbg.unbarrieredGet();
2967
2968 if (dbgp->trackingAllocationSites) {
2969 foundAnyDebuggers = true;
2970 probability = std::max(dbgp->allocationSamplingProbability, probability);
2971 }
2972 }
2973
2974 return foundAnyDebuggers ? Some(probability) : Nothing();
2975 }
2976
2977 /* static */
2978 bool DebugAPI::slowPathOnLogAllocationSite(JSContext* cx, HandleObject obj,
2979 Handle<SavedFrame*> frame,
2980 mozilla::TimeStamp when,
2981 Realm::DebuggerVector& dbgs,
2982 const gc::AutoSuppressGC& nogc) {
2983 MOZ_ASSERT(!dbgs.empty());
2984 mozilla::DebugOnly<Realm::DebuggerVectorEntry*> begin = dbgs.begin();
2985
2986 // GC is suppressed so we can iterate over the debuggers; appendAllocationSite
2987 // calls Compartment::wrap, and thus could GC.
2988
2989 for (auto p = dbgs.begin(); p < dbgs.end(); p++) {
2990 // The set of debuggers had better not change while we're iterating,
2991 // such that the vector gets reallocated.
2992 MOZ_ASSERT(dbgs.begin() == begin);
2993
2994 if (p->dbg->trackingAllocationSites &&
2995 !p->dbg->appendAllocationSite(cx, obj, frame, when)) {
2996 return false;
2997 }
2998 }
2999
3000 return true;
3001 }
3002
3003 bool Debugger::isDebuggeeUnbarriered(const Realm* realm) const {
3004 MOZ_ASSERT(realm);
3005 return realm->isDebuggee() &&
3006 debuggees.has(realm->unsafeUnbarrieredMaybeGlobal());
3007 }
3008
3009 bool Debugger::appendAllocationSite(JSContext* cx, HandleObject obj,
3010 Handle<SavedFrame*> frame,
3011 mozilla::TimeStamp when) {
3012 MOZ_ASSERT(trackingAllocationSites);
3013
3014 AutoRealm ar(cx, object);
3015 RootedObject wrappedFrame(cx, frame);
3016 if (!cx->compartment()->wrap(cx, &wrappedFrame)) {
3017 return false;
3018 }
3019
3020 auto className = obj->getClass()->name;
3021 auto size =
3022 JS::ubi::Node(obj.get()).size(cx->runtime()->debuggerMallocSizeOf);
3023 auto inNursery = gc::IsInsideNursery(obj);
3024
3025 if (!allocationsLog.emplaceBack(wrappedFrame, when, className, size,
3026 inNursery)) {
3027 ReportOutOfMemory(cx);
3028 return false;
3029 }
3030
3031 if (allocationsLog.length() > maxAllocationsLogLength) {
3032 allocationsLog.popFront();
3033 MOZ_ASSERT(allocationsLog.length() == maxAllocationsLogLength);
3034 allocationsLogOverflowed = true;
3035 }
3036
3037 return true;
3038 }
3039
3040 bool Debugger::firePromiseHook(JSContext* cx, Hook hook, HandleObject promise) {
3041 MOZ_ASSERT(hook == OnNewPromise || hook == OnPromiseSettled);
3042
3043 RootedObject hookObj(cx, getHook(hook));
3044 MOZ_ASSERT(hookObj);
3045 MOZ_ASSERT(hookObj->isCallable());
3046
3047 RootedValue dbgObj(cx, ObjectValue(*promise));
3048 if (!wrapDebuggeeValue(cx, &dbgObj)) {
3049 return false;
3050 }
3051
3052 // Like onNewGlobalObject, the Promise hooks are infallible and the comments
3053 // in |Debugger::fireNewGlobalObject| apply here as well.
3054 RootedValue fval(cx, ObjectValue(*hookObj));
3055 RootedValue rv(cx);
3056 bool ok = js::Call(cx, fval, object, dbgObj, &rv);
3057 if (ok && !rv.isUndefined()) {
3058 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3059 JSMSG_DEBUG_RESUMPTION_VALUE_DISALLOWED);
3060 ok = false;
3061 }
3062
3063 return ok || handleUncaughtException(cx);
3064 }
3065
3066 /* static */
3067 void Debugger::slowPathPromiseHook(JSContext* cx, Hook hook,
3068 Handle<PromiseObject*> promise) {
3069 MOZ_ASSERT(hook == OnNewPromise || hook == OnPromiseSettled);
3070
3071 if (hook == OnPromiseSettled) {
3072 // We should be in the right compartment, but for simplicity always enter
3073 // the promise's realm below.
3074 cx->check(promise);
3075 }
3076
3077 AutoRealm ar(cx, promise);
3078
3079 Debugger::dispatchQuietHook(
3080 cx, [hook](Debugger* dbg) -> bool { return dbg->getHook(hook); },
3081 [&](Debugger* dbg) -> bool {
3082 return dbg->firePromiseHook(cx, hook, promise);
3083 });
3084 }
3085
3086 /* static */
3087 void DebugAPI::slowPathOnNewPromise(JSContext* cx,
3088 Handle<PromiseObject*> promise) {
3089 Debugger::slowPathPromiseHook(cx, Debugger::OnNewPromise, promise);
3090 }
3091
3092 /* static */
3093 void DebugAPI::slowPathOnPromiseSettled(JSContext* cx,
3094 Handle<PromiseObject*> promise) {
3095 Debugger::slowPathPromiseHook(cx, Debugger::OnPromiseSettled, promise);
3096 }
3097
3098 /*** Debugger code invalidation for observing execution *********************/
3099
3100 class MOZ_RAII ExecutionObservableRealms
3101 : public DebugAPI::ExecutionObservableSet {
3102 HashSet<Realm*> realms_;
3103 HashSet<Zone*> zones_;
3104
3105 public:
3106 explicit ExecutionObservableRealms(JSContext* cx) : realms_(cx), zones_(cx) {}
3107
3108 bool add(Realm* realm) {
3109 return realms_.put(realm) && zones_.put(realm->zone());
3110 }
3111
3112 using RealmRange = HashSet<Realm*>::Range;
3113 const HashSet<Realm*>* realms() const { return &realms_; }
3114
3115 const HashSet<Zone*>* zones() const override { return &zones_; }
3116 bool shouldRecompileOrInvalidate(JSScript* script) const override {
3117 return script->hasBaselineScript() && realms_.has(script->realm());
3118 }
3119 bool shouldMarkAsDebuggee(FrameIter& iter) const override {
3120 // AbstractFramePtr can't refer to non-remateralized Ion frames or
3121 // non-debuggee wasm frames, so if iter refers to one such, we know we
3122 // don't match.
3123 return iter.hasUsableAbstractFramePtr() && realms_.has(iter.realm());
3124 }
3125 };
3126
3127 // Given a particular AbstractFramePtr F that has become observable, this
3128 // represents the stack frames that need to be bailed out or marked as
3129 // debuggees, and the scripts that need to be recompiled, taking inlining into
3130 // account.
3131 class MOZ_RAII ExecutionObservableFrame
3132 : public DebugAPI::ExecutionObservableSet {
3133 AbstractFramePtr frame_;
3134
3135 public:
3136 explicit ExecutionObservableFrame(AbstractFramePtr frame) : frame_(frame) {}
3137
3138 Zone* singleZone() const override {
3139 // We never inline across realms, let alone across zones, so
3140 // frames_'s script's zone is the only one of interest.
3141 return frame_.script()->zone();
3142 }
3143
3144 JSScript* singleScriptForZoneInvalidation() const override {
3145 MOZ_CRASH(
3146 "ExecutionObservableFrame shouldn't need zone-wide invalidation.");
3147 return nullptr;
3148 }
3149
3150 bool shouldRecompileOrInvalidate(JSScript* script) const override {
3151 // Normally, *this represents exactly one script: the one frame_ is
3152 // running.
3153 //
3154 // However, debug-mode OSR uses *this for both invalidating Ion frames,
3155 // and recompiling the Baseline scripts that those Ion frames will bail
3156 // out into. Suppose frame_ is an inline frame, executing a copy of its
3157 // JSScript, S_inner, that has been inlined into the IonScript of some
3158 // other JSScript, S_outer. We must match S_outer, to decide which Ion
3159 // frame to invalidate; and we must match S_inner, to decide which
3160 // Baseline script to recompile.
3161 //
3162 // Note that this does not, by design, invalidate *all* inliners of
3163 // frame_.script(), as only frame_ is made observable, not
3164 // frame_.script().
3165 if (!script->hasBaselineScript()) {
3166 return false;
3167 }
3168
3169 if (frame_.hasScript() && script == frame_.script()) {
3170 return true;
3171 }
3172
3173 return frame_.isRematerializedFrame() &&
3174 script == frame_.asRematerializedFrame()->outerScript();
3175 }
3176
3177 bool shouldMarkAsDebuggee(FrameIter& iter) const override {
3178 // AbstractFramePtr can't refer to non-remateralized Ion frames or
3179 // non-debuggee wasm frames, so if iter refers to one such, we know we
3180 // don't match.
3181 //
3182 // We never use this 'has' overload for frame invalidation, only for
3183 // frame debuggee marking; so this overload doesn't need a parallel to
3184 // the just-so inlining logic above.
3185 return iter.hasUsableAbstractFramePtr() &&
3186 iter.abstractFramePtr() == frame_;
3187 }
3188 };
3189
3190 class MOZ_RAII ExecutionObservableScript
3191 : public DebugAPI::ExecutionObservableSet {
3192 RootedScript script_;
3193
3194 public:
3195 ExecutionObservableScript(JSContext* cx, JSScript* script)
3196 : script_(cx, script) {}
3197
3198 Zone* singleZone() const override { return script_->zone(); }
3199 JSScript* singleScriptForZoneInvalidation() const override { return script_; }
3200 bool shouldRecompileOrInvalidate(JSScript* script) const override {
3201 return script->hasBaselineScript() && script == script_;
3202 }
3203 bool shouldMarkAsDebuggee(FrameIter& iter) const override {
3204 // AbstractFramePtr can't refer to non-remateralized Ion frames, and
3205 // while a non-rematerialized Ion frame may indeed be running script_,
3206 // we cannot mark them as debuggees until they bail out.
3207 //
3208 // Upon bailing out, any newly constructed Baseline frames that came
3209 // from Ion frames with scripts that are isDebuggee() is marked as
3210 // debuggee. This is correct in that the only other way a frame may be
3211 // marked as debuggee is via Debugger.Frame reflection, which would
3212 // have rematerialized any Ion frames.
3213 //
3214 // Also AbstractFramePtr can't refer to non-debuggee wasm frames, so if
3215 // iter refers to one such, we know we don't match.
3216 return iter.hasUsableAbstractFramePtr() && !iter.isWasm() &&
3217 iter.abstractFramePtr().script() == script_;
3218 }
3219 };
3220
3221 /* static */
3222 bool Debugger::updateExecutionObservabilityOfFrames(
3223 JSContext* cx, const DebugAPI::ExecutionObservableSet& obs,
3224 IsObserving observing) {
3225 AutoSuppressProfilerSampling suppressProfilerSampling(cx);
3226
3227 if (!jit::RecompileOnStackBaselineScriptsForDebugMode(cx, obs, observing)) {
3228 return false;
3229 }
3230
3231 AbstractFramePtr oldestEnabledFrame;
3232 for (AllFramesIter iter(cx); !iter.done(); ++iter) {
3233 if (obs.shouldMarkAsDebuggee(iter)) {
3234 if (observing) {
3235 if (!iter.abstractFramePtr().isDebuggee()) {
3236 oldestEnabledFrame = iter.abstractFramePtr();
3237 oldestEnabledFrame.setIsDebuggee();
3238 }
3239 if (iter.abstractFramePtr().isWasmDebugFrame()) {
3240 iter.abstractFramePtr().asWasmDebugFrame()->observe(cx);
3241 }
3242 } else {
3243 #ifdef DEBUG
3244 // Debugger.Frame lifetimes are managed by the debug epilogue,
3245 // so in general it's unsafe to unmark a frame if it has a
3246 // Debugger.Frame associated with it.
3247 MOZ_ASSERT(!DebugAPI::inFrameMaps(iter.abstractFramePtr()));
3248 #endif
3249 iter.abstractFramePtr().unsetIsDebuggee();
3250 }
3251 }
3252 }
3253
3254 // See comment in unsetPrevUpToDateUntil.
3255 if (oldestEnabledFrame) {
3256 AutoRealm ar(cx, oldestEnabledFrame.environmentChain());
3257 DebugEnvironments::unsetPrevUpToDateUntil(cx, oldestEnabledFrame);
3258 }
3259
3260 return true;
3261 }
3262
3263 static inline void MarkJitScriptActiveIfObservable(
3264 JSScript* script, const DebugAPI::ExecutionObservableSet& obs) {
3265 if (obs.shouldRecompileOrInvalidate(script)) {
3266 script->jitScript()->icScript()->setActive();
3267 }
3268 }
3269
3270 static bool AppendAndInvalidateScript(JSContext* cx, Zone* zone,
3271 JSScript* script,
3272 jit::RecompileInfoVector& invalid,
3273 Vector<JSScript*>& scripts) {
3274 // Enter the script's realm as AddPendingInvalidation attempts to
3275 // cancel off-thread compilations, whose books are kept on the
3276 // script's realm.
3277 MOZ_ASSERT(script->zone() == zone);
3278 AutoRealm ar(cx, script);
3279 AddPendingInvalidation(invalid, script);
3280 return scripts.append(script);
3281 }
3282
3283 static bool UpdateExecutionObservabilityOfScriptsInZone(
3284 JSContext* cx, Zone* zone, const DebugAPI::ExecutionObservableSet& obs,
3285 Debugger::IsObserving observing) {
3286 using namespace js::jit;
3287
3288 AutoSuppressProfilerSampling suppressProfilerSampling(cx);
3289
3290 CancelOffThreadBaselineCompile(zone);
3291
3292 JS::GCContext* gcx = cx->gcContext();
3293
3294 Vector<JSScript*> scripts(cx);
3295
3296 // Iterate through observable scripts, invalidating their Ion scripts and
3297 // appending them to a vector for discarding their baseline scripts later.
3298 {
3299 RecompileInfoVector invalid;
3300 if (JSScript* script = obs.singleScriptForZoneInvalidation()) {
3301 if (obs.shouldRecompileOrInvalidate(script)) {
3302 if (!AppendAndInvalidateScript(cx, zone, script, invalid, scripts)) {
3303 return false;
3304 }
3305 }
3306 } else {
3307 for (auto base = zone->cellIter<BaseScript>(); !base.done();
3308 base.next()) {
3309 if (!base->hasJitScript()) {
3310 continue;
3311 }
3312 JSScript* script = base->asJSScript();
3313 if (obs.shouldRecompileOrInvalidate(script)) {
3314 if (!AppendAndInvalidateScript(cx, zone, script, invalid, scripts)) {
3315 return false;
3316 }
3317 }
3318 }
3319 }
3320 Invalidate(cx, invalid);
3321 }
3322
3323 for (size_t i = 0; i < scripts.length(); i++) {
3324 MOZ_ASSERT(!scripts[i]->jitScript()->icScript()->active());
3325 }
3326
3327 // Code below this point must be infallible to ensure the active bit of
3328 // BaselineScripts is in a consistent state.
3329 //
3330 // Mark active baseline scripts in the observable set so that they don't
3331 // get discarded. They will be recompiled.
3332 for (JitActivationIterator actIter(cx); !actIter.done(); ++actIter) {
3333 if (actIter->compartment()->zone() != zone) {
3334 continue;
3335 }
3336
3337 for (OnlyJSJitFrameIter iter(actIter); !iter.done(); ++iter) {
3338 const JSJitFrameIter& frame = iter.frame();
3339 switch (frame.type()) {
3340 case FrameType::BaselineJS:
3341 MarkJitScriptActiveIfObservable(frame.script(), obs);
3342 break;
3343 case FrameType::IonJS:
3344 MarkJitScriptActiveIfObservable(frame.script(), obs);
3345 for (InlineFrameIterator inlineIter(cx, &frame); inlineIter.more();
3346 ++inlineIter) {
3347 MarkJitScriptActiveIfObservable(inlineIter.script(), obs);
3348 }
3349 break;
3350 default:;
3351 }
3352 }
3353 }
3354
3355 // Iterate through the scripts again and finish discarding
3356 // BaselineScripts. This must be done as a separate phase as we can only
3357 // discard the BaselineScript on scripts that have no IonScript.
3358 for (size_t i = 0; i < scripts.length(); i++) {
3359 MOZ_ASSERT_IF(scripts[i]->isDebuggee(), observing);
3360 if (!scripts[i]->jitScript()->icScript()->active()) {
3361 FinishDiscardBaselineScript(gcx, scripts[i]);
3362 }
3363 scripts[i]->jitScript()->icScript()->resetActive();
3364 }
3365
3366 // Iterate through all wasm instances to find ones that need to be updated.
3367 for (RealmsInZoneIter r(zone); !r.done(); r.next()) {
3368 for (wasm::Instance* instance : r->wasm.instances()) {
3369 if (!instance->debugEnabled()) {
3370 continue;
3371 }
3372
3373 bool enableTrap = observing == Debugger::Observing;
3374 instance->debug().ensureEnterFrameTrapsState(cx, instance, enableTrap);
3375 }
3376 }
3377
3378 return true;
3379 }
3380
3381 /* static */
3382 bool Debugger::updateExecutionObservabilityOfScripts(
3383 JSContext* cx, const DebugAPI::ExecutionObservableSet& obs,
3384 IsObserving observing) {
3385 if (Zone* zone = obs.singleZone()) {
3386 return UpdateExecutionObservabilityOfScriptsInZone(cx, zone, obs,
3387 observing);
3388 }
3389
3390 using ZoneRange = DebugAPI::ExecutionObservableSet::ZoneRange;
3391 for (ZoneRange r = obs.zones()->all(); !r.empty(); r.popFront()) {
3392 if (!UpdateExecutionObservabilityOfScriptsInZone(cx, r.front(), obs,
3393 observing)) {
3394 return false;
3395 }
3396 }
3397
3398 return true;
3399 }
3400
3401 template <typename FrameFn>
3402 /* static */
3403 void Debugger::forEachOnStackDebuggerFrame(AbstractFramePtr frame,
3404 const JS::AutoRequireNoGC& nogc,
3405 FrameFn fn) {
3406 for (Realm::DebuggerVectorEntry& entry : frame.global()->getDebuggers(nogc)) {
3407 Debugger* dbg = entry.dbg;
3408 if (FrameMap::Ptr frameEntry = dbg->frames.lookup(frame)) {
3409 fn(dbg, frameEntry->value());
3410 }
3411 }
3412 }
3413
3414 template <typename FrameFn>
3415 /* static */
3416 void Debugger::forEachOnStackOrSuspendedDebuggerFrame(
3417 JSContext* cx, AbstractFramePtr frame, const JS::AutoRequireNoGC& nogc,
3418 FrameFn fn) {
3419 Rooted<AbstractGeneratorObject*> genObj(
3420 cx, frame.isGeneratorFrame() ? GetGeneratorObjectForFrame(cx, frame)
3421 : nullptr);
3422
3423 for (Realm::DebuggerVectorEntry& entry : frame.global()->getDebuggers(nogc)) {
3424 Debugger* dbg = entry.dbg;
3425
3426 DebuggerFrame* frameObj = nullptr;
3427 if (FrameMap::Ptr frameEntry = dbg->frames.lookup(frame)) {
3428 frameObj = frameEntry->value();
3429 } else if (GeneratorWeakMap::Ptr frameEntry =
3430 dbg->generatorFrames.lookup(genObj)) {
3431 frameObj = frameEntry->value();
3432 }
3433
3434 if (frameObj) {
3435 fn(dbg, frameObj);
3436 }
3437 }
3438 }
3439
3440 /* static */
3441 bool Debugger::getDebuggerFrames(AbstractFramePtr frame,
3442 MutableHandle<DebuggerFrameVector> frames) {
3443 bool hadOOM = false;
3444 JS::AutoAssertNoGC nogc;
3445 forEachOnStackDebuggerFrame(frame, nogc,
3446 [&](Debugger*, DebuggerFrame* frameobj) {
3447 if (!hadOOM && !frames.append(frameobj)) {
3448 hadOOM = true;
3449 }
3450 });
3451 return !hadOOM;
3452 }
3453
3454 /* static */
3455 bool Debugger::updateExecutionObservability(
3456 JSContext* cx, DebugAPI::ExecutionObservableSet& obs,
3457 IsObserving observing) {
3458 if (!obs.singleZone() && obs.zones()->empty()) {
3459 return true;
3460 }
3461
3462 // Invalidate scripts first so we can set the needsArgsObj flag on scripts
3463 // before patching frames.
3464 return updateExecutionObservabilityOfScripts(cx, obs, observing) &&
3465 updateExecutionObservabilityOfFrames(cx, obs, observing);
3466 }
3467
3468 /* static */
3469 bool Debugger::ensureExecutionObservabilityOfScript(JSContext* cx,
3470 JSScript* script) {
3471 if (script->isDebuggee()) {
3472 return true;
3473 }
3474 ExecutionObservableScript obs(cx, script);
3475 return updateExecutionObservability(cx, obs, Observing);
3476 }
3477
3478 /* static */
3479 bool DebugAPI::ensureExecutionObservabilityOfOsrFrame(
3480 JSContext* cx, AbstractFramePtr osrSourceFrame) {
3481 MOZ_ASSERT(osrSourceFrame.isDebuggee());
3482 if (osrSourceFrame.script()->hasBaselineScript() &&
3483 osrSourceFrame.script()->baselineScript()->hasDebugInstrumentation()) {
3484 return true;
3485 }
3486 ExecutionObservableFrame obs(osrSourceFrame);
3487 return Debugger::updateExecutionObservabilityOfFrames(cx, obs, Observing);
3488 }
3489
3490 /* static */
3491 bool Debugger::ensureExecutionObservabilityOfFrame(JSContext* cx,
3492 AbstractFramePtr frame) {
3493 MOZ_ASSERT_IF(frame.hasScript() && frame.script()->isDebuggee(),
3494 frame.isDebuggee());
3495 MOZ_ASSERT_IF(frame.isWasmDebugFrame(), frame.wasmInstance()->debugEnabled());
3496 if (frame.isDebuggee()) {
3497 return true;
3498 }
3499 ExecutionObservableFrame obs(frame);
3500 return updateExecutionObservabilityOfFrames(cx, obs, Observing);
3501 }
3502
3503 /* static */
3504 bool Debugger::ensureExecutionObservabilityOfRealm(JSContext* cx,
3505 Realm* realm) {
3506 if (realm->debuggerObservesAllExecution()) {
3507 return true;
3508 }
3509 ExecutionObservableRealms obs(cx);
3510 if (!obs.add(realm)) {
3511 return false;
3512 }
3513 realm->updateDebuggerObservesAllExecution();
3514 return updateExecutionObservability(cx, obs, Observing);
3515 }
3516
3517 /* static */
3518 bool Debugger::hookObservesAllExecution(Hook which) {
3519 return which == OnEnterFrame;
3520 }
3521
3522 Debugger::IsObserving Debugger::observesAllExecution() const {
3523 if (!!getHook(OnEnterFrame)) {
3524 return Observing;
3525 }
3526 return NotObserving;
3527 }
3528
3529 Debugger::IsObserving Debugger::observesAsmJS() const {
3530 if (!allowUnobservedAsmJS) {
3531 return Observing;
3532 }
3533 return NotObserving;
3534 }
3535
3536 Debugger::IsObserving Debugger::observesWasm() const {
3537 if (!allowUnobservedWasm) {
3538 return Observing;
3539 }
3540 return NotObserving;
3541 }
3542
3543 Debugger::IsObserving Debugger::observesCoverage() const {
3544 if (collectCoverageInfo) {
3545 return Observing;
3546 }
3547 return NotObserving;
3548 }
3549
3550 Debugger::IsObserving Debugger::observesNativeCalls() const {
3551 if (getHook(Debugger::OnNativeCall)) {
3552 return Observing;
3553 }
3554 return NotObserving;
3555 }
3556
3557 bool Debugger::isExclusiveDebuggerOnEval() const {
3558 return exclusiveDebuggerOnEval;
3559 }
3560
3561 // Toggle whether this Debugger's debuggees observe all execution. This is
3562 // called when a hook that observes all execution is set or unset. See
3563 // hookObservesAllExecution.
3564 bool Debugger::updateObservesAllExecutionOnDebuggees(JSContext* cx,
3565 IsObserving observing) {
3566 ExecutionObservableRealms obs(cx);
3567
3568 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3569 r.popFront()) {
3570 GlobalObject* global = r.front();
3571 JS::Realm* realm = global->realm();
3572
3573 if (realm->debuggerObservesAllExecution() == observing) {
3574 continue;
3575 }
3576
3577 // It's expensive to eagerly invalidate and recompile a realm,
3578 // so add the realm to the set only if we are observing.
3579 if (observing && !obs.add(realm)) {
3580 return false;
3581 }
3582 }
3583
3584 if (!updateExecutionObservability(cx, obs, observing)) {
3585 return false;
3586 }
3587
3588 using RealmRange = ExecutionObservableRealms::RealmRange;
3589 for (RealmRange r = obs.realms()->all(); !r.empty(); r.popFront()) {
3590 r.front()->updateDebuggerObservesAllExecution();
3591 }
3592
3593 return true;
3594 }
3595
3596 bool Debugger::updateObservesCoverageOnDebuggees(JSContext* cx,
3597 IsObserving observing) {
3598 ExecutionObservableRealms obs(cx);
3599
3600 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3601 r.popFront()) {
3602 GlobalObject* global = r.front();
3603 Realm* realm = global->realm();
3604
3605 if (realm->debuggerObservesCoverage() == observing) {
3606 continue;
3607 }
3608
3609 // Invalidate and recompile a realm to add or remove PCCounts
3610 // increments. We have to eagerly invalidate, as otherwise we might have
3611 // dangling pointers to freed PCCounts.
3612 if (!obs.add(realm)) {
3613 return false;
3614 }
3615 }
3616
3617 // If any frame on the stack belongs to the debuggee, then we cannot update
3618 // the ScriptCounts, because this would imply to invalidate a Debugger.Frame
3619 // to recompile it with/without ScriptCount support.
3620 for (FrameIter iter(cx); !iter.done(); ++iter) {
3621 if (obs.shouldMarkAsDebuggee(iter)) {
3622 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3623 JSMSG_DEBUG_NOT_IDLE);
3624 return false;
3625 }
3626 }
3627
3628 if (!updateExecutionObservability(cx, obs, observing)) {
3629 return false;
3630 }
3631
3632 // All realms can safely be toggled, and all scripts will be recompiled.
3633 // Thus we can update each realm accordingly.
3634 using RealmRange = ExecutionObservableRealms::RealmRange;
3635 for (RealmRange r = obs.realms()->all(); !r.empty(); r.popFront()) {
3636 r.front()->updateDebuggerObservesCoverage();
3637 }
3638
3639 return true;
3640 }
3641
3642 void Debugger::updateObservesAsmJSOnDebuggees(IsObserving observing) {
3643 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3644 r.popFront()) {
3645 GlobalObject* global = r.front();
3646 Realm* realm = global->realm();
3647
3648 if (realm->debuggerObservesAsmJS() == observing) {
3649 continue;
3650 }
3651
3652 realm->updateDebuggerObservesAsmJS();
3653 }
3654 }
3655
3656 void Debugger::updateObservesWasmOnDebuggees(IsObserving observing) {
3657 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3658 r.popFront()) {
3659 GlobalObject* global = r.front();
3660 Realm* realm = global->realm();
3661
3662 if (realm->debuggerObservesWasm() == observing) {
3663 continue;
3664 }
3665
3666 realm->updateDebuggerObservesWasm();
3667 }
3668 }
3669
3670 void Debugger::updateObservesNativeCallOnDebuggees(IsObserving observing) {
3671 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3672 r.popFront()) {
3673 GlobalObject* global = r.front();
3674 Realm* realm = global->realm();
3675
3676 if (realm->debuggerObservesNativeCall() == observing) {
3677 continue;
3678 }
3679
3680 realm->updateDebuggerObservesNativeCall();
3681 }
3682 }
3683
3684 /*** Allocations Tracking ***************************************************/
3685
3686 /* static */
3687 bool Debugger::cannotTrackAllocations(const GlobalObject& global) {
3688 auto existingCallback = global.realm()->getAllocationMetadataBuilder();
3689 return existingCallback && existingCallback != &SavedStacks::metadataBuilder;
3690 }
3691
3692 /* static */
3693 bool DebugAPI::isObservedByDebuggerTrackingAllocations(
3694 const GlobalObject& debuggee) {
3695 JS::AutoAssertNoGC nogc;
3696 for (Realm::DebuggerVectorEntry& entry : debuggee.getDebuggers(nogc)) {
3697 // Use unbarrieredGet() to prevent triggering read barrier while
3698 // collecting, this is safe as long as dbg does not escape.
3699 Debugger* dbg = entry.dbg.unbarrieredGet();
3700 if (dbg->trackingAllocationSites) {
3701 return true;
3702 }
3703 }
3704
3705 return false;
3706 }
3707
3708 /* static */
3709 bool Debugger::addAllocationsTracking(JSContext* cx,
3710 Handle<GlobalObject*> debuggee) {
3711 // Precondition: the given global object is being observed by at least one
3712 // Debugger that is tracking allocations.
3713 MOZ_ASSERT(DebugAPI::isObservedByDebuggerTrackingAllocations(*debuggee));
3714
3715 if (Debugger::cannotTrackAllocations(*debuggee)) {
3716 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3717 JSMSG_OBJECT_METADATA_CALLBACK_ALREADY_SET);
3718 return false;
3719 }
3720
3721 debuggee->realm()->setAllocationMetadataBuilder(
3722 &SavedStacks::metadataBuilder);
3723 debuggee->realm()->chooseAllocationSamplingProbability();
3724 return true;
3725 }
3726
3727 /* static */
3728 void Debugger::removeAllocationsTracking(GlobalObject& global) {
3729 // If there are still Debuggers that are observing allocations, we cannot
3730 // remove the metadata callback yet. Recompute the sampling probability
3731 // based on the remaining debuggers' needs.
3732 if (DebugAPI::isObservedByDebuggerTrackingAllocations(global)) {
3733 global.realm()->chooseAllocationSamplingProbability();
3734 return;
3735 }
3736
3737 if (!global.realm()->runtimeFromMainThread()->recordAllocationCallback) {
3738 // Something like the Gecko Profiler could request from the the JS runtime
3739 // to record allocations. If it is recording allocations, then do not
3740 // destroy the allocation metadata builder at this time.
3741 global.realm()->forgetAllocationMetadataBuilder();
3742 }
3743 }
3744
3745 bool Debugger::addAllocationsTrackingForAllDebuggees(JSContext* cx) {
3746 MOZ_ASSERT(trackingAllocationSites);
3747
3748 // We don't want to end up in a state where we added allocations
3749 // tracking to some of our debuggees, but failed to do so for
3750 // others. Before attempting to start tracking allocations in *any* of
3751 // our debuggees, ensure that we will be able to track allocations for
3752 // *all* of our debuggees.
3753 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3754 r.popFront()) {
3755 if (Debugger::cannotTrackAllocations(*r.front().get())) {
3756 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
3757 JSMSG_OBJECT_METADATA_CALLBACK_ALREADY_SET);
3758 return false;
3759 }
3760 }
3761
3762 Rooted<GlobalObject*> g(cx);
3763 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3764 r.popFront()) {
3765 // This should always succeed, since we already checked for the
3766 // error case above.
3767 g = r.front().get();
3768 MOZ_ALWAYS_TRUE(Debugger::addAllocationsTracking(cx, g));
3769 }
3770
3771 return true;
3772 }
3773
3774 void Debugger::removeAllocationsTrackingForAllDebuggees() {
3775 for (WeakGlobalObjectSet::Range r = debuggees.all(); !r.empty();
3776 r.popFront()) {
3777 Debugger::removeAllocationsTracking(*r.front().get());
3778 }
3779
3780 allocationsLog.clear();
3781 }
3782
3783 /*** Debugger JSObjects *****************************************************/
3784
3785 template <typename F>
3786 inline void Debugger::forEachWeakMap(const F& f) {
3787 f(generatorFrames);
3788 f(objects);
3789 f(environments);
3790 f(scripts);
3791 f(sources);
3792 f(wasmInstanceScripts);
3793 f(wasmInstanceSources);
3794 }
3795
3796 void Debugger::traceCrossCompartmentEdges(JSTracer* trc) {
3797 forEachWeakMap(
3798 [trc](auto& weakMap) { weakMap.traceCrossCompartmentEdges(trc); });
3799 }
3800
3801 /*
3802 * Ordinarily, WeakMap keys and values are marked because at some point it was
3803 * discovered that the WeakMap was live; that is, some object containing the
3804 * WeakMap was marked during mark phase.
3805 *
3806 * However, during zone GC, we have to do something about cross-compartment
3807 * edges in non-GC'd compartments. Since the source may be live, we
3808 * conservatively assume it is and mark the edge.
3809 *
3810 * Each Debugger object keeps five cross-compartment WeakMaps: objects, scripts,
3811 * lazy scripts, script source objects, and environments. They have the property
3812 * that all their values are in the same compartment as the Debugger object,
3813 * but we have to mark the keys and the private pointer in the wrapper object.
3814 *
3815 * We must scan all Debugger objects regardless of whether they *currently* have
3816 * any debuggees in a compartment being GC'd, because the WeakMap entries
3817 * persist even when debuggees are removed.
3818 *
3819 * This happens during the initial mark phase, not iterative marking, because
3820 * all the edges being reported here are strong references.
3821 *
3822 * This method is also used during compacting GC to update cross compartment
3823 * pointers into zones that are being compacted.
3824 */
3825 /* static */
3826 void DebugAPI::traceCrossCompartmentEdges(JSTracer* trc) {
3827 MOZ_ASSERT(JS::RuntimeHeapIsMajorCollecting());
3828
3829 JSRuntime* rt = trc->runtime();
3830 gc::State state = rt->gc.state();
3831
3832 for (Debugger* dbg : rt->debuggerList()) {
3833 Zone* zone = MaybeForwarded(dbg->object.get())->zone();
3834 if (!zone->isCollecting() || state == gc::State::Compact) {
3835 dbg->traceCrossCompartmentEdges(trc);
3836 }
3837 }
3838 }
3839
3840 #ifdef DEBUG
3841
3842 static bool RuntimeHasDebugger(JSRuntime* rt, Debugger* dbg) {
3843 for (Debugger* d : rt->debuggerList()) {
3844 if (d == dbg) {
3845 return true;
3846 }
3847 }
3848 return false;
3849 }
3850
3851 /* static */
3852 bool DebugAPI::edgeIsInDebuggerWeakmap(JSRuntime* rt, JSObject* src,
3853 JS::GCCellPtr dst) {
3854 if (!Debugger::isChildJSObject(src)) {
3855 return false;
3856 }
3857
3858 if (src->is<DebuggerFrame>()) {
3859 DebuggerFrame* frame = &src->as<DebuggerFrame>();
3860 Debugger* dbg = frame->owner();
3861 MOZ_ASSERT(RuntimeHasDebugger(rt, dbg));
3862
3863 if (dst.is<BaseScript>()) {
3864 // The generatorFrames map is not keyed on the associated JSScript. Get
3865 // the key from the source object and check everything matches.
3866 AbstractGeneratorObject* genObj = &frame->unwrappedGenerator();
3867 return frame->generatorScript() == &dst.as<BaseScript>() &&
3868 dbg->generatorFrames.hasEntry(genObj, src);
3869 }
3870 return dst.is<JSObject>() &&
3871 dst.as<JSObject>().is<AbstractGeneratorObject>() &&
3872 dbg->generatorFrames.hasEntry(
3873 &dst.as<JSObject>().as<AbstractGeneratorObject>(), src);
3874 }
3875 if (src->is<DebuggerObject>()) {
3876 Debugger* dbg = src->as<DebuggerObject>().owner();
3877 MOZ_ASSERT(RuntimeHasDebugger(rt, dbg));
3878 return dst.is<JSObject>() &&
3879 dbg->objects.hasEntry(&dst.as<JSObject>(), src);
3880 }
3881 if (src->is<DebuggerEnvironment>()) {
3882 Debugger* dbg = src->as<DebuggerEnvironment>().owner();
3883 MOZ_ASSERT(RuntimeHasDebugger(rt, dbg));
3884 return dst.is<JSObject>() &&
3885 dbg->environments.hasEntry(&dst.as<JSObject>(), src);
3886 }
3887 if (src->is<DebuggerScript>()) {
3888 Debugger* dbg = src->as<DebuggerScript>().owner();
3889 MOZ_ASSERT(RuntimeHasDebugger(rt, dbg));
3890
3891 return src->as<DebuggerScript>().getReferent().match(
3892 [=](BaseScript* script) {
3893 return dst.is<BaseScript>() && script == &dst.as<BaseScript>() &&
3894 dbg->scripts.hasEntry(script, src);
3895 },
3896 [=](WasmInstanceObject* instance) {
3897 return dst.is<JSObject>() && instance == &dst.as<JSObject>() &&
3898 dbg->wasmInstanceScripts.hasEntry(instance, src);
3899 });
3900 }
3901 if (src->is<DebuggerSource>()) {
3902 Debugger* dbg = src->as<DebuggerSource>().owner();
3903 MOZ_ASSERT(RuntimeHasDebugger(rt, dbg));
3904
3905 return src->as<DebuggerSource>().getReferent().match(
3906 [=](ScriptSourceObject* sso) {
3907 return dst.is<JSObject>() && sso == &dst.as<JSObject>() &&
3908 dbg->sources.hasEntry(sso, src);
3909 },
3910 [=](WasmInstanceObject* instance) {
3911 return dst.is<JSObject>() && instance == &dst.as<JSObject>() &&
3912 dbg->wasmInstanceSources.hasEntry(instance, src);
3913 });
3914 }
3915 MOZ_ASSERT_UNREACHABLE("Unhandled cross-compartment edge");
3916 }
3917
3918 #endif
3919
3920 /* See comments in DebugAPI.h. */
3921 void DebugAPI::traceFramesWithLiveHooks(JSTracer* tracer) {
3922 JSRuntime* rt = tracer->runtime();
3923
3924 // Note that we must loop over all Debuggers here, not just those known to be
3925 // reachable from JavaScript. The existence of hooks set on a Debugger.Frame
3926 // for a live stack frame makes the Debuger.Frame (and hence its Debugger)
3927 // reachable.
3928 for (Debugger* dbg : rt->debuggerList()) {
3929 // Callback tracers set their own traversal boundaries, but otherwise we're
3930 // only interested in Debugger.Frames participating in the collection.
3931 if (!dbg->zone()->isGCMarking() && !tracer->isCallbackTracer()) {
3932 continue;
3933 }
3934
3935 for (Debugger::FrameMap::Range r = dbg->frames.all(); !r.empty();
3936 r.popFront()) {
3937 HeapPtr<DebuggerFrame*>& frameobj = r.front().value();
3938 MOZ_ASSERT(frameobj->isOnStackOrSuspendedWasmStack());
3939 if (frameobj->hasAnyHooks()) {
3940 TraceEdge(tracer, &frameobj, "Debugger.Frame with live hooks");
3941 }
3942 }
3943 }
3944 }
3945
3946 void DebugAPI::slowPathTraceGeneratorFrame(JSTracer* tracer,
3947 AbstractGeneratorObject* generator) {
3948 MOZ_ASSERT(generator->realm()->isDebuggee());
3949
3950 // Ignore generic tracers.
3951 //
3952 // There are two kinds of generic tracers we need to bar: MovingTracers used
3953 // by compacting GC; and CompartmentCheckTracers.
3954 //
3955 // MovingTracers are used by the compacting GC to update pointers to objects
3956 // that have been moved: the MovingTracer checks each outgoing pointer to see
3957 // if it refers to a forwarding pointer, and if so, updates the pointer stored
3958 // in the object.
3959 //
3960 // Generator objects are background finalized, so the compacting GC assumes it
3961 // can update their pointers in the background as well. Since we treat
3962 // generator objects as having an owning edge to their Debugger.Frame objects,
3963 // a helper thread trying to update a generator object will end up calling
3964 // this function. However, it is verboten to do weak map lookups (e.g., in
3965 // Debugger::generatorFrames) off the main thread, since StableCellHasher
3966 // must consult the Zone to find the key's unique id.
3967 //
3968 // Fortunately, it's not necessary for compacting GC to worry about that edge
3969 // in the first place: the edge isn't a literal pointer stored on the
3970 // generator object, it's only inferred from the realm's debuggee status and
3971 // its Debuggers' generatorFrames weak maps. Those get relocated when the
3972 // Debugger itself is visited, so compacting GC can just ignore this edge.
3973 //
3974 // CompartmentCheckTracers walk the graph and verify that all
3975 // cross-compartment edges are recorded in the cross-compartment wrapper
3976 // tables. But edges between Debugger.Foo objects and their referents are not
3977 // in the CCW tables, so a CrossCompartmentCheckTracers also calls
3978 // DebugAPI::edgeIsInDebuggerWeakmap to see if a given cross-compartment edge
3979 // is accounted for there. However, edgeIsInDebuggerWeakmap only handles
3980 // debugger -> debuggee edges, so it won't recognize the edge we're
3981 // potentially traversing here, from a generator object to its Debugger.Frame.
3982 //
3983 // But since the purpose of this function is to retrieve such edges, if they
3984 // exist, from the very tables that edgeIsInDebuggerWeakmap would consult,
3985 // we're at no risk of reporting edges that they do not cover. So we can
3986 // safely hide the edges from CompartmentCheckTracers.
3987 //
3988 // We can't quite recognize MovingTracers and CompartmentCheckTracers
3989 // precisely, but they're both generic tracers, so we just show them all the
3990 // door. This means the generator -> Debugger.Frame edge is going to be
3991 // invisible to some traversals. We'll cope with that when it's a problem.
3992 if (!tracer->isMarkingTracer()) {
3993 return;
3994 }
3995
3996 mozilla::Maybe<AutoLockGC> lock;
3997 GCMarker* marker = GCMarker::fromTracer(tracer);
3998 if (marker->isParallelMarking()) {
3999 // Synchronise access to generatorFrames.
4000 lock.emplace(marker->runtime());
4001 }
4002
4003 JS::AutoAssertNoGC nogc;
4004 for (Realm::DebuggerVectorEntry& entry :
4005 generator->realm()->getDebuggers(nogc)) {
4006 Debugger* dbg = entry.dbg.unbarrieredGet();
4007
4008 if (Debugger::GeneratorWeakMap::Ptr entry =
4009 dbg->generatorFrames.lookupUnbarriered(generator)) {
4010 HeapPtr<DebuggerFrame*>& frameObj = entry->value();
4011 if (frameObj->hasAnyHooks()) {
4012 // See comment above.
4013 TraceCrossCompartmentEdge(tracer, generator, &frameObj,
4014 "Debugger.Frame with hooks for generator");
4015 }
4016 }
4017 }
4018 }
4019
4020 /* static */
4021 void DebugAPI::traceAllForMovingGC(JSTracer* trc) {
4022 JSRuntime* rt = trc->runtime();
4023 for (Debugger* dbg : rt->debuggerList()) {
4024 dbg->traceForMovingGC(trc);
4025 }
4026 }
4027
4028 /*
4029 * Trace all debugger-owned GC things unconditionally. This is used during
4030 * compacting GC and in minor GC: the minor GC cannot apply the weak constraints
4031 * of the full GC because it visits only part of the heap.
4032 */
4033 void Debugger::traceForMovingGC(JSTracer* trc) {
4034 trace(trc);
4035
4036 for (WeakGlobalObjectSet::Enum e(debuggees); !e.empty(); e.popFront()) {
4037 TraceEdge(trc, &e.mutableFront(), "Global Object");
4038 }
4039 }
4040
4041 /* static */
4042 void Debugger::traceObject(JSTracer* trc, JSObject* obj) {
4043 if (Debugger* dbg = Debugger::fromJSObject(obj)) {
4044 dbg->trace(trc);
4045 }
4046 }
4047
4048 void Debugger::trace(JSTracer* trc) {
4049 TraceEdge(trc, &object, "Debugger Object");
4050
4051 TraceNullableEdge(trc, &uncaughtExceptionHook, "hooks");
4052
4053 // Mark Debugger.Frame objects. Since the Debugger is reachable, JS could call
4054 // getNewestFrame and then walk the stack, so these are all reachable from JS.
4055 //
4056 // Note that if a Debugger.Frame has hooks set, it must be retained even if
4057 // its Debugger is unreachable, since JS could observe that its hooks did not
4058 // fire. That case is handled by DebugAPI::traceFrames.
4059 //
4060 // (We have weakly-referenced Debugger.Frame objects as well, for suspended
4061 // generator frames; these are traced via generatorFrames just below.)
4062 for (FrameMap::Range r = frames.all(); !r.empty(); r.popFront()) {
4063 HeapPtr<DebuggerFrame*>& frameobj = r.front().value();
4064 TraceEdge(trc, &frameobj, "live Debugger.Frame");
4065 MOZ_ASSERT(frameobj->isOnStackOrSuspendedWasmStack());
4066 }
4067
4068 allocationsLog.trace(trc);
4069
4070 forEachWeakMap([trc](auto& weakMap) { weakMap.trace(trc); });
4071 }
4072
4073 /* static */
4074 void DebugAPI::traceFromRealm(JSTracer* trc, Realm* realm) {
4075 JS::AutoAssertNoGC nogc;
4076 for (Realm::DebuggerVectorEntry& entry : realm->getDebuggers(nogc)) {
4077 TraceEdge(trc, &entry.debuggerLink, "realm debugger");
4078 }
4079 }
4080
4081 /* static */
4082 void DebugAPI::sweepAll(JS::GCContext* gcx) {
4083 JSRuntime* rt = gcx->runtime();
4084
4085 Debugger* next;
4086 for (Debugger* dbg = rt->debuggerList().getFirst(); dbg; dbg = next) {
4087 next = dbg->getNext();
4088
4089 // Debugger.Frames for generator calls bump the JSScript's
4090 // generatorObserverCount, so the JIT will instrument the code to notify
4091 // Debugger when the generator is resumed. When a Debugger.Frame gets GC'd,
4092 // generatorObserverCount needs to be decremented. It's much easier to do
4093 // this when we know that all parties involved - the Debugger.Frame, the
4094 // generator object, and the JSScript - have not yet been finalized.
4095 //
4096 // Since DebugAPI::sweepAll is called after everything is marked, but before
4097 // anything has been finalized, this is the perfect place to drop the count.
4098 if (dbg->zone()->isGCSweeping()) {
4099 for (Debugger::GeneratorWeakMap::Enum e(dbg->generatorFrames); !e.empty();
4100 e.popFront()) {
4101 DebuggerFrame* frameObj = e.front().value();
4102 if (IsAboutToBeFinalizedUnbarriered(frameObj)) {
4103 // If the DebuggerFrame is being finalized, that means either:
4104 // 1) It is not present in "frames".
4105 // 2) The Debugger itself is also being finalized.
4106 //
4107 // In the first case, passing the frame is not necessary because there
4108 // isn't a frame entry to clear, and in the second case,
4109 // removeDebuggeeGlobal below will iterate and remove the entries
4110 // anyway, so things will be cleaned up properly.
4111 Debugger::terminateDebuggerFrame(gcx, dbg, frameObj, NullFramePtr(),
4112 nullptr, &e);
4113 }
4114 }
4115 }
4116
4117 // Detach dying debuggers and debuggees from each other. Since this
4118 // requires access to both objects it must be done before either
4119 // object is finalized.
4120 bool debuggerDying = IsAboutToBeFinalized(dbg->object);
4121 for (WeakGlobalObjectSet::Enum e(dbg->debuggees); !e.empty();
4122 e.popFront()) {
4123 GlobalObject* global = e.front().unbarrieredGet();
4124 if (debuggerDying || IsAboutToBeFinalizedUnbarriered(global)) {
4125 dbg->removeDebuggeeGlobal(gcx, e.front().unbarrieredGet(), &e,
4126 Debugger::FromSweep::Yes);
4127 }
4128 }
4129
4130 if (debuggerDying) {
4131 gcx->delete_(dbg->object, dbg, MemoryUse::Debugger);
4132 }
4133
4134 dbg = next;
4135 }
4136 }
4137
4138 static inline bool SweepZonesInSameGroup(Zone* a, Zone* b) {
4139 // Ensure two zones are swept in the same sweep group by adding an edge
4140 // between them in each direction.
4141 return a->addSweepGroupEdgeTo(b) && b->addSweepGroupEdgeTo(a);
4142 }
4143
4144 /* static */
4145 bool DebugAPI::findSweepGroupEdges(JSRuntime* rt) {
4146 // Ensure that debuggers and their debuggees are finalized in the same group
4147 // by adding edges in both directions for debuggee zones. These are weak
4148 // references that are not in the cross compartment wrapper map.
4149
4150 for (Debugger* dbg : rt->debuggerList()) {
4151 Zone* debuggerZone = dbg->object->zone();
4152 if (!debuggerZone->isGCMarking()) {
4153 continue;
4154 }
4155
4156 for (auto e = dbg->debuggeeZones.all(); !e.empty(); e.popFront()) {
4157 Zone* debuggeeZone = e.front();
4158 if (!debuggeeZone->isGCMarking()) {
4159 continue;
4160 }
4161
4162 if (!SweepZonesInSameGroup(debuggerZone, debuggeeZone)) {
4163 return false;
4164 }
4165 }
4166 }
4167
4168 return true;
4169 }
4170
4171 template <class UnbarrieredKey, class Wrapper, bool InvisibleKeysOk>
4172 bool DebuggerWeakMap<UnbarrieredKey, Wrapper,
4173 InvisibleKeysOk>::findSweepGroupEdges(Zone* atomsZone) {
4174 Zone* debuggerZone = zone();
4175 MOZ_ASSERT(debuggerZone->isGCMarking());
4176 for (Enum e(*this); !e.empty(); e.popFront()) {
4177 MOZ_ASSERT(e.front().value()->zone() == debuggerZone);
4178
4179 Zone* keyZone = e.front().key()->zone();
4180 if (keyZone->isGCMarking() &&
4181 !SweepZonesInSameGroup(debuggerZone, keyZone)) {
4182 return false;
4183 }
4184 }
4185
4186 // Add in edges for delegates, if relevant for the key type.
4187 return Base::findSweepGroupEdges(atomsZone);
4188 }
4189
4190 const JSClassOps DebuggerInstanceObject::classOps_ = {
4191 nullptr, // addProperty
4192 nullptr, // delProperty
4193 nullptr, // enumerate
4194 nullptr, // newEnumerate
4195 nullptr, // resolve
4196 nullptr, // mayResolve
4197 nullptr, // finalize
4198 nullptr, // call
4199 nullptr, // construct
4200 Debugger::traceObject, // trace
4201 };
4202
4203 const JSClass DebuggerInstanceObject::class_ = {
4204 "Debugger",
4205 JSCLASS_HAS_RESERVED_SLOTS(Debugger::JSSLOT_DEBUG_COUNT),
4206 &classOps_,
4207 };
4208
4209 static_assert(Debugger::JSSLOT_DEBUG_PROTO_START == 0,
4210 "DebuggerPrototypeObject only needs slots for the proto objects");
4211
4212 const JSClass DebuggerPrototypeObject::class_ = {
4213 "DebuggerPrototype",
4214 JSCLASS_HAS_RESERVED_SLOTS(Debugger::JSSLOT_DEBUG_PROTO_STOP),
4215 };
4216
4217 static Debugger* Debugger_fromThisValue(JSContext* cx, const CallArgs& args,
4218 const char* fnname) {
4219 JSObject* thisobj = RequireObject(cx, args.thisv());
4220 if (!thisobj) {
4221 return nullptr;
4222 }
4223 if (!thisobj->is<DebuggerInstanceObject>()) {
4224 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4225 JSMSG_INCOMPATIBLE_PROTO, "Debugger", fnname,
4226 thisobj->getClass()->name);
4227 return nullptr;
4228 }
4229
4230 Debugger* dbg = Debugger::fromJSObject(thisobj);
4231 MOZ_ASSERT(dbg);
4232 return dbg;
4233 }
4234
4235 struct MOZ_STACK_CLASS Debugger::CallData {
4236 JSContext* cx;
4237 const CallArgs& args;
4238
4239 Debugger* dbg;
4240
4241 CallData(JSContext* cx, const CallArgs& args, Debugger* dbg)
4242 : cx(cx), args(args), dbg(dbg) {}
4243
4244 bool getOnDebuggerStatement();
4245 bool setOnDebuggerStatement();
4246 bool getOnExceptionUnwind();
4247 bool setOnExceptionUnwind();
4248 bool getOnNewScript();
4249 bool setOnNewScript();
4250 bool getOnEnterFrame();
4251 bool setOnEnterFrame();
4252 bool getOnNativeCall();
4253 bool setOnNativeCall();
4254 bool getShouldAvoidSideEffects();
4255 bool setShouldAvoidSideEffects();
4256 bool getOnNewGlobalObject();
4257 bool setOnNewGlobalObject();
4258 bool getOnNewPromise();
4259 bool setOnNewPromise();
4260 bool getOnPromiseSettled();
4261 bool setOnPromiseSettled();
4262 bool getUncaughtExceptionHook();
4263 bool setUncaughtExceptionHook();
4264 bool getAllowUnobservedAsmJS();
4265 bool setAllowUnobservedAsmJS();
4266 bool getAllowUnobservedWasm();
4267 bool setAllowUnobservedWasm();
4268 bool getExclusiveDebuggerOnEval();
4269 bool setExclusiveDebuggerOnEval();
4270 bool getInspectNativeCallArguments();
4271 bool setInspectNativeCallArguments();
4272 bool getCollectCoverageInfo();
4273 bool setCollectCoverageInfo();
4274 bool getMemory();
4275 bool addDebuggee();
4276 bool addAllGlobalsAsDebuggees();
4277 bool removeDebuggee();
4278 bool removeAllDebuggees();
4279 bool hasDebuggee();
4280 bool getDebuggees();
4281 bool getNewestFrame();
4282 bool clearAllBreakpoints();
4283 bool findScripts();
4284 bool findSources();
4285 bool findObjects();
4286 bool findAllGlobals();
4287 bool findSourceURLs();
4288 bool makeGlobalObjectReference();
4289 bool adoptDebuggeeValue();
4290 bool adoptFrame();
4291 bool adoptSource();
4292 bool enableAsyncStack();
4293 bool disableAsyncStack();
4294 bool enableUnlimitedStacksCapturing();
4295 bool disableUnlimitedStacksCapturing();
4296
4297 using Method = bool (CallData::*)();
4298
4299 template <Method MyMethod>
4300 static bool ToNative(JSContext* cx, unsigned argc, Value* vp);
4301 };
4302
4303 template <Debugger::CallData::Method MyMethod>
4304 /* static */
4305 bool Debugger::CallData::ToNative(JSContext* cx, unsigned argc, Value* vp) {
4306 CallArgs args = CallArgsFromVp(argc, vp);
4307
4308 Debugger* dbg = Debugger_fromThisValue(cx, args, "method");
4309 if (!dbg) {
4310 return false;
4311 }
4312
4313 CallData data(cx, args, dbg);
4314 return (data.*MyMethod)();
4315 }
4316
4317 /* static */
4318 bool Debugger::getHookImpl(JSContext* cx, const CallArgs& args, Debugger& dbg,
4319 Hook which) {
4320 MOZ_ASSERT(which >= 0 && which < HookCount);
4321 args.rval().set(dbg.object->getReservedSlot(
4322 JSSLOT_DEBUG_HOOK_START + std::underlying_type_t<Hook>(which)));
4323 return true;
4324 }
4325
4326 /* static */
4327 bool Debugger::setHookImpl(JSContext* cx, const CallArgs& args, Debugger& dbg,
4328 Hook which) {
4329 MOZ_ASSERT(which >= 0 && which < HookCount);
4330 if (!args.requireAtLeast(cx, "Debugger.setHook", 1)) {
4331 return false;
4332 }
4333 if (args[0].isObject()) {
4334 if (!args[0].toObject().isCallable()) {
4335 return ReportIsNotFunction(cx, args[0], args.length() - 1);
4336 }
4337 } else if (!args[0].isUndefined()) {
4338 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4339 JSMSG_NOT_CALLABLE_OR_UNDEFINED);
4340 return false;
4341 }
4342
4343 // Disallow simultaneous activation of OnEnterFrame and code coverage support;
4344 // as they both use the execution observer flag. See Bug 1608891.
4345 if (dbg.collectCoverageInfo && which == Hook::OnEnterFrame) {
4346 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4347 JSMSG_DEBUG_EXCLUSIVE_FRAME_COVERAGE);
4348 return false;
4349 }
4350
4351 uint32_t slot = JSSLOT_DEBUG_HOOK_START + std::underlying_type_t<Hook>(which);
4352 RootedValue oldHook(cx, dbg.object->getReservedSlot(slot));
4353 dbg.object->setReservedSlot(slot, args[0]);
4354 if (hookObservesAllExecution(which)) {
4355 if (!dbg.updateObservesAllExecutionOnDebuggees(
4356 cx, dbg.observesAllExecution())) {
4357 dbg.object->setReservedSlot(slot, oldHook);
4358 return false;
4359 }
4360 }
4361
4362 Rooted<DebuggerDebuggeeLink*> debuggeeLink(cx, dbg.getDebuggeeLink());
4363 if (dbg.hasAnyLiveHooks()) {
4364 debuggeeLink->setLinkSlot(dbg);
4365 } else {
4366 debuggeeLink->clearLinkSlot();
4367 }
4368
4369 args.rval().setUndefined();
4370 return true;
4371 }
4372
4373 /* static */
4374 bool Debugger::getGarbageCollectionHook(JSContext* cx, const CallArgs& args,
4375 Debugger& dbg) {
4376 return getHookImpl(cx, args, dbg, OnGarbageCollection);
4377 }
4378
4379 /* static */
4380 bool Debugger::setGarbageCollectionHook(JSContext* cx, const CallArgs& args,
4381 Debugger& dbg) {
4382 Rooted<JSObject*> oldHook(cx, dbg.getHook(OnGarbageCollection));
4383
4384 if (!setHookImpl(cx, args, dbg, OnGarbageCollection)) {
4385 // We want to maintain the invariant that the hook is always set when the
4386 // Debugger is in the runtime's list, and vice-versa, so if we return early
4387 // and don't adjust the watcher list below, we need to be sure that the
4388 // hook didn't change.
4389 MOZ_ASSERT(dbg.getHook(OnGarbageCollection) == oldHook);
4390 return false;
4391 }
4392
4393 // Add or remove ourselves from the runtime's list of Debuggers that care
4394 // about garbage collection.
4395 JSObject* newHook = dbg.getHook(OnGarbageCollection);
4396 if (!oldHook && newHook) {
4397 cx->runtime()->onGarbageCollectionWatchers().pushBack(&dbg);
4398 } else if (oldHook && !newHook) {
4399 cx->runtime()->onGarbageCollectionWatchers().remove(&dbg);
4400 }
4401
4402 return true;
4403 }
4404
4405 bool Debugger::CallData::getOnDebuggerStatement() {
4406 return getHookImpl(cx, args, *dbg, OnDebuggerStatement);
4407 }
4408
4409 bool Debugger::CallData::setOnDebuggerStatement() {
4410 return setHookImpl(cx, args, *dbg, OnDebuggerStatement);
4411 }
4412
4413 bool Debugger::CallData::getOnExceptionUnwind() {
4414 return getHookImpl(cx, args, *dbg, OnExceptionUnwind);
4415 }
4416
4417 bool Debugger::CallData::setOnExceptionUnwind() {
4418 return setHookImpl(cx, args, *dbg, OnExceptionUnwind);
4419 }
4420
4421 bool Debugger::CallData::getOnNewScript() {
4422 return getHookImpl(cx, args, *dbg, OnNewScript);
4423 }
4424
4425 bool Debugger::CallData::setOnNewScript() {
4426 return setHookImpl(cx, args, *dbg, OnNewScript);
4427 }
4428
4429 bool Debugger::CallData::getOnNewPromise() {
4430 return getHookImpl(cx, args, *dbg, OnNewPromise);
4431 }
4432
4433 bool Debugger::CallData::setOnNewPromise() {
4434 return setHookImpl(cx, args, *dbg, OnNewPromise);
4435 }
4436
4437 bool Debugger::CallData::getOnPromiseSettled() {
4438 return getHookImpl(cx, args, *dbg, OnPromiseSettled);
4439 }
4440
4441 bool Debugger::CallData::setOnPromiseSettled() {
4442 return setHookImpl(cx, args, *dbg, OnPromiseSettled);
4443 }
4444
4445 bool Debugger::CallData::getOnEnterFrame() {
4446 return getHookImpl(cx, args, *dbg, OnEnterFrame);
4447 }
4448
4449 bool Debugger::CallData::setOnEnterFrame() {
4450 return setHookImpl(cx, args, *dbg, OnEnterFrame);
4451 }
4452
4453 bool Debugger::CallData::getOnNativeCall() {
4454 return getHookImpl(cx, args, *dbg, OnNativeCall);
4455 }
4456
4457 bool Debugger::CallData::setOnNativeCall() {
4458 RootedObject oldHook(cx, dbg->getHook(OnNativeCall));
4459
4460 if (!setHookImpl(cx, args, *dbg, OnNativeCall)) {
4461 return false;
4462 }
4463
4464 JSObject* newHook = dbg->getHook(OnNativeCall);
4465 if (!oldHook && newHook) {
4466 dbg->updateObservesNativeCallOnDebuggees(Observing);
4467 } else if (oldHook && !newHook) {
4468 dbg->updateObservesNativeCallOnDebuggees(NotObserving);
4469 }
4470
4471 return true;
4472 }
4473
4474 bool Debugger::CallData::getShouldAvoidSideEffects() {
4475 args.rval().setBoolean(dbg->shouldAvoidSideEffects);
4476 return true;
4477 }
4478
4479 bool Debugger::CallData::setShouldAvoidSideEffects() {
4480 if (!args.requireAtLeast(cx, "Debugger.set shouldAvoidSideEffects", 1)) {
4481 return false;
4482 }
4483
4484 dbg->shouldAvoidSideEffects = ToBoolean(args[0]);
4485
4486 args.rval().setUndefined();
4487 return true;
4488 }
4489
4490 bool Debugger::CallData::getOnNewGlobalObject() {
4491 return getHookImpl(cx, args, *dbg, OnNewGlobalObject);
4492 }
4493
4494 bool Debugger::CallData::setOnNewGlobalObject() {
4495 RootedObject oldHook(cx, dbg->getHook(OnNewGlobalObject));
4496
4497 if (!setHookImpl(cx, args, *dbg, OnNewGlobalObject)) {
4498 return false;
4499 }
4500
4501 // Add or remove ourselves from the runtime's list of Debuggers that care
4502 // about new globals.
4503 JSObject* newHook = dbg->getHook(OnNewGlobalObject);
4504 if (!oldHook && newHook) {
4505 cx->runtime()->onNewGlobalObjectWatchers().pushBack(dbg);
4506 } else if (oldHook && !newHook) {
4507 cx->runtime()->onNewGlobalObjectWatchers().remove(dbg);
4508 }
4509
4510 return true;
4511 }
4512
4513 bool Debugger::CallData::getUncaughtExceptionHook() {
4514 args.rval().setObjectOrNull(dbg->uncaughtExceptionHook);
4515 return true;
4516 }
4517
4518 bool Debugger::CallData::setUncaughtExceptionHook() {
4519 if (!args.requireAtLeast(cx, "Debugger.set uncaughtExceptionHook", 1)) {
4520 return false;
4521 }
4522 if (!args[0].isNull() &&
4523 (!args[0].isObject() || !args[0].toObject().isCallable())) {
4524 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4525 JSMSG_ASSIGN_FUNCTION_OR_NULL,
4526 "uncaughtExceptionHook");
4527 return false;
4528 }
4529 dbg->uncaughtExceptionHook = args[0].toObjectOrNull();
4530 args.rval().setUndefined();
4531 return true;
4532 }
4533
4534 bool Debugger::CallData::getAllowUnobservedAsmJS() {
4535 args.rval().setBoolean(dbg->allowUnobservedAsmJS);
4536 return true;
4537 }
4538
4539 bool Debugger::CallData::setAllowUnobservedAsmJS() {
4540 if (!args.requireAtLeast(cx, "Debugger.set allowUnobservedAsmJS", 1)) {
4541 return false;
4542 }
4543 dbg->allowUnobservedAsmJS = ToBoolean(args[0]);
4544
4545 for (WeakGlobalObjectSet::Range r = dbg->debuggees.all(); !r.empty();
4546 r.popFront()) {
4547 GlobalObject* global = r.front();
4548 Realm* realm = global->realm();
4549 realm->updateDebuggerObservesAsmJS();
4550 }
4551
4552 args.rval().setUndefined();
4553 return true;
4554 }
4555
4556 bool Debugger::CallData::getAllowUnobservedWasm() {
4557 args.rval().setBoolean(dbg->allowUnobservedWasm);
4558 return true;
4559 }
4560
4561 bool Debugger::CallData::setAllowUnobservedWasm() {
4562 if (!args.requireAtLeast(cx, "Debugger.set allowUnobservedWasm", 1)) {
4563 return false;
4564 }
4565 dbg->allowUnobservedWasm = ToBoolean(args[0]);
4566
4567 for (WeakGlobalObjectSet::Range r = dbg->debuggees.all(); !r.empty();
4568 r.popFront()) {
4569 GlobalObject* global = r.front();
4570 Realm* realm = global->realm();
4571 realm->updateDebuggerObservesWasm();
4572 }
4573
4574 args.rval().setUndefined();
4575 return true;
4576 }
4577
4578 bool Debugger::CallData::getExclusiveDebuggerOnEval() {
4579 args.rval().setBoolean(dbg->exclusiveDebuggerOnEval);
4580 return true;
4581 }
4582
4583 bool Debugger::CallData::setExclusiveDebuggerOnEval() {
4584 if (!args.requireAtLeast(cx, "Debugger.set exclusiveDebuggerOnEval", 1)) {
4585 return false;
4586 }
4587 dbg->exclusiveDebuggerOnEval = ToBoolean(args[0]);
4588
4589 args.rval().setUndefined();
4590 return true;
4591 }
4592
4593 bool Debugger::CallData::getInspectNativeCallArguments() {
4594 args.rval().setBoolean(dbg->inspectNativeCallArguments);
4595 return true;
4596 }
4597
4598 bool Debugger::CallData::setInspectNativeCallArguments() {
4599 if (!args.requireAtLeast(cx, "Debugger.set inspectNativeCallArguments", 1)) {
4600 return false;
4601 }
4602 dbg->inspectNativeCallArguments = ToBoolean(args[0]);
4603
4604 args.rval().setUndefined();
4605 return true;
4606 }
4607
4608 bool Debugger::CallData::getCollectCoverageInfo() {
4609 args.rval().setBoolean(dbg->collectCoverageInfo);
4610 return true;
4611 }
4612
4613 bool Debugger::CallData::setCollectCoverageInfo() {
4614 if (!args.requireAtLeast(cx, "Debugger.set collectCoverageInfo", 1)) {
4615 return false;
4616 }
4617
4618 // Disallow simultaneous activation of OnEnterFrame and code coverage support;
4619 // as they both use the execution observer flag. See Bug 1608891.
4620 uint32_t slot = JSSLOT_DEBUG_HOOK_START +
4621 std::underlying_type_t<Hook>(Hook::OnEnterFrame);
4622 if (!dbg->object->getReservedSlot(slot).isUndefined()) {
4623 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4624 JSMSG_DEBUG_EXCLUSIVE_FRAME_COVERAGE);
4625 return false;
4626 }
4627
4628 if (cx->realm()->isTracingExecution()) {
4629 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4630 JSMSG_DEBUG_EXCLUSIVE_EXECUTION_TRACE_COVERAGE);
4631 return false;
4632 }
4633
4634 dbg->collectCoverageInfo = ToBoolean(args[0]);
4635
4636 IsObserving observing = dbg->collectCoverageInfo ? Observing : NotObserving;
4637 if (!dbg->updateObservesCoverageOnDebuggees(cx, observing)) {
4638 return false;
4639 }
4640
4641 args.rval().setUndefined();
4642 return true;
4643 }
4644
4645 bool Debugger::CallData::getMemory() {
4646 Value memoryValue =
4647 dbg->object->getReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE);
4648
4649 if (!memoryValue.isObject()) {
4650 RootedObject memory(cx, DebuggerMemory::create(cx, dbg));
4651 if (!memory) {
4652 return false;
4653 }
4654 memoryValue = ObjectValue(*memory);
4655 }
4656
4657 args.rval().set(memoryValue);
4658 return true;
4659 }
4660
4661 /*
4662 * Given a value used to designate a global (there's quite a variety; see the
4663 * docs), return the actual designee.
4664 *
4665 * Note that this does not check whether the designee is marked "invisible to
4666 * Debugger" or not; different callers need to handle invisible-to-Debugger
4667 * globals in different ways.
4668 */
4669 GlobalObject* Debugger::unwrapDebuggeeArgument(JSContext* cx, const Value& v) {
4670 if (!v.isObject()) {
4671 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4672 JSMSG_UNEXPECTED_TYPE, "argument",
4673 "not a global object");
4674 return nullptr;
4675 }
4676
4677 RootedObject obj(cx, &v.toObject());
4678
4679 // If it's a Debugger.Object belonging to this debugger, dereference that.
4680 if (obj->getClass() == &DebuggerObject::class_) {
4681 RootedValue rv(cx, v);
4682 if (!unwrapDebuggeeValue(cx, &rv)) {
4683 return nullptr;
4684 }
4685 obj = &rv.toObject();
4686 }
4687
4688 // If we have a cross-compartment wrapper, dereference as far as is secure.
4689 //
4690 // Since we're dealing with globals, we may have a WindowProxy here. So we
4691 // have to make sure to do a dynamic unwrap, and we want to unwrap the
4692 // WindowProxy too, if we have one.
4693 obj = CheckedUnwrapDynamic(obj, cx, /* stopAtWindowProxy = */ false);
4694 if (!obj) {
4695 ReportAccessDenied(cx);
4696 return nullptr;
4697 }
4698
4699 if (JS_IsDeadWrapper(obj)) {
4700 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEAD_OBJECT);
4701 return nullptr;
4702 }
4703
4704 // If that didn't produce a global object, it's an error.
4705 if (!obj->is<GlobalObject>()) {
4706 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4707 JSMSG_UNEXPECTED_TYPE, "argument",
4708 "not a global object");
4709 return nullptr;
4710 }
4711
4712 return &obj->as<GlobalObject>();
4713 }
4714
4715 bool Debugger::CallData::addDebuggee() {
4716 if (!args.requireAtLeast(cx, "Debugger.addDebuggee", 1)) {
4717 return false;
4718 }
4719 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
4720 if (!global) {
4721 return false;
4722 }
4723
4724 if (!dbg->addDebuggeeGlobal(cx, global)) {
4725 return false;
4726 }
4727
4728 RootedValue v(cx, ObjectValue(*global));
4729 if (!dbg->wrapDebuggeeValue(cx, &v)) {
4730 return false;
4731 }
4732 args.rval().set(v);
4733 return true;
4734 }
4735
4736 bool Debugger::CallData::addAllGlobalsAsDebuggees() {
4737 for (CompartmentsIter comp(cx->runtime()); !comp.done(); comp.next()) {
4738 if (comp == dbg->object->compartment()) {
4739 continue;
4740 }
4741 for (RealmsInCompartmentIter r(comp); !r.done(); r.next()) {
4742 if (r->creationOptions().invisibleToDebugger()) {
4743 continue;
4744 }
4745 if (!r->hasInitializedGlobal()) {
4746 continue;
4747 }
4748 r->compartment()->gcState.scheduledForDestruction = false;
4749 Rooted<GlobalObject*> global(cx, r->maybeGlobal());
4750 MOZ_ASSERT(global);
4751 if (!dbg->addDebuggeeGlobal(cx, global)) {
4752 return false;
4753 }
4754 }
4755 }
4756
4757 args.rval().setUndefined();
4758 return true;
4759 }
4760
4761 bool Debugger::CallData::removeDebuggee() {
4762 if (!args.requireAtLeast(cx, "Debugger.removeDebuggee", 1)) {
4763 return false;
4764 }
4765 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
4766 if (!global) {
4767 return false;
4768 }
4769
4770 ExecutionObservableRealms obs(cx);
4771
4772 if (dbg->debuggees.has(global)) {
4773 dbg->removeDebuggeeGlobal(cx->gcContext(), global, nullptr, FromSweep::No);
4774
4775 // Only update the realm if there are no Debuggers left, as it's
4776 // expensive to check if no other Debugger has a live script or frame
4777 // hook on any of the current on-stack debuggee frames.
4778 if (!global->hasDebuggers() && !obs.add(global->realm())) {
4779 return false;
4780 }
4781 if (!updateExecutionObservability(cx, obs, NotObserving)) {
4782 return false;
4783 }
4784 }
4785
4786 args.rval().setUndefined();
4787 return true;
4788 }
4789
4790 bool Debugger::CallData::removeAllDebuggees() {
4791 ExecutionObservableRealms obs(cx);
4792
4793 for (WeakGlobalObjectSet::Enum e(dbg->debuggees); !e.empty(); e.popFront()) {
4794 Rooted<GlobalObject*> global(cx, e.front());
4795 dbg->removeDebuggeeGlobal(cx->gcContext(), global, &e, FromSweep::No);
4796
4797 // See note about adding to the observable set in removeDebuggee.
4798 if (!global->hasDebuggers() && !obs.add(global->realm())) {
4799 return false;
4800 }
4801 }
4802
4803 if (!updateExecutionObservability(cx, obs, NotObserving)) {
4804 return false;
4805 }
4806
4807 args.rval().setUndefined();
4808 return true;
4809 }
4810
4811 bool Debugger::CallData::hasDebuggee() {
4812 if (!args.requireAtLeast(cx, "Debugger.hasDebuggee", 1)) {
4813 return false;
4814 }
4815 GlobalObject* global = dbg->unwrapDebuggeeArgument(cx, args[0]);
4816 if (!global) {
4817 return false;
4818 }
4819 args.rval().setBoolean(!!dbg->debuggees.lookup(global));
4820 return true;
4821 }
4822
4823 bool Debugger::CallData::getDebuggees() {
4824 // Obtain the list of debuggees before wrapping each debuggee, as a GC could
4825 // update the debuggees set while we are iterating it.
4826 unsigned count = dbg->debuggees.count();
4827 RootedValueVector debuggees(cx);
4828 if (!debuggees.resize(count)) {
4829 return false;
4830 }
4831 unsigned i = 0;
4832 {
4833 JS::AutoCheckCannotGC nogc;
4834 for (WeakGlobalObjectSet::Enum e(dbg->debuggees); !e.empty();
4835 e.popFront()) {
4836 debuggees[i++].setObject(*e.front().get());
4837 }
4838 }
4839
4840 Rooted<ArrayObject*> arrobj(cx, NewDenseFullyAllocatedArray(cx, count));
4841 if (!arrobj) {
4842 return false;
4843 }
4844 arrobj->ensureDenseInitializedLength(0, count);
4845 for (i = 0; i < count; i++) {
4846 RootedValue v(cx, debuggees[i]);
4847 if (!dbg->wrapDebuggeeValue(cx, &v)) {
4848 return false;
4849 }
4850 arrobj->setDenseElement(i, v);
4851 }
4852
4853 args.rval().setObject(*arrobj);
4854 return true;
4855 }
4856
4857 bool Debugger::CallData::getNewestFrame() {
4858 // Since there may be multiple contexts, use AllFramesIter.
4859 for (AllFramesIter i(cx); !i.done(); ++i) {
4860 if (dbg->observesFrame(i)) {
4861 // Ensure that Ion frames are rematerialized. Only rematerialized
4862 // Ion frames may be used as AbstractFramePtrs.
4863 if (i.isIon() && !i.ensureHasRematerializedFrame(cx)) {
4864 return false;
4865 }
4866 AbstractFramePtr frame = i.abstractFramePtr();
4867 FrameIter iter(i.activation()->cx());
4868 while (!iter.hasUsableAbstractFramePtr() ||
4869 iter.abstractFramePtr() != frame) {
4870 ++iter;
4871 }
4872 return dbg->getFrame(cx, iter, args.rval());
4873 }
4874 }
4875 args.rval().setNull();
4876 return true;
4877 }
4878
4879 bool Debugger::CallData::clearAllBreakpoints() {
4880 JS::GCContext* gcx = cx->gcContext();
4881 Breakpoint* nextbp;
4882 for (Breakpoint* bp = dbg->firstBreakpoint(); bp; bp = nextbp) {
4883 nextbp = bp->nextInDebugger();
4884
4885 bp->remove(gcx);
4886 }
4887 MOZ_ASSERT(!dbg->firstBreakpoint());
4888
4889 return true;
4890 }
4891
4892 /* static */
4893 bool Debugger::construct(JSContext* cx, unsigned argc, Value* vp) {
4894 CallArgs args = CallArgsFromVp(argc, vp);
4895
4896 // Check that the arguments, if any, are cross-compartment wrappers.
4897 for (unsigned i = 0; i < args.length(); i++) {
4898 JSObject* argobj = RequireObject(cx, args[i]);
4899 if (!argobj) {
4900 return false;
4901 }
4902 if (!argobj->is<CrossCompartmentWrapperObject>()) {
4903 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4904 JSMSG_DEBUG_CCW_REQUIRED, "Debugger");
4905 return false;
4906 }
4907 }
4908
4909 // Get Debugger.prototype.
4910 RootedValue v(cx);
4911 RootedObject callee(cx, &args.callee());
4912 if (!GetProperty(cx, callee, callee, cx->names().prototype, &v)) {
4913 return false;
4914 }
4915 Rooted<NativeObject*> proto(cx, &v.toObject().as<NativeObject>());
4916 MOZ_ASSERT(proto->is<DebuggerPrototypeObject>());
4917
4918 // Make the new Debugger object. Each one has a reference to
4919 // Debugger.{Frame,Object,Script,Memory}.prototype in reserved slots. The
4920 // rest of the reserved slots are for hooks; they default to undefined.
4921 Rooted<DebuggerInstanceObject*> obj(
4922 cx, NewTenuredObjectWithGivenProto<DebuggerInstanceObject>(cx, proto));
4923 if (!obj) {
4924 return false;
4925 }
4926 for (unsigned slot = JSSLOT_DEBUG_PROTO_START; slot < JSSLOT_DEBUG_PROTO_STOP;
4927 slot++) {
4928 obj->setReservedSlot(slot, proto->getReservedSlot(slot));
4929 }
4930 obj->setReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE, NullValue());
4931
4932 Rooted<NativeObject*> livenessLink(
4933 cx, NewObjectWithGivenProto<DebuggerDebuggeeLink>(cx, nullptr));
4934 if (!livenessLink) {
4935 return false;
4936 }
4937 obj->setReservedSlot(JSSLOT_DEBUG_DEBUGGEE_LINK, ObjectValue(*livenessLink));
4938
4939 Debugger* debugger;
4940 {
4941 // Construct the underlying C++ object.
4942 auto dbg = cx->make_unique<Debugger>(cx, obj.get());
4943 if (!dbg) {
4944 return false;
4945 }
4946
4947 // The object owns the released pointer.
4948 debugger = dbg.release();
4949 InitReservedSlot(obj, JSSLOT_DEBUG_DEBUGGER, debugger, MemoryUse::Debugger);
4950 }
4951
4952 // Add the initial debuggees, if any.
4953 for (unsigned i = 0; i < args.length(); i++) {
4954 JSObject& wrappedObj =
4955 args[i].toObject().as<ProxyObject>().private_().toObject();
4956 Rooted<GlobalObject*> debuggee(cx, &wrappedObj.nonCCWGlobal());
4957 if (!debugger->addDebuggeeGlobal(cx, debuggee)) {
4958 return false;
4959 }
4960 }
4961
4962 args.rval().setObject(*obj);
4963 return true;
4964 }
4965
4966 bool Debugger::addDebuggeeGlobal(JSContext* cx, Handle<GlobalObject*> global) {
4967 if (debuggees.has(global)) {
4968 return true;
4969 }
4970
4971 // Callers should generally be unable to get a reference to a debugger-
4972 // invisible global in order to pass it to addDebuggee. But this is possible
4973 // with certain testing aides we expose in the shell, so just make addDebuggee
4974 // throw in that case.
4975 Realm* debuggeeRealm = global->realm();
4976 if (debuggeeRealm->creationOptions().invisibleToDebugger()) {
4977 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4978 JSMSG_DEBUG_CANT_DEBUG_GLOBAL);
4979 return false;
4980 }
4981
4982 // Debugger and debuggee must be in different compartments.
4983 if (debuggeeRealm->compartment() == object->compartment()) {
4984 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
4985 JSMSG_DEBUG_SAME_COMPARTMENT);
4986 return false;
4987 }
4988
4989 // Check for cycles. If global's realm is reachable from this Debugger
4990 // object's realm by following debuggee-to-debugger links, then adding
4991 // global would create a cycle. (Typically nobody is debugging the
4992 // debugger, in which case we zip through this code without looping.)
4993 Vector<Realm*> visited(cx);
4994 if (!visited.append(object->realm())) {
4995 return false;
4996 }
4997 for (size_t i = 0; i < visited.length(); i++) {
4998 Realm* realm = visited[i];
4999 if (realm == debuggeeRealm) {
5000 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_DEBUG_LOOP);
5001 return false;
5002 }
5003
5004 // Find all realms containing debuggers debugging realm's global object.
5005 // Add those realms to visited.
5006 if (realm->isDebuggee()) {
5007 JS::AutoAssertNoGC nogc;
5008 for (Realm::DebuggerVectorEntry& entry : realm->getDebuggers(nogc)) {
5009 Realm* next = entry.dbg->object->realm();
5010 if (std::find(visited.begin(), visited.end(), next) == visited.end()) {
5011 if (!visited.append(next)) {
5012 return false;
5013 }
5014 }
5015 }
5016 }
5017 }
5018
5019 // For global to become this js::Debugger's debuggee:
5020 //
5021 // 1. this js::Debugger must be in global->getDebuggers(),
5022 // 2. global must be in this->debuggees,
5023 // 3. the debuggee's zone must be in this->debuggeeZones,
5024 // 4. if we are tracking allocations, the SavedStacksMetadataBuilder must be
5025 // installed for this realm, and
5026 // 5. Realm::isDebuggee()'s bit must be set.
5027 //
5028 // All five indications must be kept consistent.
5029
5030 AutoRealm ar(cx, global);
5031 Zone* zone = global->zone();
5032
5033 RootedObject debuggeeLink(cx, getDebuggeeLink());
5034 if (!cx->compartment()->wrap(cx, &debuggeeLink)) {
5035 return false;
5036 }
5037
5038 // (1)
5039 JS::AutoAssertNoGC nogc;
5040 auto& globalDebuggers = global->getDebuggers(nogc);
5041 if (!globalDebuggers.append(Realm::DebuggerVectorEntry(this, debuggeeLink))) {
5042 ReportOutOfMemory(cx);
5043 return false;
5044 }
5045 auto globalDebuggersGuard = MakeScopeExit([&] { globalDebuggers.popBack(); });
5046
5047 // (2)
5048 if (!debuggees.put(global)) {
5049 ReportOutOfMemory(cx);
5050 return false;
5051 }
5052 auto debuggeesGuard = MakeScopeExit([&] { debuggees.remove(global); });
5053
5054 bool addingZoneRelation = !debuggeeZones.has(zone);
5055
5056 // (3)
5057 if (addingZoneRelation && !debuggeeZones.put(zone)) {
5058 ReportOutOfMemory(cx);
5059 return false;
5060 }
5061 auto debuggeeZonesGuard = MakeScopeExit([&] {
5062 if (addingZoneRelation) {
5063 debuggeeZones.remove(zone);
5064 }
5065 });
5066
5067 // (4)
5068 if (trackingAllocationSites &&
5069 !Debugger::addAllocationsTracking(cx, global)) {
5070 return false;
5071 }
5072
5073 auto allocationsTrackingGuard = MakeScopeExit([&] {
5074 if (trackingAllocationSites) {
5075 Debugger::removeAllocationsTracking(*global);
5076 }
5077 });
5078
5079 // (5)
5080 AutoRestoreRealmDebugMode debugModeGuard(debuggeeRealm);
5081 debuggeeRealm->setIsDebuggee();
5082 debuggeeRealm->updateDebuggerObservesAsmJS();
5083 debuggeeRealm->updateDebuggerObservesWasm();
5084 debuggeeRealm->updateDebuggerObservesCoverage();
5085 if (observesAllExecution() &&
5086 !ensureExecutionObservabilityOfRealm(cx, debuggeeRealm)) {
5087 return false;
5088 }
5089
5090 globalDebuggersGuard.release();
5091 debuggeesGuard.release();
5092 debuggeeZonesGuard.release();
5093 allocationsTrackingGuard.release();
5094 debugModeGuard.release();
5095 return true;
5096 }
5097
5098 void Debugger::recomputeDebuggeeZoneSet() {
5099 AutoEnterOOMUnsafeRegion oomUnsafe;
5100 debuggeeZones.clear();
5101 for (auto range = debuggees.all(); !range.empty(); range.popFront()) {
5102 if (!debuggeeZones.put(range.front().unbarrieredGet()->zone())) {
5103 oomUnsafe.crash("Debugger::removeDebuggeeGlobal");
5104 }
5105 }
5106 }
5107
5108 template <typename T, typename AP>
5109 static T* findDebuggerInVector(Debugger* dbg, Vector<T, 0, AP>* vec) {
5110 T* p;
5111 for (p = vec->begin(); p != vec->end(); p++) {
5112 if (p->dbg == dbg) {
5113 break;
5114 }
5115 }
5116 MOZ_ASSERT(p != vec->end());
5117 return p;
5118 }
5119
5120 void Debugger::removeDebuggeeGlobal(JS::GCContext* gcx, GlobalObject* global,
5121 WeakGlobalObjectSet::Enum* debugEnum,
5122 FromSweep fromSweep) {
5123 // The caller might have found global by enumerating this->debuggees; if
5124 // so, use HashSet::Enum::removeFront rather than HashSet::remove below,
5125 // to avoid invalidating the live enumerator.
5126 MOZ_ASSERT(debuggees.has(global));
5127 MOZ_ASSERT(debuggeeZones.has(global->zone()));
5128 MOZ_ASSERT_IF(debugEnum, debugEnum->front().unbarrieredGet() == global);
5129
5130 // Clear this global's generators from generatorFrames as well.
5131 //
5132 // This method can be called either from script (dbg.removeDebuggee) or during
5133 // GC sweeping, because the Debugger, debuggee global, or both are being GC'd.
5134 //
5135 // When called from script, it's okay to iterate over generatorFrames and
5136 // touch its keys and values (even when an incremental GC is in progress).
5137 // When called from GC, it's not okay; the keys and values may be dying. But
5138 // in that case, we can actually just skip the loop entirely! If the Debugger
5139 // is going away, it doesn't care about the state of its generatorFrames
5140 // table, and the Debugger.Frame finalizer will fix up the generator observer
5141 // counts.
5142 if (fromSweep == FromSweep::No) {
5143 for (GeneratorWeakMap::Enum e(generatorFrames); !e.empty(); e.popFront()) {
5144 AbstractGeneratorObject& genObj = *e.front().key();
5145 if (&genObj.global() == global) {
5146 terminateDebuggerFrame(gcx, this, e.front().value(), NullFramePtr(),
5147 nullptr, &e);
5148 }
5149 }
5150 }
5151
5152 for (FrameMap::Enum e(frames); !e.empty(); e.popFront()) {
5153 AbstractFramePtr frame = e.front().key();
5154 if (frame.hasGlobal(global)) {
5155 terminateDebuggerFrame(gcx, this, e.front().value(), frame, &e);
5156 }
5157 }
5158
5159 JS::AutoAssertNoGC nogc;
5160 auto& globalDebuggersVector = global->getDebuggers(nogc);
5161
5162 // The relation must be removed from up to three places:
5163 // globalDebuggersVector and debuggees for sure, and possibly the
5164 // compartment's debuggee set.
5165 //
5166 // The debuggee zone set is recomputed on demand. This avoids refcounting
5167 // and in practice we have relatively few debuggees that tend to all be in
5168 // the same zone. If after recomputing the debuggee zone set, this global's
5169 // zone is not in the set, then we must remove ourselves from the zone's
5170 // vector of observing debuggers.
5171 globalDebuggersVector.erase(
5172 findDebuggerInVector(this, &globalDebuggersVector));
5173
5174 if (debugEnum) {
5175 debugEnum->removeFront();
5176 } else {
5177 debuggees.remove(global);
5178 }
5179
5180 recomputeDebuggeeZoneSet();
5181
5182 // Remove all breakpoints for the debuggee.
5183 Breakpoint* nextbp;
5184 for (Breakpoint* bp = firstBreakpoint(); bp; bp = nextbp) {
5185 nextbp = bp->nextInDebugger();
5186
5187 if (bp->site->realm() == global->realm()) {
5188 bp->remove(gcx);
5189 }
5190 }
5191 MOZ_ASSERT_IF(debuggees.empty(), !firstBreakpoint());
5192
5193 // If we are tracking allocation sites, we need to remove the object
5194 // metadata callback from this global's realm.
5195 if (trackingAllocationSites) {
5196 Debugger::removeAllocationsTracking(*global);
5197 }
5198
5199 if (!global->realm()->hasDebuggers() &&
5200 !global->realm()->isTracingExecution()) {
5201 global->realm()->unsetIsDebuggee();
5202 } else {
5203 global->realm()->updateDebuggerObservesAllExecution();
5204 global->realm()->updateDebuggerObservesAsmJS();
5205 global->realm()->updateDebuggerObservesWasm();
5206 global->realm()->updateDebuggerObservesCoverage();
5207 }
5208 }
5209
5210 class MOZ_STACK_CLASS Debugger::QueryBase {
5211 protected:
5212 QueryBase(JSContext* cx, Debugger* dbg)
5213 : cx(cx),
5214 debugger(dbg),
5215 iterMarker(&cx->runtime()->gc),
5216 realms(cx->zone()) {}
5217
5218 // The context in which we should do our work.
5219 JSContext* cx;
5220
5221 // The debugger for which we conduct queries.
5222 Debugger* debugger;
5223
5224 // Require the set of realms to stay fixed while the query is alive.
5225 gc::AutoEnterIteration iterMarker;
5226
5227 using RealmSet = HashSet<Realm*, DefaultHasher<Realm*>, ZoneAllocPolicy>;
5228
5229 // A script must be in one of these realms to match the query.
5230 RealmSet realms;
5231
5232 // Indicates whether OOM has occurred while matching.
5233 bool oom = false;
5234
5235 bool addRealm(Realm* realm) { return realms.put(realm); }
5236
5237 // Arrange for this query to match only scripts that run in |global|.
5238 bool matchSingleGlobal(GlobalObject* global) {
5239 MOZ_ASSERT(realms.count() == 0);
5240 if (!addRealm(global->realm())) {
5241 ReportOutOfMemory(cx);
5242 return false;
5243 }
5244 return true;
5245 }
5246
5247 // Arrange for this ScriptQuery to match all scripts running in debuggee
5248 // globals.
5249 bool matchAllDebuggeeGlobals() {
5250 MOZ_ASSERT(realms.count() == 0);
5251 // Build our realm set from the debugger's set of debuggee globals.
5252 for (WeakGlobalObjectSet::Range r = debugger->debuggees.all(); !r.empty();
5253 r.popFront()) {
5254 if (!addRealm(r.front()->realm())) {
5255 ReportOutOfMemory(cx);
5256 return false;
5257 }
5258 }
5259 return true;
5260 }
5261 };
5262
5263 /*
5264 * A class for parsing 'findScripts' query arguments and searching for
5265 * scripts that match the criteria they represent.
5266 */
5267 class MOZ_STACK_CLASS Debugger::ScriptQuery : public Debugger::QueryBase {
5268 public:
5269 /* Construct a ScriptQuery to use matching scripts for |dbg|. */
5270 ScriptQuery(JSContext* cx, Debugger* dbg)
5271 : QueryBase(cx, dbg),
5272 url(cx),
5273 displayURLString(cx),
5274 source(cx, AsVariant(static_cast<ScriptSourceObject*>(nullptr))),
5275 scriptVector(cx, BaseScriptVector(cx)),
5276 partialMatchVector(cx, BaseScriptVector(cx)),
5277 wasmInstanceVector(cx, WasmInstanceObjectVector(cx)) {}
5278
5279 /*
5280 * Parse the query object |query|, and prepare to match only the scripts
5281 * it specifies.
5282 */
5283 bool parseQuery(HandleObject query) {
5284 // Check for a 'global' property, which limits the results to those
5285 // scripts scoped to a particular global object.
5286 RootedValue global(cx);
5287 if (!GetProperty(cx, query, query, cx->names().global, &global)) {
5288 return false;
5289 }
5290 if (global.isUndefined()) {
5291 if (!matchAllDebuggeeGlobals()) {
5292 return false;
5293 }
5294 } else {
5295 GlobalObject* globalObject = debugger->unwrapDebuggeeArgument(cx, global);
5296 if (!globalObject) {
5297 return false;
5298 }
5299
5300 // If the given global isn't a debuggee, just leave the set of
5301 // acceptable globals empty; we'll return no scripts.
5302 if (debugger->debuggees.has(globalObject)) {
5303 if (!matchSingleGlobal(globalObject)) {
5304 return false;
5305 }
5306 }
5307 }
5308
5309 // Check for a 'url' property.
5310 if (!GetProperty(cx, query, query, cx->names().url, &url)) {
5311 return false;
5312 }
5313 if (!url.isUndefined() && !url.isString()) {
5314 JS_ReportErrorNumberASCII(
5315 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
5316 "query object's 'url' property", "neither undefined nor a string");
5317 return false;
5318 }
5319
5320 // Check for a 'source' property
5321 RootedValue debuggerSource(cx);
5322 if (!GetProperty(cx, query, query, cx->names().source, &debuggerSource)) {
5323 return false;
5324 }
5325 if (!debuggerSource.isUndefined()) {
5326 if (!debuggerSource.isObject() ||
5327 !debuggerSource.toObject().is<DebuggerSource>()) {
5328 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5329 JSMSG_UNEXPECTED_TYPE,
5330 "query object's 'source' property",
5331 "not undefined nor a Debugger.Source object");
5332 return false;
5333 }
5334
5335 DebuggerSource& debuggerSourceObj =
5336 debuggerSource.toObject().as<DebuggerSource>();
5337
5338 // If it does have an owner, it should match the Debugger we're
5339 // calling findScripts on. It would work fine even if it didn't,
5340 // but mixing Debugger.Sources is probably a sign of confusion.
5341 if (debuggerSourceObj.owner() != debugger) {
5342 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5343 JSMSG_DEBUG_WRONG_OWNER, "Debugger.Source");
5344 return false;
5345 }
5346
5347 hasSource = true;
5348 source = debuggerSourceObj.getReferent();
5349 }
5350
5351 // Check for a 'displayURL' property.
5352 RootedValue displayURL(cx);
5353 if (!GetProperty(cx, query, query, cx->names().displayURL, &displayURL)) {
5354 return false;
5355 }
5356 if (!displayURL.isUndefined() && !displayURL.isString()) {
5357 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5358 JSMSG_UNEXPECTED_TYPE,
5359 "query object's 'displayURL' property",
5360 "neither undefined nor a string");
5361 return false;
5362 }
5363
5364 if (displayURL.isString()) {
5365 displayURLString = displayURL.toString()->ensureLinear(cx);
5366 if (!displayURLString) {
5367 return false;
5368 }
5369 }
5370
5371 // Check for a 'line' property.
5372 RootedValue lineProperty(cx);
5373 if (!GetProperty(cx, query, query, cx->names().line, &lineProperty)) {
5374 return false;
5375 }
5376 if (lineProperty.isUndefined()) {
5377 hasLine = false;
5378 } else if (lineProperty.isNumber()) {
5379 if (displayURL.isUndefined() && url.isUndefined() && !hasSource) {
5380 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5381 JSMSG_QUERY_LINE_WITHOUT_URL,
5382 "'line' property");
5383 return false;
5384 }
5385 if (!parsePositiveInteger(lineProperty, line, JSMSG_DEBUG_BAD_LINE)) {
5386 return false;
5387 }
5388 hasLine = true;
5389 lineEnd = line;
5390 } else {
5391 JS_ReportErrorNumberASCII(
5392 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
5393 "query object's 'line' property", "neither undefined nor an integer");
5394 return false;
5395 }
5396
5397 // Check for a 'start' property.
5398 RootedValue startProperty(cx);
5399 if (!GetProperty(cx, query, query, cx->names().start, &startProperty)) {
5400 return false;
5401 }
5402 if (startProperty.isObject()) {
5403 Rooted<JSObject*> startObject(cx, &startProperty.toObject());
5404 if (!parseLineColumnObject(startObject, "start", line, columnStart)) {
5405 return false;
5406 }
5407 hasLine = true;
5408 } else if (!startProperty.isUndefined()) {
5409 JS_ReportErrorNumberASCII(
5410 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
5411 "query object's 'start' property", "neither undefined nor an object");
5412 return false;
5413 }
5414
5415 // Check for a 'end' property.
5416 RootedValue endProperty(cx);
5417 if (!GetProperty(cx, query, query, cx->names().end, &endProperty)) {
5418 return false;
5419 }
5420 if (endProperty.isObject()) {
5421 Rooted<JSObject*> endObject(cx, &endProperty.toObject());
5422 if (!parseLineColumnObject(endObject, "end", lineEnd, columnEnd)) {
5423 return false;
5424 }
5425 } else if (!endProperty.isUndefined()) {
5426 JS_ReportErrorNumberASCII(
5427 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
5428 "query object's 'end' property", "neither undefined nor an object");
5429 return false;
5430 }
5431
5432 if (startProperty.isUndefined() ^ endProperty.isUndefined()) {
5433 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5434 JSMSG_QUERY_USE_START_AND_END_TOGETHER);
5435 return false;
5436 }
5437
5438 if (!startProperty.isUndefined()) {
5439 // endProperty is also not undefined here
5440 if (displayURL.isUndefined() && url.isUndefined() && !hasSource) {
5441 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5442 JSMSG_QUERY_LINE_WITHOUT_URL,
5443 "'start' and 'end' properties");
5444 return false;
5445 }
5446 }
5447
5448 if (hasLine && lineEnd < line) {
5449 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5450 JSMSG_QUERY_START_LINE_IS_AFTER_END);
5451 return false;
5452 }
5453
5454 // Check for an 'innermost' property.
5455 PropertyName* innermostName = cx->names().innermost;
5456 RootedValue innermostProperty(cx);
5457 if (!GetProperty(cx, query, query, innermostName, &innermostProperty)) {
5458 return false;
5459 }
5460 innermost = ToBoolean(innermostProperty);
5461 if (innermost) {
5462 // Technically, we need only check hasLine, but this is clearer.
5463 if ((displayURL.isUndefined() && url.isUndefined() && !hasSource) ||
5464 !hasLine) {
5465 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5466 JSMSG_QUERY_INNERMOST_WITHOUT_LINE_URL);
5467 return false;
5468 }
5469 }
5470
5471 return true;
5472 }
5473
5474 /* Set up this ScriptQuery appropriately for a missing query argument. */
5475 bool omittedQuery() {
5476 url.setUndefined();
5477 hasLine = false;
5478 innermost = false;
5479 displayURLString = nullptr;
5480 return matchAllDebuggeeGlobals();
5481 }
5482
5483 /*
5484 * Search all relevant realms and the stack for scripts matching
5485 * this query, and append the matching scripts to |scriptVector|.
5486 */
5487 bool findScripts() {
5488 if (!prepareQuery()) {
5489 return false;
5490 }
5491
5492 Realm* singletonRealm = nullptr;
5493 if (realms.count() == 1) {
5494 singletonRealm = realms.all().front();
5495 }
5496
5497 // Search each realm for debuggee scripts.
5498 MOZ_ASSERT(scriptVector.empty());
5499 MOZ_ASSERT(partialMatchVector.empty());
5500 oom = false;
5501 IterateScripts(cx, singletonRealm, this, considerScript);
5502 if (oom) {
5503 ReportOutOfMemory(cx);
5504 return false;
5505 }
5506
5507 // If we are filtering by line number, the lazy BaseScripts were not checked
5508 // yet since they do not implement `GetScriptLineExtent`. Instead we revisit
5509 // each result script and delazify its children and add any matching ones to
5510 // the results list.
5511 MOZ_ASSERT(hasLine || partialMatchVector.empty());
5512 Rooted<BaseScript*> script(cx);
5513 RootedFunction fun(cx);
5514 while (!partialMatchVector.empty()) {
5515 script = partialMatchVector.popCopy();
5516
5517 // As a performance optimization, we can skip scripts that are definitely
5518 // out-of-bounds for the target line. This was checked before adding to
5519 // the partialMatchVector, but the bound may have improved since then.
5520 if (script->extent().sourceEnd <= sourceOffsetLowerBound) {
5521 continue;
5522 }
5523
5524 MOZ_ASSERT(script->isFunction());
5525 MOZ_ASSERT(script->isReadyForDelazification());
5526
5527 fun = script->function();
5528
5529 // Ignore any delazification placeholder functions. These should not be
5530 // exposed to debugger in any way.
5531 if (fun->isGhost()) {
5532 continue;
5533 }
5534
5535 // Delazify script.
5536 JSScript* compiledScript = GetOrCreateFunctionScript(cx, fun);
5537 if (!compiledScript) {
5538 return false;
5539 }
5540
5541 // If target line isn't in script, we are done with it.
5542 if (!scriptIsLineMatch(compiledScript)) {
5543 continue;
5544 }
5545
5546 // Add script to results now that we've completed checks.
5547 if (!scriptVector.append(compiledScript)) {
5548 return false;
5549 }
5550
5551 // If script was a leaf we are done with it. This is an optional
5552 // optimization to avoid inspecting the `gcthings` list below.
5553 if (!script->hasInnerFunctions()) {
5554 continue;
5555 }
5556
5557 // Now add inner scripts to `partialMatchVector` work list to determine if
5558 // they are matches. Note that out IterateScripts callback ignored them
5559 // already since they did not have a compiled parent at the time.
5560 for (JS::GCCellPtr thing : script->gcthings()) {
5561 if (!thing.is<JSObject>() || !thing.as<JSObject>().is<JSFunction>()) {
5562 continue;
5563 }
5564 JSFunction* fun = &thing.as<JSObject>().as<JSFunction>();
5565 if (!fun->hasBaseScript()) {
5566 continue;
5567 }
5568 BaseScript* inner = fun->baseScript();
5569 MOZ_ASSERT(inner);
5570 if (!inner) {
5571 // If the function doesn't have script, ignore it.
5572 continue;
5573 }
5574
5575 if (!scriptIsPartialLineMatch(inner)) {
5576 continue;
5577 }
5578
5579 // Add the matching inner script to the back of the results queue
5580 // where it will be processed recursively.
5581 if (!partialMatchVector.append(inner)) {
5582 return false;
5583 }
5584 }
5585 }
5586
5587 // If this is an 'innermost' query, we want to filter the results again to
5588 // only return the innermost script for each realm. To do this we build a
5589 // hashmap to track innermost and then recreate the `scriptVector` with the
5590 // results that remain in the hashmap.
5591 if (innermost) {
5592 using RealmToScriptMap =
5593 GCHashMap<Realm*, BaseScript*, DefaultHasher<Realm*>>;
5594
5595 Rooted<RealmToScriptMap> innermostForRealm(cx, cx);
5596
5597 // Visit each candidate script and find innermost in each realm.
5598 for (BaseScript* script : scriptVector) {
5599 Realm* realm = script->realm();
5600 RealmToScriptMap::AddPtr p = innermostForRealm.lookupForAdd(realm);
5601 if (p) {
5602 // Is our newly found script deeper than the last one we found?
5603 BaseScript* incumbent = p->value();
5604 if (script->asJSScript()->innermostScope()->chainLength() >
5605 incumbent->asJSScript()->innermostScope()->chainLength()) {
5606 p->value() = script;
5607 }
5608 } else {
5609 // This is the first matching script we've encountered for this
5610 // realm, so it is thus the innermost such script.
5611 if (!innermostForRealm.add(p, realm, script)) {
5612 return false;
5613 }
5614 }
5615 }
5616
5617 // Reset the results vector.
5618 scriptVector.clear();
5619
5620 // Re-add only the innermost scripts to the results.
5621 for (RealmToScriptMap::Range r = innermostForRealm.all(); !r.empty();
5622 r.popFront()) {
5623 if (!scriptVector.append(r.front().value())) {
5624 return false;
5625 }
5626 }
5627 }
5628
5629 // TODO: Until such time that wasm modules are real ES6 modules,
5630 // unconditionally consider all wasm toplevel instance scripts.
5631 for (WeakGlobalObjectSet::Range r = debugger->allDebuggees(); !r.empty();
5632 r.popFront()) {
5633 for (wasm::Instance* instance : r.front()->realm()->wasm.instances()) {
5634 consider(instance->object());
5635 if (oom) {
5636 ReportOutOfMemory(cx);
5637 return false;
5638 }
5639 }
5640 }
5641
5642 return true;
5643 }
5644
5645 Handle<BaseScriptVector> foundScripts() const { return scriptVector; }
5646
5647 Handle<WasmInstanceObjectVector> foundWasmInstances() const {
5648 return wasmInstanceVector;
5649 }
5650
5651 private:
5652 static const uint32_t LINE_CONSTRAINT_NOT_PROVIDED = 0;
5653
5654 /* If this is a string, matching scripts have urls equal to it. */
5655 RootedValue url;
5656
5657 /* url as a C string. */
5658 UniqueChars urlCString;
5659
5660 /* If this is a string, matching scripts' sources have displayURLs equal to
5661 * it. */
5662 Rooted<JSLinearString*> displayURLString;
5663
5664 /*
5665 * If this is a source referent, matching scripts will have sources equal
5666 * to this instance. Ideally we'd use a Maybe here, but Maybe interacts
5667 * very badly with Rooted's LIFO invariant.
5668 */
5669 bool hasSource = false;
5670 Rooted<DebuggerSourceReferent> source;
5671
5672 /* True if the query contained a 'line' or 'start' property. */
5673 bool hasLine = false;
5674
5675 /* The start line of the target range, inclusive. A script's lines must
5676 * overlap the target line range or it will be filtered out by the query. */
5677 uint32_t line = LINE_CONSTRAINT_NOT_PROVIDED;
5678
5679 /* The end line of the target range, inclusive. A script's lines must overlap
5680 * the target line range or it will be filtered out by the query. */
5681 uint32_t lineEnd = LINE_CONSTRAINT_NOT_PROVIDED;
5682
5683 Maybe<JS::LimitedColumnNumberOneOrigin> columnStart;
5684
5685 Maybe<JS::LimitedColumnNumberOneOrigin> columnEnd;
5686
5687 // As a performance optimization (and to avoid delazifying as many scripts),
5688 // we would like to know the source offset of the target range start line.
5689 //
5690 // Since we do not have a simple way to compute this precisely, we instead
5691 // track a lower-bound of the offset value. As we collect SourceExtent
5692 // examples with (line,column) <-> sourceStart mappings, we can improve the
5693 // bound. The target range start line is within the range
5694 // [sourceOffsetLowerBound, Inf).
5695 //
5696 // NOTE: Using a SourceExtent for updating the bound happens independently of
5697 // if the script matches the target range start line or not in the end.
5698 mutable uint32_t sourceOffsetLowerBound = 0;
5699
5700 /* True if the query has an 'innermost' property whose value is true. */
5701 bool innermost = false;
5702
5703 /*
5704 * Accumulate the scripts in an Rooted<BaseScriptVector> instead of creating
5705 * the JS array as we go, because we mustn't allocate JS objects or GC while
5706 * we use the CellIter.
5707 */
5708 Rooted<BaseScriptVector> scriptVector;
5709
5710 /*
5711 * While in the CellIter we may find BaseScripts that need to be compiled
5712 * before the query can be fully checked. Since we cannot compile while under
5713 * CellIter we accumulate them here instead.
5714 *
5715 * This occurs when matching line numbers since `GetScriptLineExtent` cannot
5716 * be computed without bytecode existing.
5717 */
5718 Rooted<BaseScriptVector> partialMatchVector;
5719
5720 /*
5721 * Like above, but for wasm modules.
5722 */
5723 Rooted<WasmInstanceObjectVector> wasmInstanceVector;
5724
5725 /*
5726 * Given that parseQuery or omittedQuery has been called, prepare to match
5727 * scripts. Set urlCString and displayURLChars as appropriate.
5728 */
5729 bool prepareQuery() {
5730 // Compute urlCString and displayURLChars, if a url or displayURL was
5731 // given respectively.
5732 if (url.isString()) {
5733 Rooted<JSString*> str(cx, url.toString());
5734 urlCString = JS_EncodeStringToUTF8(cx, str);
5735 if (!urlCString) {
5736 return false;
5737 }
5738 }
5739
5740 return true;
5741 }
5742
5743 template <size_t N>
5744 bool parseLineColumnObject(
5745 Handle<JSObject*> obj, const char (&propName)[N], uint32_t& lineOut,
5746 Maybe<JS::LimitedColumnNumberOneOrigin>& columnOut) {
5747 RootedValue lineProp(cx);
5748 if (!GetProperty(cx, obj, obj, cx->names().line, &lineProp)) {
5749 return false;
5750 }
5751 if (!lineProp.isNumber()) {
5752 static const char propMessageFormat[] =
5753 "query object's '%s.line' property";
5754 char propMessage[N - 1 /* propName's terminating null */
5755 + sizeof(propMessageFormat) - 2 /* '%s' is replaced */];
5756 DebugOnly<size_t> checkLen =
5757 SprintfLiteral(propMessage, propMessageFormat, propName);
5758 MOZ_ASSERT(checkLen == sizeof(propMessage) - 1 /* terminating null */);
5759 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5760 JSMSG_UNEXPECTED_TYPE, propMessage,
5761 "not a number");
5762 return false;
5763 }
5764 if (!parsePositiveInteger(lineProp, lineOut, JSMSG_DEBUG_BAD_LINE)) {
5765 return false;
5766 }
5767
5768 RootedValue columnProp(cx);
5769 if (!GetProperty(cx, obj, obj, cx->names().column, &columnProp)) {
5770 return false;
5771 }
5772 if (!columnProp.isUndefined()) {
5773 if (!columnProp.isNumber()) {
5774 static const char propMessageFormat[] =
5775 "query object's '%s.column' property";
5776 char propMessage[N - 1 /* propName's terminating null */
5777 + sizeof(propMessageFormat) -
5778 2 /* '%s' is replaced */];
5779 DebugOnly<size_t> checkLen =
5780 SprintfLiteral(propMessage, propMessageFormat, propName);
5781 MOZ_ASSERT(checkLen == sizeof(propMessage) - 1 /* terminating null */);
5782 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5783 JSMSG_UNEXPECTED_TYPE, propMessage,
5784 "not a number");
5785 return false;
5786 }
5787 uint32_t uintColumn = 0;
5788 if (!parsePositiveInteger(columnProp, uintColumn,
5789 JSMSG_BAD_COLUMN_NUMBER)) {
5790 return false;
5791 }
5792 if (uintColumn > JS::LimitedColumnNumberOneOrigin::Limit) {
5793 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
5794 JSMSG_BAD_COLUMN_NUMBER);
5795 return false;
5796 }
5797 columnOut.emplace(JS::LimitedColumnNumberOneOrigin(uintColumn));
5798 }
5799 return true;
5800 }
5801
5802 bool parsePositiveInteger(Handle<Value> numberProp, uint32_t& result,
5803 JSErrNum errorNumber) {
5804 double doubleVal = numberProp.toNumber();
5805 uint32_t uintVal = (uint32_t)doubleVal;
5806 if (doubleVal <= 0 || uintVal != doubleVal) {
5807 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, errorNumber);
5808 return false;
5809 }
5810 result = uintVal;
5811 return true;
5812 }
5813
5814 void updateSourceOffsetLowerBound(const SourceExtent& extent) {
5815 // We trying to find the offset of (target-range-start-line, 0), so ignore
5816 // any scripts within the target range.
5817 MOZ_ASSERT(line != LINE_CONSTRAINT_NOT_PROVIDED &&
5818 lineEnd != LINE_CONSTRAINT_NOT_PROVIDED);
5819 MOZ_ASSERT(extent.lineno <= lineEnd);
5820 if (extent.lineno >= line) {
5821 return;
5822 }
5823
5824 // The extent.sourceStart position is now definitely *before* the target
5825 // range start line, so update sourceOffsetLowerBound if extent.sourceStart
5826 // is a tighter bound.
5827 if (extent.sourceStart > sourceOffsetLowerBound) {
5828 sourceOffsetLowerBound = extent.sourceStart;
5829 }
5830 }
5831
5832 // A partial match is a script that starts before the target range ends, but
5833 // may or may not end before the target range starts. We can also return false
5834 // if we can prove the script ends before the target range starts.
5835 bool scriptIsPartialLineMatch(BaseScript* script) {
5836 const SourceExtent& extent = script->extent();
5837
5838 // We only know for sure that the script is outside the target line range
5839 // if the start of script is after the target end line, because we don't
5840 // know how many lines the script has yet.
5841 MOZ_ASSERT(line != LINE_CONSTRAINT_NOT_PROVIDED &&
5842 lineEnd != LINE_CONSTRAINT_NOT_PROVIDED);
5843 MOZ_ASSERT(line <= lineEnd);
5844 if (extent.lineno > lineEnd) {
5845 return false;
5846 }
5847 if (columnEnd.isSome() && script->lineno() == lineEnd &&
5848 script->column() > columnEnd.value()) {
5849 return false;
5850 }
5851
5852 // Use the implicit (line, column) <-> sourceStart mapping from the
5853 // SourceExtent to update our bounds on possible matches. We call this
5854 // without knowing if the script is a match or not.
5855 updateSourceOffsetLowerBound(script->extent());
5856
5857 // As an optional performance optimization, we rule out any script that ends
5858 // before the lower-bound on where target range start line exists.
5859 return extent.sourceEnd > sourceOffsetLowerBound;
5860 }
5861
5862 // True if any part of script source overlaps the target range.
5863 bool scriptIsLineMatch(JSScript* script) {
5864 MOZ_ASSERT(scriptIsPartialLineMatch(script));
5865
5866 JS::LimitedColumnNumberOneOrigin scriptEndColumn;
5867 uint32_t lineCount = GetScriptLineExtent(script, &scriptEndColumn);
5868 if (columnStart.isSome() && script->lineno() + lineCount - 1 == line) {
5869 if (scriptEndColumn <= columnStart.value()) {
5870 return false;
5871 }
5872 }
5873 return (script->lineno() + lineCount > line);
5874 }
5875
5876 static void considerScript(JSRuntime* rt, void* data, BaseScript* script,
5877 const JS::AutoRequireNoGC& nogc) {
5878 ScriptQuery* self = static_cast<ScriptQuery*>(data);
5879 self->consider(script, nogc);
5880 }
5881
5882 template <typename T>
5883 [[nodiscard]] bool commonFilter(T script, const JS::AutoRequireNoGC& nogc) {
5884 if (urlCString) {
5885 bool gotFilename = false;
5886 if (script->filename() &&
5887 strcmp(script->filename(), urlCString.get()) == 0) {
5888 gotFilename = true;
5889 }
5890
5891 bool gotSourceURL = false;
5892 if (!gotFilename && script->scriptSource()->introducerFilename() &&
5893 strcmp(script->scriptSource()->introducerFilename(),
5894 urlCString.get()) == 0) {
5895 gotSourceURL = true;
5896 }
5897 if (!gotFilename && !gotSourceURL) {
5898 return false;
5899 }
5900 }
5901 if (displayURLString) {
5902 if (!script->scriptSource() || !script->scriptSource()->hasDisplayURL()) {
5903 return false;
5904 }
5905
5906 const char16_t* s = script->scriptSource()->displayURL();
5907 if (CompareChars(s, js_strlen(s), displayURLString) != 0) {
5908 return false;
5909 }
5910 }
5911 if (hasSource && !(source.is<ScriptSourceObject*>() &&
5912 source.as<ScriptSourceObject*>()->source() ==
5913 script->scriptSource())) {
5914 return false;
5915 }
5916 return true;
5917 }
5918
5919 /*
5920 * If |script| matches this query, append it to |scriptVector|. Set |oom| if
5921 * an out of memory condition occurred.
5922 */
5923 void consider(BaseScript* script, const JS::AutoRequireNoGC& nogc) {
5924 if (oom || script->selfHosted()) {
5925 return;
5926 }
5927
5928 Realm* realm = script->realm();
5929 if (!realms.has(realm)) {
5930 return;
5931 }
5932
5933 if (!commonFilter(script, nogc)) {
5934 return;
5935 }
5936
5937 bool partial = false;
5938
5939 if (hasLine) {
5940 if (!scriptIsPartialLineMatch(script)) {
5941 return;
5942 }
5943
5944 if (script->hasBytecode()) {
5945 // Check if line is within script (or any of its inner scripts).
5946 if (!scriptIsLineMatch(script->asJSScript())) {
5947 return;
5948 }
5949 } else {
5950 // GetScriptLineExtent is not available on lazy scripts so instead to
5951 // the partial match list for be compiled and reprocessed later. We only
5952 // add scripts that are ready for delazification and they may in turn
5953 // process their inner functions.
5954 if (!script->isReadyForDelazification()) {
5955 return;
5956 }
5957 partial = true;
5958 }
5959 }
5960
5961 // If innermost filter is required, we collect everything that matches the
5962 // line number and filter at the end of `findScripts`.
5963 MOZ_ASSERT_IF(innermost, hasLine);
5964
5965 Rooted<BaseScriptVector>& vec = partial ? partialMatchVector : scriptVector;
5966 if (!vec.append(script)) {
5967 oom = true;
5968 }
5969 }
5970
5971 /*
5972 * If |instanceObject| matches this query, append it to |wasmInstanceVector|.
5973 * Set |oom| if an out of memory condition occurred.
5974 */
5975 void consider(WasmInstanceObject* instanceObject) {
5976 if (oom) {
5977 return;
5978 }
5979
5980 if (hasSource && source != AsVariant(instanceObject)) {
5981 return;
5982 }
5983
5984 if (!wasmInstanceVector.append(instanceObject)) {
5985 oom = true;
5986 }
5987 }
5988 };
5989
5990 bool Debugger::CallData::findScripts() {
5991 ScriptQuery query(cx, dbg);
5992
5993 if (args.length() >= 1) {
5994 RootedObject queryObject(cx, RequireObject(cx, args[0]));
5995 if (!queryObject || !query.parseQuery(queryObject)) {
5996 return false;
5997 }
5998 } else {
5999 if (!query.omittedQuery()) {
6000 return false;
6001 }
6002 }
6003
6004 if (!query.findScripts()) {
6005 return false;
6006 }
6007
6008 Handle<BaseScriptVector> scripts(query.foundScripts());
6009 Handle<WasmInstanceObjectVector> wasmInstances(query.foundWasmInstances());
6010
6011 size_t resultLength = scripts.length() + wasmInstances.length();
6012 Rooted<ArrayObject*> result(cx,
6013 NewDenseFullyAllocatedArray(cx, resultLength));
6014 if (!result) {
6015 return false;
6016 }
6017
6018 result->ensureDenseInitializedLength(0, resultLength);
6019
6020 for (size_t i = 0; i < scripts.length(); i++) {
6021 JSObject* scriptObject = dbg->wrapScript(cx, scripts[i]);
6022 if (!scriptObject) {
6023 return false;
6024 }
6025 result->setDenseElement(i, ObjectValue(*scriptObject));
6026 }
6027
6028 size_t wasmStart = scripts.length();
6029 for (size_t i = 0; i < wasmInstances.length(); i++) {
6030 JSObject* scriptObject = dbg->wrapWasmScript(cx, wasmInstances[i]);
6031 if (!scriptObject) {
6032 return false;
6033 }
6034 result->setDenseElement(wasmStart + i, ObjectValue(*scriptObject));
6035 }
6036
6037 args.rval().setObject(*result);
6038 return true;
6039 }
6040
6041 /*
6042 * A class for searching sources for 'findSources'.
6043 */
6044 class MOZ_STACK_CLASS Debugger::SourceQuery : public Debugger::QueryBase {
6045 public:
6046 using SourceSet = JS::GCHashSet<JSObject*, js::StableCellHasher<JSObject*>,
6047 ZoneAllocPolicy>;
6048
6049 SourceQuery(JSContext* cx, Debugger* dbg)
6050 : QueryBase(cx, dbg), sources(cx, SourceSet(cx->zone())) {}
6051
6052 bool findSources() {
6053 if (!matchAllDebuggeeGlobals()) {
6054 return false;
6055 }
6056
6057 Realm* singletonRealm = nullptr;
6058 if (realms.count() == 1) {
6059 singletonRealm = realms.all().front();
6060 }
6061
6062 // Search each realm for debuggee scripts.
6063 MOZ_ASSERT(sources.empty());
6064 oom = false;
6065 IterateScripts(cx, singletonRealm, this, considerScript);
6066 if (oom) {
6067 ReportOutOfMemory(cx);
6068 return false;
6069 }
6070
6071 // TODO: Until such time that wasm modules are real ES6 modules,
6072 // unconditionally consider all wasm toplevel instance scripts.
6073 for (WeakGlobalObjectSet::Range r = debugger->allDebuggees(); !r.empty();
6074 r.popFront()) {
6075 for (wasm::Instance* instance : r.front()->realm()->wasm.instances()) {
6076 consider(instance->object());
6077 if (oom) {
6078 ReportOutOfMemory(cx);
6079 return false;
6080 }
6081 }
6082 }
6083
6084 return true;
6085 }
6086
6087 Handle<SourceSet> foundSources() const { return sources; }
6088
6089 private:
6090 Rooted<SourceSet> sources;
6091
6092 static void considerScript(JSRuntime* rt, void* data, BaseScript* script,
6093 const JS::AutoRequireNoGC& nogc) {
6094 SourceQuery* self = static_cast<SourceQuery*>(data);
6095 self->consider(script, nogc);
6096 }
6097
6098 void consider(BaseScript* script, const JS::AutoRequireNoGC& nogc) {
6099 if (oom || script->selfHosted()) {
6100 return;
6101 }
6102
6103 Realm* realm = script->realm();
6104 if (!realms.has(realm)) {
6105 return;
6106 }
6107
6108 ScriptSourceObject* source = script->sourceObject();
6109 if (!sources.put(source)) {
6110 oom = true;
6111 }
6112 }
6113
6114 void consider(WasmInstanceObject* instanceObject) {
6115 if (oom) {
6116 return;
6117 }
6118
6119 if (!sources.put(instanceObject)) {
6120 oom = true;
6121 }
6122 }
6123 };
6124
6125 static inline DebuggerSourceReferent AsSourceReferent(JSObject* obj) {
6126 if (obj->is<ScriptSourceObject>()) {
6127 return AsVariant(&obj->as<ScriptSourceObject>());
6128 }
6129 return AsVariant(&obj->as<WasmInstanceObject>());
6130 }
6131
6132 bool Debugger::CallData::findSources() {
6133 SourceQuery query(cx, dbg);
6134 if (!query.findSources()) {
6135 return false;
6136 }
6137
6138 Handle<SourceQuery::SourceSet> sources(query.foundSources());
6139
6140 size_t resultLength = sources.count();
6141 Rooted<ArrayObject*> result(cx,
6142 NewDenseFullyAllocatedArray(cx, resultLength));
6143 if (!result) {
6144 return false;
6145 }
6146
6147 result->ensureDenseInitializedLength(0, resultLength);
6148
6149 size_t i = 0;
6150 for (auto iter = sources.get().iter(); !iter.done(); iter.next()) {
6151 Rooted<DebuggerSourceReferent> sourceReferent(cx,
6152 AsSourceReferent(iter.get()));
6153 RootedObject sourceObject(cx, dbg->wrapVariantReferent(cx, sourceReferent));
6154 if (!sourceObject) {
6155 return false;
6156 }
6157 result->setDenseElement(i, ObjectValue(*sourceObject));
6158 i++;
6159 }
6160
6161 args.rval().setObject(*result);
6162 return true;
6163 }
6164
6165 /*
6166 * A class for parsing 'findObjects' query arguments and searching for objects
6167 * that match the criteria they represent.
6168 */
6169 class MOZ_STACK_CLASS Debugger::ObjectQuery {
6170 public:
6171 /* Construct an ObjectQuery to use matching scripts for |dbg|. */
6172 ObjectQuery(JSContext* cx, Debugger* dbg)
6173 : objects(cx),
6174 cx(cx),
6175 dbg(dbg),
6176 queryType(QueryType::None),
6177 jsClassName(cx),
6178 unwrappedCtorOrProto(cx) {}
6179
6180 /* The vector that we are accumulating results in. */
6181 RootedObjectVector objects;
6182
6183 /* The set of debuggee compartments. */
6184 JS::CompartmentSet debuggeeCompartments;
6185
6186 /*
6187 * Parse the query object |query|, and prepare to match only the objects it
6188 * specifies.
6189 */
6190 bool parseQuery(HandleObject query) {
6191 // Check for the 'class' property
6192 RootedValue cls(cx);
6193 if (!GetProperty(cx, query, query, cx->names().class_, &cls)) {
6194 return false;
6195 }
6196
6197 if (cls.isUndefined()) {
6198 return true;
6199 }
6200
6201 if (cls.isString()) {
6202 JSLinearString* str = cls.toString()->ensureLinear(cx);
6203 if (!str) {
6204 return false;
6205 }
6206 if (!StringIsAscii(str)) {
6207 JS_ReportErrorNumberASCII(
6208 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
6209 "query object's 'class' property string",
6210 "not a string containing only ASCII characters");
6211 return false;
6212 }
6213 jsClassName = cls;
6214 queryType = QueryType::JSClassName;
6215 return true;
6216 }
6217
6218 if (cls.isObject()) {
6219 JS::Rooted<JSObject*> obj(cx, &cls.toObject());
6220 obj = UncheckedUnwrap(obj);
6221 if (JS_IsDeadWrapper(obj)) {
6222 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6223 JSMSG_DEAD_OBJECT);
6224 return false;
6225 }
6226 if (!obj->is<DebuggerObject>()) {
6227 JS_ReportErrorNumberASCII(
6228 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
6229 "query object's 'class' property object", "not Debugger.Object");
6230 return false;
6231 }
6232
6233 unwrappedCtorOrProto = obj->as<DebuggerObject>().referent();
6234 unwrappedCtorOrProto = UncheckedUnwrap(unwrappedCtorOrProto);
6235 if (JS_IsDeadWrapper(unwrappedCtorOrProto)) {
6236 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6237 JSMSG_DEAD_OBJECT);
6238 return false;
6239 }
6240 queryType = QueryType::CtorOrProto;
6241 return true;
6242 }
6243
6244 JS_ReportErrorNumberASCII(
6245 cx, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
6246 "query object's 'class' property",
6247 "none of JSClass name string, constructor/prototype debuggee object, "
6248 "or undefined");
6249 return false;
6250 }
6251
6252 /* Set up this ObjectQuery appropriately for a missing query argument. */
6253 void omittedQuery() {
6254 jsClassName.setUndefined();
6255 unwrappedCtorOrProto = nullptr;
6256 queryType = QueryType::None;
6257 }
6258
6259 /*
6260 * Traverse the heap to find all relevant objects and add them to the
6261 * provided vector.
6262 */
6263 bool findObjects() {
6264 if (!prepareQuery()) {
6265 return false;
6266 }
6267
6268 for (WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty();
6269 r.popFront()) {
6270 if (!debuggeeCompartments.put(r.front()->compartment())) {
6271 ReportOutOfMemory(cx);
6272 return false;
6273 }
6274 }
6275
6276 {
6277 // We can't tolerate the GC moving things around while we're
6278 // searching the heap. Check that nothing we do causes a GC.
6279 RootedObject dbgObj(cx, dbg->object);
6280 JS::ubi::RootList rootList(cx);
6281 auto [ok, nogc] = rootList.init(dbgObj);
6282 if (!ok) {
6283 ReportOutOfMemory(cx);
6284 return false;
6285 }
6286
6287 Traversal traversal(cx, *this, nogc);
6288 traversal.wantNames = false;
6289
6290 if (!traversal.addStart(JS::ubi::Node(&rootList)) ||
6291 !traversal.traverse()) {
6292 ReportOutOfMemory(cx);
6293 return false;
6294 }
6295 return true;
6296 }
6297 }
6298
6299 /*
6300 * |ubi::Node::BreadthFirst| interface.
6301 */
6302 class NodeData {};
6303 using Traversal = JS::ubi::BreadthFirst<ObjectQuery>;
6304 bool operator()(Traversal& traversal, JS::ubi::Node origin,
6305 const JS::ubi::Edge& edge, NodeData*, bool first) {
6306 if (!first) {
6307 return true;
6308 }
6309
6310 JS::ubi::Node referent = edge.referent;
6311
6312 // Only follow edges within our set of debuggee compartments; we don't
6313 // care about the heap's subgraphs outside of our debuggee compartments,
6314 // so we abandon the referent. Either (1) there is not a path from this
6315 // non-debuggee node back to a node in our debuggee compartments, and we
6316 // don't need to follow edges to or from this node, or (2) there does
6317 // exist some path from this non-debuggee node back to a node in our
6318 // debuggee compartments. However, if that were true, then the incoming
6319 // cross compartment edge back into a debuggee compartment is already
6320 // listed as an edge in the RootList we started traversal with, and
6321 // therefore we don't need to follow edges to or from this non-debuggee
6322 // node.
6323 JS::Compartment* comp = referent.compartment();
6324 if (comp && !debuggeeCompartments.has(comp)) {
6325 traversal.abandonReferent();
6326 return true;
6327 }
6328
6329 // If the referent has an associated realm and it's not a debuggee
6330 // realm, skip it. Don't abandonReferent() here like above: realms
6331 // within a compartment can reference each other without going through
6332 // cross-compartment wrappers.
6333 Realm* realm = referent.realm();
6334 if (realm && !dbg->isDebuggeeUnbarriered(realm)) {
6335 return true;
6336 }
6337
6338 // If the referent is an object and matches our query's restrictions,
6339 // add it to the vector accumulating results. Skip objects that should
6340 // never be exposed to JS, like EnvironmentObjects and internal
6341 // functions.
6342
6343 if (!referent.is<JSObject>() || referent.exposeToJS().isUndefined()) {
6344 return true;
6345 }
6346
6347 JSObject* obj = referent.as<JSObject>();
6348
6349 switch (queryType) {
6350 case QueryType::None:
6351 break;
6352 case QueryType::JSClassName: {
6353 const char* objJSClassName = obj->getClass()->name;
6354 if (strcmp(objJSClassName, jsClassNameCString.get()) != 0) {
6355 return true;
6356 }
6357 break;
6358 }
6359 case QueryType::CtorOrProto:
6360 if (!hasConstructorOrPrototype(obj, unwrappedCtorOrProto, cx)) {
6361 return true;
6362 }
6363 break;
6364 }
6365
6366 return objects.append(obj);
6367 }
6368
6369 // Returns true if `obj` is confirmed to have `ctorOrProto` as its
6370 // constructor or prototype in the prototype chain.
6371 //
6372 // If it requires side-effect-ful operation for accessing the constructor or
6373 // prototype, this can return false even if `obj instanceof ctorOrProto` is
6374 // actually `true`.
6375 static bool hasConstructorOrPrototype(JSObject* obj, JSObject* ctorOrProto,
6376 JSContext* cx) {
6377 obj = UncheckedUnwrap(obj);
6378
6379 while (true) {
6380 if (!obj->hasStaticPrototype()) {
6381 // Dynamic prototype cannot be matched without side-effect.
6382 break;
6383 }
6384
6385 JSObject* proto = obj->staticPrototype();
6386 if (!proto) {
6387 break;
6388 }
6389 proto = UncheckedUnwrap(proto);
6390 if (proto == ctorOrProto) {
6391 return true;
6392 }
6393
6394 JS::Value ctorVal;
6395 bool result;
6396 {
6397 AutoRealm ar(cx, proto);
6398 result = GetPropertyPure(cx, proto, NameToId(cx->names().constructor),
6399 &ctorVal);
6400 }
6401 if (result && ctorVal.isObject()) {
6402 JSObject* ctor = &ctorVal.toObject();
6403 ctor = UncheckedUnwrap(ctor);
6404 if (ctor == ctorOrProto) {
6405 return true;
6406 }
6407 }
6408
6409 obj = proto;
6410 }
6411
6412 return false;
6413 }
6414
6415 private:
6416 /* The context in which we should do our work. */
6417 JSContext* cx;
6418
6419 /* The debugger for which we conduct queries. */
6420 Debugger* dbg;
6421
6422 enum class QueryType {
6423 /* No filtering. */
6424 None,
6425
6426 /* Match objects with given JSClass name. */
6427 JSClassName,
6428
6429 /* Match objects with given object as constructor or prototype. */
6430 CtorOrProto,
6431 };
6432 QueryType queryType;
6433
6434 /* Matching objects will have a JSClass whose name is this property. */
6435 RootedValue jsClassName;
6436
6437 /* The jsClassName member, as a C string. */
6438 UniqueChars jsClassNameCString;
6439
6440 /* Matching objects will have given object as constructor or prototype. */
6441 JS::Rooted<JSObject*> unwrappedCtorOrProto;
6442
6443 /*
6444 * Given that either omittedQuery or parseQuery has been called, prepare the
6445 * query for matching objects.
6446 */
6447 bool prepareQuery() {
6448 if (jsClassName.isString()) {
6449 jsClassNameCString = JS_EncodeStringToASCII(cx, jsClassName.toString());
6450 if (!jsClassNameCString) {
6451 return false;
6452 }
6453 }
6454
6455 return true;
6456 }
6457 };
6458
6459 bool Debugger::CallData::findObjects() {
6460 ObjectQuery query(cx, dbg);
6461
6462 if (args.length() >= 1) {
6463 RootedObject queryObject(cx, RequireObject(cx, args[0]));
6464 if (!queryObject || !query.parseQuery(queryObject)) {
6465 return false;
6466 }
6467 } else {
6468 query.omittedQuery();
6469 }
6470
6471 if (!query.findObjects()) {
6472 return false;
6473 }
6474
6475 // Returning internal objects (such as self-hosting intrinsics) to JS is not
6476 // fuzzing-safe. We still want to call parseQuery/findObjects when fuzzing so
6477 // just clear the Vector here.
6478 if (fuzzingSafe) {
6479 query.objects.clear();
6480 }
6481
6482 size_t length = query.objects.length();
6483 Rooted<ArrayObject*> result(cx, NewDenseFullyAllocatedArray(cx, length));
6484 if (!result) {
6485 return false;
6486 }
6487
6488 result->ensureDenseInitializedLength(0, length);
6489
6490 for (size_t i = 0; i < length; i++) {
6491 RootedValue debuggeeVal(cx, ObjectValue(*query.objects[i]));
6492 if (!dbg->wrapDebuggeeValue(cx, &debuggeeVal)) {
6493 return false;
6494 }
6495 result->setDenseElement(i, debuggeeVal);
6496 }
6497
6498 args.rval().setObject(*result);
6499 return true;
6500 }
6501
6502 bool Debugger::CallData::findAllGlobals() {
6503 RootedObjectVector globals(cx);
6504
6505 {
6506 // Accumulate the list of globals before wrapping them, because
6507 // wrapping can GC and collect realms from under us, while iterating.
6508 JS::AutoCheckCannotGC nogc;
6509
6510 for (RealmsIter r(cx->runtime()); !r.done(); r.next()) {
6511 if (r->creationOptions().invisibleToDebugger()) {
6512 continue;
6513 }
6514
6515 if (!r->hasInitializedGlobal()) {
6516 continue;
6517 }
6518
6519 if (JS::RealmBehaviorsRef(r).isNonLive()) {
6520 continue;
6521 }
6522
6523 r->compartment()->gcState.scheduledForDestruction = false;
6524
6525 GlobalObject* global = r->maybeGlobal();
6526
6527 // We pulled |global| out of nowhere, so it's possible that it was
6528 // marked gray by XPConnect. Since we're now exposing it to JS code,
6529 // we need to mark it black.
6530 JS::ExposeObjectToActiveJS(global);
6531 if (!globals.append(global)) {
6532 return false;
6533 }
6534 }
6535 }
6536
6537 RootedObject result(cx, NewDenseEmptyArray(cx));
6538 if (!result) {
6539 return false;
6540 }
6541
6542 for (size_t i = 0; i < globals.length(); i++) {
6543 RootedValue globalValue(cx, ObjectValue(*globals[i]));
6544 if (!dbg->wrapDebuggeeValue(cx, &globalValue)) {
6545 return false;
6546 }
6547 if (!NewbornArrayPush(cx, result, globalValue)) {
6548 return false;
6549 }
6550 }
6551
6552 args.rval().setObject(*result);
6553 return true;
6554 }
6555
6556 bool Debugger::CallData::findSourceURLs() {
6557 RootedObject result(cx, NewDenseEmptyArray(cx));
6558 if (!result) {
6559 return false;
6560 }
6561
6562 for (WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty();
6563 r.popFront()) {
6564 RootedObject holder(cx, r.front()->getSourceURLsHolder());
6565 if (holder) {
6566 for (size_t i = 0; i < holder->as<ArrayObject>().length(); i++) {
6567 Value v = holder->as<ArrayObject>().getDenseElement(i);
6568
6569 // The value is an atom and doesn't need wrapping, but the holder may be
6570 // in another zone and the atom must be marked when we create a
6571 // reference in this zone.
6572 MOZ_ASSERT(v.isString() && v.toString()->isAtom());
6573 cx->markAtomValue(v);
6574
6575 if (!NewbornArrayPush(cx, result, v)) {
6576 return false;
6577 }
6578 }
6579 }
6580 }
6581
6582 args.rval().setObject(*result);
6583 return true;
6584 }
6585
6586 bool Debugger::CallData::makeGlobalObjectReference() {
6587 if (!args.requireAtLeast(cx, "Debugger.makeGlobalObjectReference", 1)) {
6588 return false;
6589 }
6590
6591 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
6592 if (!global) {
6593 return false;
6594 }
6595
6596 // If we create a D.O referring to a global in an invisible realm,
6597 // then from it we can reach function objects, scripts, environments, etc.,
6598 // none of which we're ever supposed to see.
6599 if (global->realm()->creationOptions().invisibleToDebugger()) {
6600 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
6601 JSMSG_DEBUG_INVISIBLE_COMPARTMENT);
6602 return false;
6603 }
6604
6605 args.rval().setObject(*global);
6606 return dbg->wrapDebuggeeValue(cx, args.rval());
6607 }
6608
6609 bool Debugger::isCompilableUnit(JSContext* cx, unsigned argc, Value* vp) {
6610 CallArgs args = CallArgsFromVp(argc, vp);
6611
6612 if (!args.requireAtLeast(cx, "Debugger.isCompilableUnit", 1)) {
6613 return false;
6614 }
6615
6616 if (!args[0].isString()) {
6617 JS_ReportErrorNumberASCII(
6618 cx, GetErrorMessage, nullptr, JSMSG_NOT_EXPECTED_TYPE,
6619 "Debugger.isCompilableUnit", "string", InformalValueTypeName(args[0]));
6620 return false;
6621 }
6622
6623 JSString* str = args[0].toString();
6624 size_t length = str->length();
6625
6626 AutoStableStringChars chars(cx);
6627 if (!chars.initTwoByte(cx, str)) {
6628 return false;
6629 }
6630
6631 bool result = true;
6632
6633 AutoReportFrontendContext fc(cx,
6634 AutoReportFrontendContext::Warning::Suppress);
6635 CompileOptions options(cx);
6636 Rooted<frontend::CompilationInput> input(cx,
6637 frontend::CompilationInput(options));
6638 if (!input.get().initForGlobal(&fc)) {
6639 return false;
6640 }
6641
6642 LifoAllocScope allocScope(&cx->tempLifoAlloc());
6643 frontend::NoScopeBindingCache scopeCache;
6644 frontend::CompilationState compilationState(&fc, allocScope, input.get());
6645 if (!compilationState.init(&fc, &scopeCache)) {
6646 return false;
6647 }
6648
6649 frontend::Parser<frontend::FullParseHandler, char16_t> parser(
6650 &fc, options, chars.twoByteChars(), length, compilationState,
6651 /* syntaxParser = */ nullptr);
6652 if (!parser.checkOptions() || parser.parse().isErr()) {
6653 // We ran into an error. If it was because we ran out of memory we report
6654 // it in the usual way.
6655 if (fc.hadOutOfMemory()) {
6656 return false;
6657 }
6658
6659 // If it was because we ran out of source, we return false so our caller
6660 // knows to try to collect more [source].
6661 if (parser.isUnexpectedEOF()) {
6662 result = false;
6663 }
6664
6665 fc.clearAutoReport();
6666 }
6667
6668 args.rval().setBoolean(result);
6669 return true;
6670 }
6671
6672 bool Debugger::CallData::adoptDebuggeeValue() {
6673 if (!args.requireAtLeast(cx, "Debugger.adoptDebuggeeValue", 1)) {
6674 return false;
6675 }
6676
6677 RootedValue v(cx, args[0]);
6678 if (v.isObject()) {
6679 RootedObject obj(cx, &v.toObject());
6680 DebuggerObject* ndobj = ToNativeDebuggerObject(cx, &obj);
6681 if (!ndobj) {
6682 return false;
6683 }
6684
6685 obj.set(ndobj->referent());
6686 v = ObjectValue(*obj);
6687
6688 if (!dbg->wrapDebuggeeValue(cx, &v)) {
6689 return false;
6690 }
6691 }
6692
6693 args.rval().set(v);
6694 return true;
6695 }
6696
6697 class DebuggerAdoptSourceMatcher {
6698 JSContext* cx_;
6699 Debugger* dbg_;
6700
6701 public:
6702 explicit DebuggerAdoptSourceMatcher(JSContext* cx, Debugger* dbg)
6703 : cx_(cx), dbg_(dbg) {}
6704
6705 using ReturnType = DebuggerSource*;
6706
6707 ReturnType match(Handle<ScriptSourceObject*> source) {
6708 if (source->compartment() == cx_->compartment()) {
6709 JS_ReportErrorASCII(cx_,
6710 "Source is in the same compartment as this debugger");
6711 return nullptr;
6712 }
6713 return dbg_->wrapSource(cx_, source);
6714 }
6715 ReturnType match(Handle<WasmInstanceObject*> wasmInstance) {
6716 if (wasmInstance->compartment() == cx_->compartment()) {
6717 JS_ReportErrorASCII(
6718 cx_, "WasmInstance is in the same compartment as this debugger");
6719 return nullptr;
6720 }
6721 return dbg_->wrapWasmSource(cx_, wasmInstance);
6722 }
6723 };
6724
6725 bool Debugger::CallData::adoptFrame() {
6726 if (!args.requireAtLeast(cx, "Debugger.adoptFrame", 1)) {
6727 return false;
6728 }
6729
6730 RootedObject obj(cx, RequireObject(cx, args[0]));
6731 if (!obj) {
6732 return false;
6733 }
6734
6735 obj = UncheckedUnwrap(obj);
6736 if (!obj->is<DebuggerFrame>()) {
6737 JS_ReportErrorASCII(cx, "Argument is not a Debugger.Frame");
6738 return false;
6739 }
6740
6741 RootedValue objVal(cx, ObjectValue(*obj));
6742 Rooted<DebuggerFrame*> frameObj(cx, DebuggerFrame::check(cx, objVal));
6743 if (!frameObj) {
6744 return false;
6745 }
6746
6747 Rooted<DebuggerFrame*> adoptedFrame(cx);
6748 if (frameObj->isOnStack()) {
6749 FrameIter iter = frameObj->getFrameIter(cx);
6750 if (!dbg->observesFrame(iter)) {
6751 JS_ReportErrorASCII(cx, "Debugger.Frame's global is not a debuggee");
6752 return false;
6753 }
6754 if (!dbg->getFrame(cx, iter, &adoptedFrame)) {
6755 return false;
6756 }
6757 } else if (frameObj->isSuspended()) {
6758 Rooted<AbstractGeneratorObject*> gen(cx, &frameObj->unwrappedGenerator());
6759 if (!dbg->observesGlobal(&gen->global())) {
6760 JS_ReportErrorASCII(cx, "Debugger.Frame's global is not a debuggee");
6761 return false;
6762 }
6763
6764 if (!dbg->getFrame(cx, gen, &adoptedFrame)) {
6765 return false;
6766 }
6767 } else {
6768 if (!dbg->getFrame(cx, &adoptedFrame)) {
6769 return false;
6770 }
6771 }
6772
6773 args.rval().setObject(*adoptedFrame);
6774 return true;
6775 }
6776
6777 bool Debugger::CallData::adoptSource() {
6778 if (!args.requireAtLeast(cx, "Debugger.adoptSource", 1)) {
6779 return false;
6780 }
6781
6782 RootedObject obj(cx, RequireObject(cx, args[0]));
6783 if (!obj) {
6784 return false;
6785 }
6786
6787 obj = UncheckedUnwrap(obj);
6788 if (!obj->is<DebuggerSource>()) {
6789 JS_ReportErrorASCII(cx, "Argument is not a Debugger.Source");
6790 return false;
6791 }
6792
6793 Rooted<DebuggerSource*> sourceObj(cx, &obj->as<DebuggerSource>());
6794 if (!sourceObj->getReferentRawObject()) {
6795 JS_ReportErrorASCII(cx, "Argument is Debugger.Source.prototype");
6796 return false;
6797 }
6798
6799 Rooted<DebuggerSourceReferent> referent(cx, sourceObj->getReferent());
6800
6801 DebuggerAdoptSourceMatcher matcher(cx, dbg);
6802 DebuggerSource* res = referent.match(matcher);
6803 if (!res) {
6804 return false;
6805 }
6806
6807 args.rval().setObject(*res);
6808 return true;
6809 }
6810
6811 bool Debugger::CallData::enableAsyncStack() {
6812 if (!args.requireAtLeast(cx, "Debugger.enableAsyncStack", 1)) {
6813 return false;
6814 }
6815 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
6816 if (!global) {
6817 return false;
6818 }
6819
6820 global->realm()->isAsyncStackCapturingEnabled = true;
6821
6822 args.rval().setUndefined();
6823 return true;
6824 }
6825
6826 bool Debugger::CallData::disableAsyncStack() {
6827 if (!args.requireAtLeast(cx, "Debugger.disableAsyncStack", 1)) {
6828 return false;
6829 }
6830 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
6831 if (!global) {
6832 return false;
6833 }
6834
6835 global->realm()->isAsyncStackCapturingEnabled = false;
6836
6837 args.rval().setUndefined();
6838 return true;
6839 }
6840
6841 bool Debugger::CallData::enableUnlimitedStacksCapturing() {
6842 if (!args.requireAtLeast(cx, "Debugger.enableUnlimitedStacksCapturing", 1)) {
6843 return false;
6844 }
6845 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
6846 if (!global) {
6847 return false;
6848 }
6849
6850 global->realm()->isUnlimitedStacksCapturingEnabled = true;
6851
6852 args.rval().setUndefined();
6853 return true;
6854 }
6855
6856 bool Debugger::CallData::disableUnlimitedStacksCapturing() {
6857 if (!args.requireAtLeast(cx, "Debugger.disableUnlimitedStacksCapturing", 1)) {
6858 return false;
6859 }
6860 Rooted<GlobalObject*> global(cx, dbg->unwrapDebuggeeArgument(cx, args[0]));
6861 if (!global) {
6862 return false;
6863 }
6864
6865 global->realm()->isUnlimitedStacksCapturingEnabled = false;
6866
6867 args.rval().setUndefined();
6868 return true;
6869 }
6870
6871 const JSPropertySpec Debugger::properties[] = {
6872 JS_DEBUG_PSGS("onDebuggerStatement", getOnDebuggerStatement,
6873 setOnDebuggerStatement),
6874 JS_DEBUG_PSGS("onExceptionUnwind", getOnExceptionUnwind,
6875 setOnExceptionUnwind),
6876 JS_DEBUG_PSGS("onNewScript", getOnNewScript, setOnNewScript),
6877 JS_DEBUG_PSGS("onNewPromise", getOnNewPromise, setOnNewPromise),
6878 JS_DEBUG_PSGS("onPromiseSettled", getOnPromiseSettled, setOnPromiseSettled),
6879 JS_DEBUG_PSGS("onEnterFrame", getOnEnterFrame, setOnEnterFrame),
6880 JS_DEBUG_PSGS("onNativeCall", getOnNativeCall, setOnNativeCall),
6881 JS_DEBUG_PSGS("shouldAvoidSideEffects", getShouldAvoidSideEffects,
6882 setShouldAvoidSideEffects),
6883 JS_DEBUG_PSGS("onNewGlobalObject", getOnNewGlobalObject,
6884 setOnNewGlobalObject),
6885 JS_DEBUG_PSGS("uncaughtExceptionHook", getUncaughtExceptionHook,
6886 setUncaughtExceptionHook),
6887 JS_DEBUG_PSGS("allowUnobservedAsmJS", getAllowUnobservedAsmJS,
6888 setAllowUnobservedAsmJS),
6889 JS_DEBUG_PSGS("allowUnobservedWasm", getAllowUnobservedWasm,
6890 setAllowUnobservedWasm),
6891 JS_DEBUG_PSGS("collectCoverageInfo", getCollectCoverageInfo,
6892 setCollectCoverageInfo),
6893 JS_DEBUG_PSGS("exclusiveDebuggerOnEval", getExclusiveDebuggerOnEval,
6894 setExclusiveDebuggerOnEval),
6895 JS_DEBUG_PSGS("inspectNativeCallArguments", getInspectNativeCallArguments,
6896 setInspectNativeCallArguments),
6897 JS_DEBUG_PSG("memory", getMemory),
6898 JS_STRING_SYM_PS(toStringTag, "Debugger", JSPROP_READONLY),
6899 JS_PS_END,
6900 };
6901
6902 const JSFunctionSpec Debugger::methods[] = {
6903 JS_DEBUG_FN("addDebuggee", addDebuggee, 1),
6904 JS_DEBUG_FN("addAllGlobalsAsDebuggees", addAllGlobalsAsDebuggees, 0),
6905 JS_DEBUG_FN("removeDebuggee", removeDebuggee, 1),
6906 JS_DEBUG_FN("removeAllDebuggees", removeAllDebuggees, 0),
6907 JS_DEBUG_FN("hasDebuggee", hasDebuggee, 1),
6908 JS_DEBUG_FN("getDebuggees", getDebuggees, 0),
6909 JS_DEBUG_FN("getNewestFrame", getNewestFrame, 0),
6910 JS_DEBUG_FN("clearAllBreakpoints", clearAllBreakpoints, 0),
6911 JS_DEBUG_FN("findScripts", findScripts, 1),
6912 JS_DEBUG_FN("findSources", findSources, 1),
6913 JS_DEBUG_FN("findObjects", findObjects, 1),
6914 JS_DEBUG_FN("findAllGlobals", findAllGlobals, 0),
6915 JS_DEBUG_FN("findSourceURLs", findSourceURLs, 0),
6916 JS_DEBUG_FN("makeGlobalObjectReference", makeGlobalObjectReference, 1),
6917 JS_DEBUG_FN("adoptDebuggeeValue", adoptDebuggeeValue, 1),
6918 JS_DEBUG_FN("adoptFrame", adoptFrame, 1),
6919 JS_DEBUG_FN("adoptSource", adoptSource, 1),
6920 JS_DEBUG_FN("enableAsyncStack", enableAsyncStack, 1),
6921 JS_DEBUG_FN("disableAsyncStack", disableAsyncStack, 1),
6922 JS_DEBUG_FN("enableUnlimitedStacksCapturing",
6923 enableUnlimitedStacksCapturing, 1),
6924 JS_DEBUG_FN("disableUnlimitedStacksCapturing",
6925 disableUnlimitedStacksCapturing, 1),
6926 JS_FS_END,
6927 };
6928
6929 const JSFunctionSpec Debugger::static_methods[]{
6930 JS_FN("isCompilableUnit", Debugger::isCompilableUnit, 1, 0),
6931 JS_FS_END,
6932 };
6933
6934 DebuggerScript* Debugger::newDebuggerScript(
6935 JSContext* cx, Handle<DebuggerScriptReferent> referent) {
6936 cx->check(object.get());
6937
6938 RootedObject proto(
6939 cx, &object->getReservedSlot(JSSLOT_DEBUG_SCRIPT_PROTO).toObject());
6940 MOZ_ASSERT(proto);
6941 Rooted<NativeObject*> debugger(cx, object);
6942
6943 return DebuggerScript::create(cx, proto, referent, debugger);
6944 }
6945
6946 template <typename ReferentType, typename Map>
6947 typename Map::WrapperType* Debugger::wrapVariantReferent(
6948 JSContext* cx, Map& map,
6949 Handle<typename Map::WrapperType::ReferentVariant> referent) {
6950 cx->check(object);
6951
6952 Handle<ReferentType*> untaggedReferent =
6953 referent.template as<ReferentType*>();
6954 MOZ_ASSERT(cx->compartment() != untaggedReferent->compartment());
6955
6956 DependentAddPtr<Map> p(cx, map, untaggedReferent);
6957 if (!p) {
6958 typename Map::WrapperType* wrapper = newVariantWrapper(cx, referent);
6959 if (!wrapper) {
6960 return nullptr;
6961 }
6962
6963 if (!p.add(cx, map, untaggedReferent, wrapper)) {
6964 // We need to destroy the edge to the referent, to avoid trying to trace
6965 // it during untimely collections.
6966 wrapper->clearReferent();
6967 return nullptr;
6968 }
6969 }
6970
6971 return &p->value()->template as<typename Map::WrapperType>();
6972 }
6973
6974 DebuggerScript* Debugger::wrapVariantReferent(
6975 JSContext* cx, Handle<DebuggerScriptReferent> referent) {
6976 if (referent.is<BaseScript*>()) {
6977 return wrapVariantReferent<BaseScript>(cx, scripts, referent);
6978 }
6979
6980 return wrapVariantReferent<WasmInstanceObject>(cx, wasmInstanceScripts,
6981 referent);
6982 }
6983
6984 DebuggerScript* Debugger::wrapScript(JSContext* cx,
6985 Handle<BaseScript*> script) {
6986 Rooted<DebuggerScriptReferent> referent(cx,
6987 DebuggerScriptReferent(script.get()));
6988 return wrapVariantReferent(cx, referent);
6989 }
6990
6991 DebuggerScript* Debugger::wrapWasmScript(
6992 JSContext* cx, Handle<WasmInstanceObject*> wasmInstance) {
6993 Rooted<DebuggerScriptReferent> referent(cx, wasmInstance.get());
6994 return wrapVariantReferent(cx, referent);
6995 }
6996
6997 DebuggerSource* Debugger::newDebuggerSource(
6998 JSContext* cx, Handle<DebuggerSourceReferent> referent) {
6999 cx->check(object.get());
7000
7001 RootedObject proto(
7002 cx, &object->getReservedSlot(JSSLOT_DEBUG_SOURCE_PROTO).toObject());
7003 MOZ_ASSERT(proto);
7004 Rooted<NativeObject*> debugger(cx, object);
7005 return DebuggerSource::create(cx, proto, referent, debugger);
7006 }
7007
7008 DebuggerSource* Debugger::wrapVariantReferent(
7009 JSContext* cx, Handle<DebuggerSourceReferent> referent) {
7010 DebuggerSource* obj;
7011 if (referent.is<ScriptSourceObject*>()) {
7012 obj = wrapVariantReferent<ScriptSourceObject>(cx, sources, referent);
7013 } else {
7014 obj = wrapVariantReferent<WasmInstanceObject>(cx, wasmInstanceSources,
7015 referent);
7016 }
7017 MOZ_ASSERT_IF(obj, obj->getReferent() == referent);
7018 return obj;
7019 }
7020
7021 DebuggerSource* Debugger::wrapSource(JSContext* cx,
7022 Handle<ScriptSourceObject*> source) {
7023 Rooted<DebuggerSourceReferent> referent(cx, source.get());
7024 return wrapVariantReferent(cx, referent);
7025 }
7026
7027 DebuggerSource* Debugger::wrapWasmSource(
7028 JSContext* cx, Handle<WasmInstanceObject*> wasmInstance) {
7029 Rooted<DebuggerSourceReferent> referent(cx, wasmInstance.get());
7030 return wrapVariantReferent(cx, referent);
7031 }
7032
7033 bool Debugger::observesFrame(AbstractFramePtr frame) const {
7034 if (frame.isWasmDebugFrame()) {
7035 return observesWasm(frame.wasmInstance());
7036 }
7037
7038 return observesScript(frame.script());
7039 }
7040
7041 bool Debugger::observesFrame(const FrameIter& iter) const {
7042 // Skip frames not yet fully initialized during their prologue.
7043 if (iter.isInterp() && iter.isFunctionFrame()) {
7044 const Value& thisVal = iter.interpFrame()->thisArgument();
7045 if (thisVal.isMagic() && thisVal.whyMagic() == JS_IS_CONSTRUCTING) {
7046 return false;
7047 }
7048 }
7049 if (iter.isWasm()) {
7050 // Skip frame of wasm instances we cannot observe.
7051 if (!iter.wasmDebugEnabled()) {
7052 return false;
7053 }
7054 return observesWasm(iter.wasmInstance());
7055 }
7056 return observesScript(iter.script());
7057 }
7058
7059 bool Debugger::observesScript(JSScript* script) const {
7060 // Don't ever observe self-hosted scripts: the Debugger API can break
7061 // self-hosted invariants.
7062 return observesGlobal(&script->global()) && !script->selfHosted();
7063 }
7064
7065 bool Debugger::observesWasm(wasm::Instance* instance) const {
7066 if (!instance->debugEnabled()) {
7067 return false;
7068 }
7069 return observesGlobal(&instance->object()->global());
7070 }
7071
7072 /* static */
7073 bool Debugger::replaceFrameGuts(JSContext* cx, AbstractFramePtr from,
7074 AbstractFramePtr to, ScriptFrameIter& iter) {
7075 MOZ_ASSERT(from != to);
7076
7077 // Rekey missingScopes to maintain Debugger.Environment identity and
7078 // forward liveScopes to point to the new frame.
7079 DebugEnvironments::forwardLiveFrame(cx, from, to);
7080
7081 // If we hit an OOM anywhere in here, we need to make sure there aren't any
7082 // Debugger.Frame objects left partially-initialized.
7083 auto terminateDebuggerFramesOnExit = MakeScopeExit([&] {
7084 terminateDebuggerFrames(cx, from);
7085 terminateDebuggerFrames(cx, to);
7086
7087 MOZ_ASSERT(!DebugAPI::inFrameMaps(from));
7088 MOZ_ASSERT(!DebugAPI::inFrameMaps(to));
7089 });
7090
7091 // Forward live Debugger.Frame objects.
7092 Rooted<DebuggerFrameVector> frames(cx);
7093 if (!getDebuggerFrames(from, &frames)) {
7094 // An OOM here means that all Debuggers' frame maps still contain
7095 // entries for 'from' and no entries for 'to'. Since the 'from' frame
7096 // will be gone, they are removed by terminateDebuggerFramesOnExit
7097 // above.
7098 ReportOutOfMemory(cx);
7099 return false;
7100 }
7101
7102 for (size_t i = 0; i < frames.length(); i++) {
7103 Handle<DebuggerFrame*> frameobj = frames[i];
7104 Debugger* dbg = frameobj->owner();
7105
7106 // Update frame object's ScriptFrameIter::data pointer.
7107 if (!frameobj->replaceFrameIterData(cx, iter)) {
7108 return false;
7109 }
7110
7111 // Add the frame object with |to| as key.
7112 if (!dbg->frames.putNew(to, frameobj)) {
7113 ReportOutOfMemory(cx);
7114 return false;
7115 }
7116
7117 // Remove the old frame entry after all fallible operations are completed
7118 // so that an OOM will be able to clean up properly.
7119 dbg->frames.remove(from);
7120 }
7121
7122 // All frames successfuly replaced, cancel the rollback.
7123 terminateDebuggerFramesOnExit.release();
7124
7125 MOZ_ASSERT(!DebugAPI::inFrameMaps(from));
7126 MOZ_ASSERT_IF(!frames.empty(), DebugAPI::inFrameMaps(to));
7127 return true;
7128 }
7129
7130 /* static */
7131 bool DebugAPI::inFrameMaps(AbstractFramePtr frame) {
7132 bool foundAny = false;
7133 JS::AutoAssertNoGC nogc;
7134 Debugger::forEachOnStackDebuggerFrame(
7135 frame, nogc,
7136 [&](Debugger*, DebuggerFrame* frameobj) { foundAny = true; });
7137 return foundAny;
7138 }
7139
7140 /* static */
7141 void Debugger::suspendGeneratorDebuggerFrames(JSContext* cx,
7142 AbstractFramePtr frame) {
7143 JS::GCContext* gcx = cx->gcContext();
7144 JS::AutoAssertNoGC nogc;
7145 forEachOnStackDebuggerFrame(
7146 frame, nogc, [&](Debugger* dbg, DebuggerFrame* dbgFrame) {
7147 dbg->frames.remove(frame);
7148
7149 #if DEBUG
7150 MOZ_ASSERT(dbgFrame->hasGeneratorInfo());
7151 AbstractGeneratorObject& genObj = dbgFrame->unwrappedGenerator();
7152 GeneratorWeakMap::Ptr p = dbg->generatorFrames.lookup(&genObj);
7153 MOZ_ASSERT(p);
7154 MOZ_ASSERT(p->value() == dbgFrame);
7155 #endif
7156
7157 dbgFrame->suspend(gcx);
7158 });
7159 }
7160
7161 /* static */
7162 void Debugger::terminateDebuggerFrames(JSContext* cx, AbstractFramePtr frame) {
7163 JS::GCContext* gcx = cx->gcContext();
7164
7165 JS::AutoAssertNoGC nogc;
7166 forEachOnStackOrSuspendedDebuggerFrame(
7167 cx, frame, nogc, [&](Debugger* dbg, DebuggerFrame* dbgFrame) {
7168 Debugger::terminateDebuggerFrame(gcx, dbg, dbgFrame, frame);
7169 });
7170
7171 // If this is an eval frame, then from the debugger's perspective the
7172 // script is about to be destroyed. Remove any breakpoints in it.
7173 if (frame.isEvalFrame()) {
7174 RootedScript script(cx, frame.script());
7175 DebugScript::clearBreakpointsIn(cx->gcContext(), script, nullptr, nullptr);
7176 }
7177 }
7178
7179 /* static */
7180 void Debugger::terminateDebuggerFrame(
7181 JS::GCContext* gcx, Debugger* dbg, DebuggerFrame* dbgFrame,
7182 AbstractFramePtr frame, FrameMap::Enum* maybeFramesEnum,
7183 GeneratorWeakMap::Enum* maybeGeneratorFramesEnum) {
7184 // If we were not passed the frame, either we are destroying a frame early
7185 // on before it was inserted into the "frames" list, or else we are
7186 // terminating a frame from "generatorFrames" and the "frames" entries will
7187 // be cleaned up later on with a second call to this function.
7188 MOZ_ASSERT_IF(!frame, !maybeFramesEnum);
7189 MOZ_ASSERT_IF(!frame, dbgFrame->hasGeneratorInfo());
7190 MOZ_ASSERT_IF(!dbgFrame->hasGeneratorInfo(), !maybeGeneratorFramesEnum);
7191
7192 if (frame) {
7193 if (maybeFramesEnum) {
7194 maybeFramesEnum->removeFront();
7195 } else {
7196 dbg->frames.remove(frame);
7197 }
7198 }
7199
7200 if (dbgFrame->hasGeneratorInfo()) {
7201 if (maybeGeneratorFramesEnum) {
7202 maybeGeneratorFramesEnum->removeFront();
7203 } else {
7204 dbg->generatorFrames.remove(&dbgFrame->unwrappedGenerator());
7205 }
7206 }
7207
7208 dbgFrame->terminate(gcx, frame);
7209 }
7210
7211 DebuggerDebuggeeLink* Debugger::getDebuggeeLink() {
7212 return &object->getReservedSlot(JSSLOT_DEBUG_DEBUGGEE_LINK)
7213 .toObject()
7214 .as<DebuggerDebuggeeLink>();
7215 }
7216
7217 void DebuggerDebuggeeLink::setLinkSlot(Debugger& dbg) {
7218 setReservedSlot(DEBUGGER_LINK_SLOT, ObjectValue(*dbg.toJSObject()));
7219 }
7220
7221 void DebuggerDebuggeeLink::clearLinkSlot() {
7222 setReservedSlot(DEBUGGER_LINK_SLOT, UndefinedValue());
7223 }
7224
7225 const JSClass DebuggerDebuggeeLink::class_ = {
7226 "DebuggerDebuggeeLink",
7227 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS),
7228 };
7229
7230 /* static */
7231 bool DebugAPI::handleBaselineOsr(JSContext* cx, InterpreterFrame* from,
7232 jit::BaselineFrame* to) {
7233 ScriptFrameIter iter(cx);
7234 MOZ_ASSERT(iter.abstractFramePtr() == to);
7235 return Debugger::replaceFrameGuts(cx, from, to, iter);
7236 }
7237
7238 /* static */
7239 bool DebugAPI::handleIonBailout(JSContext* cx, jit::RematerializedFrame* from,
7240 jit::BaselineFrame* to) {
7241 // When we return to a bailed-out Ion real frame, we must update all
7242 // Debugger.Frames that refer to its inline frames. However, since we
7243 // can't pop individual inline frames off the stack (we can only pop the
7244 // real frame that contains them all, as a unit), we cannot assume that
7245 // the frame we're dealing with is the top frame. Advance the iterator
7246 // across any inlined frames younger than |to|, the baseline frame
7247 // reconstructed during bailout from the Ion frame corresponding to
7248 // |from|.
7249 ScriptFrameIter iter(cx);
7250 while (iter.abstractFramePtr() != to) {
7251 ++iter;
7252 }
7253 return Debugger::replaceFrameGuts(cx, from, to, iter);
7254 }
7255
7256 /* static */
7257 void DebugAPI::handleUnrecoverableIonBailoutError(
7258 JSContext* cx, jit::RematerializedFrame* frame) {
7259 // Ion bailout can fail due to overrecursion. In such cases we cannot
7260 // honor any further Debugger hooks on the frame, and need to ensure that
7261 // its Debugger.Frame entry is cleaned up.
7262 Debugger::terminateDebuggerFrames(cx, frame);
7263 }
7264
7265 /*** JS::dbg::Builder *******************************************************/
7266
7267 Builder::Builder(JSContext* cx, js::Debugger* debugger)
7268 : debuggerObject(cx, debugger->toJSObject().get()), debugger(debugger) {}
7269
7270 #if DEBUG
7271 void Builder::assertBuilt(JSObject* obj) {
7272 // We can't use assertSameCompartment here, because that is always keyed to
7273 // some JSContext's current compartment, whereas BuiltThings can be
7274 // constructed and assigned to without respect to any particular context;
7275 // the only constraint is that they should be in their debugger's compartment.
7276 MOZ_ASSERT_IF(obj, debuggerObject->compartment() == obj->compartment());
7277 }
7278 #endif
7279
7280 bool Builder::Object::definePropertyToTrusted(JSContext* cx, const char* name,
7281 JS::MutableHandleValue trusted) {
7282 // We should have checked for false Objects before calling this.
7283 MOZ_ASSERT(value);
7284
7285 JSAtom* atom = Atomize(cx, name, strlen(name));
7286 if (!atom) {
7287 return false;
7288 }
7289 RootedId id(cx, AtomToId(atom));
7290
7291 return DefineDataProperty(cx, value, id, trusted);
7292 }
7293
7294 bool Builder::Object::defineProperty(JSContext* cx, const char* name,
7295 JS::HandleValue propval_) {
7296 AutoRealm ar(cx, debuggerObject());
7297
7298 RootedValue propval(cx, propval_);
7299 if (!debugger()->wrapDebuggeeValue(cx, &propval)) {
7300 return false;
7301 }
7302
7303 return definePropertyToTrusted(cx, name, &propval);
7304 }
7305
7306 bool Builder::Object::defineProperty(JSContext* cx, const char* name,
7307 JS::HandleObject propval_) {
7308 RootedValue propval(cx, ObjectOrNullValue(propval_));
7309 return defineProperty(cx, name, propval);
7310 }
7311
7312 bool Builder::Object::defineProperty(JSContext* cx, const char* name,
7313 Builder::Object& propval_) {
7314 AutoRealm ar(cx, debuggerObject());
7315
7316 RootedValue propval(cx, ObjectOrNullValue(propval_.value));
7317 return definePropertyToTrusted(cx, name, &propval);
7318 }
7319
7320 Builder::Object Builder::newObject(JSContext* cx) {
7321 AutoRealm ar(cx, debuggerObject);
7322
7323 Rooted<PlainObject*> obj(cx, NewPlainObject(cx));
7324
7325 // If the allocation failed, this will return a false Object, as the spec
7326 // promises.
7327 return Object(cx, *this, obj);
7328 }
7329
7330 /*** Glue *******************************************************************/
7331
7332 extern JS_PUBLIC_API bool JS_DefineDebuggerObject(JSContext* cx,
7333 HandleObject obj) {
7334 Rooted<NativeObject*> debugCtor(cx), debugProto(cx), frameProto(cx),
7335 scriptProto(cx), sourceProto(cx), objectProto(cx), envProto(cx),
7336 memoryProto(cx);
7337 RootedObject debuggeeWouldRunProto(cx);
7338 RootedValue debuggeeWouldRunCtor(cx);
7339 Handle<GlobalObject*> global = obj.as<GlobalObject>();
7340
7341 debugProto = InitClass(cx, global, &DebuggerPrototypeObject::class_, nullptr,
7342 "Debugger", Debugger::construct, 1,
7343 Debugger::properties, Debugger::methods, nullptr,
7344 Debugger::static_methods, debugCtor.address());
7345 if (!debugProto) {
7346 return false;
7347 }
7348
7349 frameProto = DebuggerFrame::initClass(cx, global, debugCtor);
7350 if (!frameProto) {
7351 return false;
7352 }
7353
7354 scriptProto = DebuggerScript::initClass(cx, global, debugCtor);
7355 if (!scriptProto) {
7356 return false;
7357 }
7358
7359 sourceProto = DebuggerSource::initClass(cx, global, debugCtor);
7360 if (!sourceProto) {
7361 return false;
7362 }
7363
7364 objectProto = DebuggerObject::initClass(cx, global, debugCtor);
7365 if (!objectProto) {
7366 return false;
7367 }
7368
7369 envProto = DebuggerEnvironment::initClass(cx, global, debugCtor);
7370 if (!envProto) {
7371 return false;
7372 }
7373
7374 memoryProto = InitClass(
7375 cx, debugCtor, nullptr, nullptr, "Memory", DebuggerMemory::construct, 0,
7376 DebuggerMemory::properties, DebuggerMemory::methods, nullptr, nullptr);
7377 if (!memoryProto) {
7378 return false;
7379 }
7380
7381 debuggeeWouldRunProto = GlobalObject::getOrCreateCustomErrorPrototype(
7382 cx, global, JSEXN_DEBUGGEEWOULDRUN);
7383 if (!debuggeeWouldRunProto) {
7384 return false;
7385 }
7386 debuggeeWouldRunCtor =
7387 ObjectValue(global->getConstructor(JSProto_DebuggeeWouldRun));
7388 RootedId debuggeeWouldRunId(
7389 cx, NameToId(ClassName(JSProto_DebuggeeWouldRun, cx)));
7390 if (!DefineDataProperty(cx, debugCtor, debuggeeWouldRunId,
7391 debuggeeWouldRunCtor, 0)) {
7392 return false;
7393 }
7394
7395 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_FRAME_PROTO,
7396 ObjectValue(*frameProto));
7397 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_OBJECT_PROTO,
7398 ObjectValue(*objectProto));
7399 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_SCRIPT_PROTO,
7400 ObjectValue(*scriptProto));
7401 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_SOURCE_PROTO,
7402 ObjectValue(*sourceProto));
7403 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_ENV_PROTO,
7404 ObjectValue(*envProto));
7405 debugProto->setReservedSlot(Debugger::JSSLOT_DEBUG_MEMORY_PROTO,
7406 ObjectValue(*memoryProto));
7407 return true;
7408 }
7409
7410 JS_PUBLIC_API bool JS::dbg::IsDebugger(JSObject& obj) {
7411 /* We only care about debugger objects, so CheckedUnwrapStatic is OK. */
7412 JSObject* unwrapped = CheckedUnwrapStatic(&obj);
7413 if (!unwrapped || !unwrapped->is<DebuggerInstanceObject>()) {
7414 return false;
7415 }
7416 MOZ_ASSERT(js::Debugger::fromJSObject(unwrapped));
7417 return true;
7418 }
7419
7420 JS_PUBLIC_API bool JS::dbg::GetDebuggeeGlobals(
7421 JSContext* cx, JSObject& dbgObj, MutableHandleObjectVector vector) {
7422 MOZ_ASSERT(IsDebugger(dbgObj));
7423 /* Since we know we have a debugger object, CheckedUnwrapStatic is fine. */
7424 js::Debugger* dbg = js::Debugger::fromJSObject(CheckedUnwrapStatic(&dbgObj));
7425
7426 if (!vector.reserve(vector.length() + dbg->debuggees.count())) {
7427 JS_ReportOutOfMemory(cx);
7428 return false;
7429 }
7430
7431 for (WeakGlobalObjectSet::Range r = dbg->allDebuggees(); !r.empty();
7432 r.popFront()) {
7433 vector.infallibleAppend(static_cast<JSObject*>(r.front()));
7434 }
7435
7436 return true;
7437 }
7438
7439 #ifdef DEBUG
7440 /* static */
7441 bool Debugger::isDebuggerCrossCompartmentEdge(JSObject* obj,
7442 const gc::Cell* target) {
7443 MOZ_ASSERT(target);
7444
7445 const gc::Cell* referent = nullptr;
7446 if (obj->is<DebuggerScript>()) {
7447 referent = obj->as<DebuggerScript>().getReferentCell();
7448 } else if (obj->is<DebuggerSource>()) {
7449 referent = obj->as<DebuggerSource>().getReferentRawObject();
7450 } else if (obj->is<DebuggerObject>()) {
7451 referent = obj->as<DebuggerObject>().referent();
7452 } else if (obj->is<DebuggerEnvironment>()) {
7453 referent = obj->as<DebuggerEnvironment>().referent();
7454 }
7455
7456 return referent == target;
7457 }
7458
7459 static void CheckDebuggeeThingRealm(Realm* realm, bool invisibleOk) {
7460 MOZ_ASSERT_IF(!invisibleOk, !realm->creationOptions().invisibleToDebugger());
7461 }
7462
7463 void js::CheckDebuggeeThing(BaseScript* script, bool invisibleOk) {
7464 CheckDebuggeeThingRealm(script->realm(), invisibleOk);
7465 }
7466
7467 void js::CheckDebuggeeThing(JSObject* obj, bool invisibleOk) {
7468 if (Realm* realm = JS::GetObjectRealmOrNull(obj)) {
7469 CheckDebuggeeThingRealm(realm, invisibleOk);
7470 }
7471 }
7472 #endif // DEBUG
7473
7474 /*** JS::dbg::GarbageCollectionEvent ****************************************/
7475
7476 namespace JS {
7477 namespace dbg {
7478
7479 /* static */ GarbageCollectionEvent::Ptr GarbageCollectionEvent::Create(
7480 JSRuntime* rt, ::js::gcstats::Statistics& stats, uint64_t gcNumber) {
7481 auto data = MakeUnique<GarbageCollectionEvent>(gcNumber);
7482 if (!data) {
7483 return nullptr;
7484 }
7485
7486 data->nonincrementalReason = stats.nonincrementalReason();
7487
7488 for (auto& slice : stats.slices()) {
7489 if (!data->reason) {
7490 // There is only one GC reason for the whole cycle, but for legacy
7491 // reasons this data is stored and replicated on each slice. Each
7492 // slice used to have its own GCReason, but now they are all the
7493 // same.
7494 data->reason = ExplainGCReason(slice.reason);
7495 MOZ_ASSERT(data->reason);
7496 }
7497
7498 if (!data->collections.growBy(1)) {
7499 return nullptr;
7500 }
7501
7502 data->collections.back().startTimestamp = slice.start;
7503 data->collections.back().endTimestamp = slice.end;
7504 }
7505
7506 return data;
7507 }
7508
7509 static bool DefineStringProperty(JSContext* cx, HandleObject obj,
7510 PropertyName* propName, const char* strVal) {
7511 RootedValue val(cx, UndefinedValue());
7512 if (strVal) {
7513 JSAtom* atomized = Atomize(cx, strVal, strlen(strVal));
7514 if (!atomized) {
7515 return false;
7516 }
7517 val = StringValue(atomized);
7518 }
7519 return DefineDataProperty(cx, obj, propName, val);
7520 }
7521
7522 JSObject* GarbageCollectionEvent::toJSObject(JSContext* cx) const {
7523 RootedObject obj(cx, NewPlainObject(cx));
7524 RootedValue gcCycleNumberVal(cx, NumberValue(majorGCNumber_));
7525 if (!obj ||
7526 !DefineStringProperty(cx, obj, cx->names().nonincrementalReason,
7527 nonincrementalReason) ||
7528 !DefineStringProperty(cx, obj, cx->names().reason, reason) ||
7529 !DefineDataProperty(cx, obj, cx->names().gcCycleNumber,
7530 gcCycleNumberVal)) {
7531 return nullptr;
7532 }
7533
7534 Rooted<ArrayObject*> slicesArray(cx, NewDenseEmptyArray(cx));
7535 if (!slicesArray) {
7536 return nullptr;
7537 }
7538
7539 TimeStamp originTime = TimeStamp::ProcessCreation();
7540
7541 size_t idx = 0;
7542 for (auto range = collections.all(); !range.empty(); range.popFront()) {
7543 Rooted<PlainObject*> collectionObj(cx, NewPlainObject(cx));
7544 if (!collectionObj) {
7545 return nullptr;
7546 }
7547
7548 RootedValue start(cx), end(cx);
7549 start = NumberValue(
7550 (range.front().startTimestamp - originTime).ToMilliseconds());
7551 end =
7552 NumberValue((range.front().endTimestamp - originTime).ToMilliseconds());
7553 if (!DefineDataProperty(cx, collectionObj, cx->names().startTimestamp,
7554 start) ||
7555 !DefineDataProperty(cx, collectionObj, cx->names().endTimestamp, end)) {
7556 return nullptr;
7557 }
7558
7559 RootedValue collectionVal(cx, ObjectValue(*collectionObj));
7560 if (!DefineDataElement(cx, slicesArray, idx++, collectionVal)) {
7561 return nullptr;
7562 }
7563 }
7564
7565 RootedValue slicesValue(cx, ObjectValue(*slicesArray));
7566 if (!DefineDataProperty(cx, obj, cx->names().collections, slicesValue)) {
7567 return nullptr;
7568 }
7569
7570 return obj;
7571 }
7572
7573 JS_PUBLIC_API bool FireOnGarbageCollectionHookRequired(JSContext* cx) {
7574 AutoCheckCannotGC noGC;
7575
7576 for (auto& dbg : cx->runtime()->onGarbageCollectionWatchers()) {
7577 MOZ_ASSERT(dbg.getHook(Debugger::OnGarbageCollection));
7578 if (dbg.observedGC(cx->runtime()->gc.majorGCCount())) {
7579 return true;
7580 }
7581 }
7582
7583 return false;
7584 }
7585
7586 JS_PUBLIC_API bool FireOnGarbageCollectionHook(
7587 JSContext* cx, JS::dbg::GarbageCollectionEvent::Ptr&& data) {
7588 RootedObjectVector triggered(cx);
7589
7590 {
7591 // We had better not GC (and potentially get a dangling Debugger
7592 // pointer) while finding all Debuggers observing a debuggee that
7593 // participated in this GC.
7594 AutoCheckCannotGC noGC;
7595
7596 for (auto& dbg : cx->runtime()->onGarbageCollectionWatchers()) {
7597 MOZ_ASSERT(dbg.getHook(Debugger::OnGarbageCollection));
7598 if (dbg.observedGC(data->majorGCNumber())) {
7599 if (!triggered.append(dbg.object)) {
7600 JS_ReportOutOfMemory(cx);
7601 return false;
7602 }
7603 }
7604 }
7605 }
7606
7607 for (; !triggered.empty(); triggered.popBack()) {
7608 Debugger* dbg = Debugger::fromJSObject(triggered.back());
7609
7610 if (dbg->getHook(Debugger::OnGarbageCollection)) {
7611 (void)dbg->enterDebuggerHook(cx, [&]() -> bool {
7612 return dbg->fireOnGarbageCollectionHook(cx, data);
7613 });
7614 MOZ_ASSERT(!cx->isExceptionPending());
7615 }
7616 }
7617
7618 return true;
7619 }
7620
7621 bool ShouldAvoidSideEffects(JSContext* cx) {
7622 return DebugAPI::shouldAvoidSideEffects(cx);
7623 }
7624
7625 } // namespace dbg
7626 } // namespace JS