Debian Codegraph @

js/src/debugger/Script.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/Script-inl.h"
8
9 #include "mozilla/Maybe.h" // for Some, Maybe
10 #include "mozilla/Span.h" // for Span
11 #include "mozilla/Vector.h" // for Vector
12
13 #include <stddef.h> // for ptrdiff_t
14 #include <stdint.h> // for uint32_t, UINT32_MAX, SIZE_MAX, int32_t
15
16 #include "jsnum.h" // for ToNumber
17 #include "NamespaceImports.h" // for CallArgs, RootedValue
18
19 #include "builtin/Array.h" // for NewDenseEmptyArray
20 #include "debugger/Debugger.h" // for DebuggerScriptReferent, Debugger
21 #include "debugger/DebugScript.h" // for DebugScript
22 #include "debugger/Source.h" // for DebuggerSource
23 #include "gc/GC.h" // for MemoryUse, MemoryUse::Breakpoint
24 #include "gc/Tracer.h" // for TraceManuallyBarrieredCrossCompartmentEdge
25 #include "gc/Zone.h" // for Zone
26 #include "gc/ZoneAllocator.h" // for AddCellMemory
27 #include "js/CallArgs.h" // for CallArgs, CallArgsFromVp
28 #include "js/ColumnNumber.h" // JS::LimitedColumnNumberOneOrigin, JS::WasmFunctionIndex
29 #include "js/friend/ErrorMessages.h" // for GetErrorMessage, JSMSG_*
30 #include "js/GCVariant.h" // for GCVariant
31 #include "js/HeapAPI.h" // for GCCellPtr
32 #include "js/RootingAPI.h" // for Rooted
33 #include "js/Wrapper.h" // for UncheckedUnwrap
34 #include "vm/ArrayObject.h" // for ArrayObject
35 #include "vm/BytecodeUtil.h" // for GET_JUMP_OFFSET
36 #include "vm/Compartment.h" // for JS::Compartment
37 #include "vm/EnvironmentObject.h" // for EnvironmentCoordinateNameSlow
38 #include "vm/GlobalObject.h" // for GlobalObject
39 #include "vm/JSContext.h" // for JSContext, ReportValueError
40 #include "vm/JSFunction.h" // for JSFunction
41 #include "vm/JSObject.h" // for RequireObject, JSObject
42 #include "vm/JSScript.h" // for BaseScript
43 #include "vm/ObjectOperations.h" // for DefineDataProperty, HasOwnProperty
44 #include "vm/PlainObject.h" // for js::PlainObject
45 #include "vm/Realm.h" // for AutoRealm
46 #include "vm/Runtime.h" // for JSAtomState, JSRuntime
47 #include "vm/StringType.h" // for NameToId, PropertyName, JSAtom
48 #include "wasm/WasmDebug.h" // for ExprLoc, DebugState
49 #include "wasm/WasmInstance.h" // for Instance
50 #include "wasm/WasmJS.h" // for WasmInstanceObject
51 #include "wasm/WasmTypeDecls.h" // for Bytes
52
53 #include "gc/Marking-inl.h" // for MaybeForwardedObjectIs
54 #include "vm/BytecodeUtil-inl.h" // for BytecodeRangeWithPosition
55 #include "vm/JSAtomUtils-inl.h" // for PrimitiveValueToId
56 #include "vm/JSObject-inl.h" // for NewBuiltinClassInstance, NewObjectWithGivenProto, NewTenuredObjectWithGivenProto
57 #include "vm/JSScript-inl.h" // for JSScript::global
58 #include "vm/ObjectOperations-inl.h" // for GetProperty
59 #include "vm/Realm-inl.h" // for AutoRealm::AutoRealm
60
61 using namespace js;
62
63 using mozilla::Maybe;
64 using mozilla::Some;
65
66 const JSClassOps DebuggerScript::classOps_ = {
67 nullptr, // addProperty
68 nullptr, // delProperty
69 nullptr, // enumerate
70 nullptr, // newEnumerate
71 nullptr, // resolve
72 nullptr, // mayResolve
73 nullptr, // finalize
74 nullptr, // call
75 nullptr, // construct
76 CallTraceMethod<DebuggerScript>, // trace
77 };
78
79 const JSClass DebuggerScript::class_ = {
80 "Script",
81 JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS),
82 &classOps_,
83 };
84
85 void DebuggerScript::trace(JSTracer* trc) {
86 // This comes from a private pointer, so no barrier needed.
87 gc::Cell* cell = getReferentCell();
88 if (cell) {
89 if (cell->is<BaseScript>()) {
90 BaseScript* script = cell->as<BaseScript>();
91 TraceManuallyBarrieredCrossCompartmentEdge(
92 trc, this, &script, "Debugger.Script script referent");
93 if (script != cell->as<BaseScript>()) {
94 setReservedSlotGCThingAsPrivateUnbarriered(SCRIPT_SLOT, script);
95 }
96 } else {
97 JSObject* wasm = cell->as<JSObject>();
98 TraceManuallyBarrieredCrossCompartmentEdge(
99 trc, this, &wasm, "Debugger.Script wasm referent");
100 if (wasm != cell->as<JSObject>()) {
101 MOZ_ASSERT(gc::MaybeForwardedObjectIs<WasmInstanceObject>(wasm));
102 setReservedSlotGCThingAsPrivateUnbarriered(SCRIPT_SLOT, wasm);
103 }
104 }
105 }
106 }
107
108 /* static */
109 NativeObject* DebuggerScript::initClass(JSContext* cx,
110 Handle<GlobalObject*> global,
111 HandleObject debugCtor) {
112 return InitClass(cx, debugCtor, nullptr, nullptr, "Script", construct, 0,
113 properties_, methods_, nullptr, nullptr);
114 }
115
116 /* static */
117 DebuggerScript* DebuggerScript::create(JSContext* cx, HandleObject proto,
118 Handle<DebuggerScriptReferent> referent,
119 Handle<NativeObject*> debugger) {
120 DebuggerScript* scriptobj =
121 NewTenuredObjectWithGivenProto<DebuggerScript>(cx, proto);
122 if (!scriptobj) {
123 return nullptr;
124 }
125
126 scriptobj->setReservedSlot(DebuggerScript::OWNER_SLOT,
127 ObjectValue(*debugger));
128 referent.get().match([&](auto& scriptHandle) {
129 scriptobj->setReservedSlotGCThingAsPrivate(SCRIPT_SLOT, scriptHandle);
130 });
131
132 return scriptobj;
133 }
134
135 static JSScript* DelazifyScript(JSContext* cx, Handle<BaseScript*> script) {
136 if (script->hasBytecode()) {
137 return script->asJSScript();
138 }
139 MOZ_ASSERT(script->isFunction());
140
141 // JSFunction::getOrCreateScript requires an enclosing scope. This requires
142 // the enclosing script to be non-lazy.
143 if (script->hasEnclosingScript()) {
144 Rooted<BaseScript*> enclosingScript(cx, script->enclosingScript());
145 if (!DelazifyScript(cx, enclosingScript)) {
146 return nullptr;
147 }
148
149 if (!script->isReadyForDelazification()) {
150 // It didn't work! Delazifying the enclosing script still didn't
151 // delazify this script. This happens when the function
152 // corresponding to this script was removed by constant folding.
153 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
154 JSMSG_DEBUG_OPTIMIZED_OUT_FUN);
155 return nullptr;
156 }
157 }
158
159 MOZ_ASSERT(script->enclosingScope());
160
161 RootedFunction fun(cx, script->function());
162 AutoRealm ar(cx, fun);
163 return JSFunction::getOrCreateScript(cx, fun);
164 }
165
166 /* static */
167 DebuggerScript* DebuggerScript::check(JSContext* cx, HandleValue v) {
168 JSObject* thisobj = RequireObject(cx, v);
169 if (!thisobj) {
170 return nullptr;
171 }
172 if (!thisobj->is<DebuggerScript>()) {
173 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
174 JSMSG_INCOMPATIBLE_PROTO, "Debugger.Script",
175 "method", thisobj->getClass()->name);
176 return nullptr;
177 }
178
179 return &thisobj->as<DebuggerScript>();
180 }
181
182 struct MOZ_STACK_CLASS DebuggerScript::CallData {
183 JSContext* cx;
184 const CallArgs& args;
185
186 Handle<DebuggerScript*> obj;
187 Rooted<DebuggerScriptReferent> referent;
188 RootedScript script;
189
190 CallData(JSContext* cx, const CallArgs& args, Handle<DebuggerScript*> obj)
191 : cx(cx),
192 args(args),
193 obj(obj),
194 referent(cx, obj->getReferent()),
195 script(cx) {}
196
197 [[nodiscard]] bool ensureScriptMaybeLazy() {
198 if (!referent.is<BaseScript*>()) {
199 ReportValueError(cx, JSMSG_DEBUG_BAD_REFERENT, JSDVG_SEARCH_STACK,
200 args.thisv(), nullptr, "a JS script");
201 return false;
202 }
203 return true;
204 }
205
206 [[nodiscard]] bool ensureScript() {
207 if (!ensureScriptMaybeLazy()) {
208 return false;
209 }
210 script = DelazifyScript(cx, referent.as<BaseScript*>());
211 if (!script) {
212 return false;
213 }
214 return true;
215 }
216
217 bool getIsGeneratorFunction();
218 bool getIsAsyncFunction();
219 bool getIsFunction();
220 bool getIsModule();
221 bool getDisplayName();
222 bool getParameterNames();
223 bool getUrl();
224 bool getStartLine();
225 bool getStartColumn();
226 bool getLineCount();
227 bool getSource();
228 bool getSourceStart();
229 bool getSourceLength();
230 bool getMainOffset();
231 bool getGlobal();
232 bool getFormat();
233 bool getChildScripts();
234 bool getPossibleBreakpoints();
235 bool getPossibleBreakpointOffsets();
236 bool getOffsetMetadata();
237 bool getOffsetLocation();
238 bool getEffectfulOffsets();
239 bool getAllOffsets();
240 bool getAllColumnOffsets();
241 bool getLineOffsets();
242 bool setBreakpoint();
243 bool getBreakpoints();
244 bool clearBreakpoint();
245 bool clearAllBreakpoints();
246 bool isInCatchScope();
247 bool getOffsetsCoverage();
248
249 using Method = bool (CallData::*)();
250
251 template <Method MyMethod>
252 static bool ToNative(JSContext* cx, unsigned argc, Value* vp);
253 };
254
255 template <DebuggerScript::CallData::Method MyMethod>
256 /* static */
257 bool DebuggerScript::CallData::ToNative(JSContext* cx, unsigned argc,
258 Value* vp) {
259 CallArgs args = CallArgsFromVp(argc, vp);
260
261 Rooted<DebuggerScript*> obj(cx, DebuggerScript::check(cx, args.thisv()));
262 if (!obj) {
263 return false;
264 }
265
266 CallData data(cx, args, obj);
267 return (data.*MyMethod)();
268 }
269
270 bool DebuggerScript::CallData::getIsGeneratorFunction() {
271 if (!ensureScriptMaybeLazy()) {
272 return false;
273 }
274 args.rval().setBoolean(obj->getReferentScript()->isGenerator());
275 return true;
276 }
277
278 bool DebuggerScript::CallData::getIsAsyncFunction() {
279 if (!ensureScriptMaybeLazy()) {
280 return false;
281 }
282 args.rval().setBoolean(obj->getReferentScript()->isAsync());
283 return true;
284 }
285
286 bool DebuggerScript::CallData::getIsFunction() {
287 if (!ensureScriptMaybeLazy()) {
288 return false;
289 }
290
291 args.rval().setBoolean(obj->getReferentScript()->function());
292 return true;
293 }
294
295 bool DebuggerScript::CallData::getIsModule() {
296 if (!ensureScriptMaybeLazy()) {
297 return false;
298 }
299 BaseScript* script = referent.as<BaseScript*>();
300
301 args.rval().setBoolean(script->isModule());
302 return true;
303 }
304
305 bool DebuggerScript::CallData::getDisplayName() {
306 if (!ensureScriptMaybeLazy()) {
307 return false;
308 }
309
310 JSFunction* func = obj->getReferentScript()->function();
311 if (!func) {
312 args.rval().setUndefined();
313 return true;
314 }
315
316 JSAtom* name = func->fullDisplayAtom();
317 if (!name) {
318 args.rval().setUndefined();
319 return true;
320 }
321
322 RootedValue namev(cx, StringValue(name));
323 Debugger* dbg = obj->owner();
324 if (!dbg->wrapDebuggeeValue(cx, &namev)) {
325 return false;
326 }
327 args.rval().set(namev);
328 return true;
329 }
330
331 bool DebuggerScript::CallData::getParameterNames() {
332 if (!ensureScript()) {
333 return false;
334 }
335
336 RootedFunction fun(cx, referent.as<BaseScript*>()->function());
337 if (!fun) {
338 args.rval().setUndefined();
339 return true;
340 }
341
342 ArrayObject* arr = GetFunctionParameterNamesArray(cx, fun);
343 if (!arr) {
344 return false;
345 }
346
347 args.rval().setObject(*arr);
348 return true;
349 }
350
351 bool DebuggerScript::CallData::getUrl() {
352 if (!ensureScriptMaybeLazy()) {
353 return false;
354 }
355
356 Rooted<BaseScript*> script(cx, referent.as<BaseScript*>());
357
358 if (script->filename()) {
359 JSString* str;
360 if (const char* introducer = script->scriptSource()->introducerFilename()) {
361 str =
362 NewStringCopyUTF8N(cx, JS::UTF8Chars(introducer, strlen(introducer)));
363 } else {
364 const char* filename = script->filename();
365 str = NewStringCopyUTF8N(cx, JS::UTF8Chars(filename, strlen(filename)));
366 }
367 if (!str) {
368 return false;
369 }
370 args.rval().setString(str);
371 } else {
372 args.rval().setNull();
373 }
374 return true;
375 }
376
377 bool DebuggerScript::CallData::getStartLine() {
378 args.rval().setNumber(
379 referent.get().match([](BaseScript*& s) { return s->lineno(); },
380 [](WasmInstanceObject*&) { return (uint32_t)1; }));
381 return true;
382 }
383
384 bool DebuggerScript::CallData::getStartColumn() {
385 JS::LimitedColumnNumberOneOrigin column = referent.get().match(
386 [](BaseScript*& s) { return s->column(); },
387 [](WasmInstanceObject*&) {
388 return JS::LimitedColumnNumberOneOrigin(
389 JS::WasmFunctionIndex::DefaultBinarySourceColumnNumberOneOrigin);
390 });
391 args.rval().setNumber(column.oneOriginValue());
392 return true;
393 }
394
395 struct DebuggerScript::GetLineCountMatcher {
396 JSContext* cx_;
397 double totalLines;
398
399 explicit GetLineCountMatcher(JSContext* cx) : cx_(cx), totalLines(0.0) {}
400 using ReturnType = bool;
401
402 ReturnType match(Handle<BaseScript*> base) {
403 RootedScript script(cx_, DelazifyScript(cx_, base));
404 if (!script) {
405 return false;
406 }
407 totalLines = double(GetScriptLineExtent(script));
408 return true;
409 }
410 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
411 wasm::Instance& instance = instanceObj->instance();
412 if (instance.debugEnabled()) {
413 totalLines = double(instance.debug().bytecode().length());
414 } else {
415 totalLines = 0;
416 }
417 return true;
418 }
419 };
420
421 bool DebuggerScript::CallData::getLineCount() {
422 GetLineCountMatcher matcher(cx);
423 if (!referent.match(matcher)) {
424 return false;
425 }
426 args.rval().setNumber(matcher.totalLines);
427 return true;
428 }
429
430 class DebuggerScript::GetSourceMatcher {
431 JSContext* cx_;
432 Debugger* dbg_;
433
434 public:
435 GetSourceMatcher(JSContext* cx, Debugger* dbg) : cx_(cx), dbg_(dbg) {}
436
437 using ReturnType = DebuggerSource*;
438
439 ReturnType match(Handle<BaseScript*> script) {
440 Rooted<ScriptSourceObject*> source(cx_, script->sourceObject());
441 return dbg_->wrapSource(cx_, source);
442 }
443 ReturnType match(Handle<WasmInstanceObject*> wasmInstance) {
444 return dbg_->wrapWasmSource(cx_, wasmInstance);
445 }
446 };
447
448 bool DebuggerScript::CallData::getSource() {
449 Debugger* dbg = obj->owner();
450
451 GetSourceMatcher matcher(cx, dbg);
452 Rooted<DebuggerSource*> sourceObject(cx, referent.match(matcher));
453 if (!sourceObject) {
454 return false;
455 }
456
457 args.rval().setObject(*sourceObject);
458 return true;
459 }
460
461 bool DebuggerScript::CallData::getSourceStart() {
462 if (!ensureScriptMaybeLazy()) {
463 return false;
464 }
465 args.rval().setNumber(uint32_t(obj->getReferentScript()->sourceStart()));
466 return true;
467 }
468
469 bool DebuggerScript::CallData::getSourceLength() {
470 if (!ensureScriptMaybeLazy()) {
471 return false;
472 }
473 args.rval().setNumber(uint32_t(obj->getReferentScript()->sourceLength()));
474 return true;
475 }
476
477 bool DebuggerScript::CallData::getMainOffset() {
478 if (!ensureScript()) {
479 return false;
480 }
481 args.rval().setNumber(uint32_t(script->mainOffset()));
482 return true;
483 }
484
485 bool DebuggerScript::CallData::getGlobal() {
486 if (!ensureScript()) {
487 return false;
488 }
489 Debugger* dbg = obj->owner();
490
491 RootedValue v(cx, ObjectValue(script->global()));
492 if (!dbg->wrapDebuggeeValue(cx, &v)) {
493 return false;
494 }
495 args.rval().set(v);
496 return true;
497 }
498
499 bool DebuggerScript::CallData::getFormat() {
500 args.rval().setString(referent.get().match(
501 [this](BaseScript*&) { return cx->names().js.get(); },
502 [this](WasmInstanceObject*&) { return cx->names().wasm.get(); }));
503 return true;
504 }
505
506 static bool PushFunctionScript(JSContext* cx, Debugger* dbg, HandleFunction fun,
507 HandleObject array) {
508 // Ignore asm.js natives.
509 if (!IsInterpretedNonSelfHostedFunction(fun)) {
510 return true;
511 }
512
513 Rooted<BaseScript*> script(cx, fun->baseScript());
514 MOZ_ASSERT(script);
515 if (!script) {
516 // If the function doesn't have script, ignore it.
517 return true;
518 }
519 RootedObject wrapped(cx, dbg->wrapScript(cx, script));
520 if (!wrapped) {
521 return false;
522 }
523
524 return NewbornArrayPush(cx, array, ObjectValue(*wrapped));
525 }
526
527 static bool PushInnerFunctions(JSContext* cx, Debugger* dbg, HandleObject array,
528 mozilla::Span<const JS::GCCellPtr> gcThings) {
529 RootedFunction fun(cx);
530
531 for (JS::GCCellPtr gcThing : gcThings) {
532 if (!gcThing.is<JSObject>()) {
533 continue;
534 }
535
536 JSObject* obj = &gcThing.as<JSObject>();
537 if (obj->is<JSFunction>()) {
538 fun = &obj->as<JSFunction>();
539
540 // Ignore any delazification placeholder functions. These should not be
541 // exposed to debugger in any way.
542 if (fun->isGhost()) {
543 continue;
544 }
545
546 if (!PushFunctionScript(cx, dbg, fun, array)) {
547 return false;
548 }
549 }
550 }
551
552 return true;
553 }
554
555 bool DebuggerScript::CallData::getChildScripts() {
556 if (!ensureScriptMaybeLazy()) {
557 return false;
558 }
559 Debugger* dbg = obj->owner();
560
561 RootedObject result(cx, NewDenseEmptyArray(cx));
562 if (!result) {
563 return false;
564 }
565
566 Rooted<BaseScript*> script(cx, obj->getReferent().as<BaseScript*>());
567 if (!PushInnerFunctions(cx, dbg, result, script->gcthings())) {
568 return false;
569 }
570
571 args.rval().setObject(*result);
572 return true;
573 }
574
575 static bool ScriptOffset(JSContext* cx, const Value& v, size_t* offsetp) {
576 double d;
577 size_t off;
578
579 bool ok = v.isNumber();
580 if (ok) {
581 d = v.toNumber();
582 off = size_t(d);
583 }
584 if (!ok || off != d) {
585 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
586 JSMSG_DEBUG_BAD_OFFSET);
587 return false;
588 }
589 *offsetp = off;
590 return true;
591 }
592
593 static bool EnsureScriptOffsetIsValid(JSContext* cx, JSScript* script,
594 size_t offset) {
595 if (IsValidBytecodeOffset(cx, script, offset)) {
596 return true;
597 }
598 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
599 JSMSG_DEBUG_BAD_OFFSET);
600 return false;
601 }
602
603 static bool IsGeneratorSlotInitialization(JSScript* script, size_t offset,
604 JSContext* cx) {
605 jsbytecode* pc = script->offsetToPC(offset);
606 if (JSOp(*pc) != JSOp::SetAliasedVar) {
607 return false;
608 }
609
610 PropertyName* name = EnvironmentCoordinateNameSlow(script, pc);
611 return name == cx->names().dot_generator_;
612 }
613
614 static bool EnsureBreakpointIsAllowed(JSContext* cx, JSScript* script,
615 size_t offset) {
616 // Disallow breakpoint for `JSOp::SetAliasedVar` after `JSOp::Generator`.
617 // Those 2 instructions are supposed to be atomic, and nothing should happen
618 // in between them.
619 //
620 // Hitting a breakpoint there breaks the assumption around the existence of
621 // the frame's `GeneratorInfo`.
622 // (see `DebugAPI::slowPathOnNewGenerator` and `DebuggerFrame::create`)
623 if (IsGeneratorSlotInitialization(script, offset, cx)) {
624 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
625 JSMSG_DEBUG_BREAKPOINT_NOT_ALLOWED);
626 return false;
627 }
628
629 return true;
630 }
631
632 template <bool OnlyOffsets>
633 class DebuggerScript::GetPossibleBreakpointsMatcher {
634 JSContext* cx_;
635 MutableHandleObject result_;
636
637 Maybe<size_t> minOffset;
638 Maybe<size_t> maxOffset;
639
640 Maybe<uint32_t> minLine;
641 JS::LimitedColumnNumberOneOrigin minColumn;
642 Maybe<uint32_t> maxLine;
643 JS::LimitedColumnNumberOneOrigin maxColumn;
644
645 bool passesQuery(size_t offset, uint32_t lineno,
646 JS::LimitedColumnNumberOneOrigin colno) {
647 // [minOffset, maxOffset) - Inclusive minimum and exclusive maximum.
648 if ((minOffset && offset < *minOffset) ||
649 (maxOffset && offset >= *maxOffset)) {
650 return false;
651 }
652
653 if (minLine) {
654 if (lineno < *minLine || (lineno == *minLine && colno < minColumn)) {
655 return false;
656 }
657 }
658
659 if (maxLine) {
660 if (lineno > *maxLine || (lineno == *maxLine && colno >= maxColumn)) {
661 return false;
662 }
663 }
664
665 return true;
666 }
667
668 bool maybeAppendEntry(size_t offset, uint32_t lineno,
669 JS::LimitedColumnNumberOneOrigin colno,
670 bool isStepStart) {
671 if (!passesQuery(offset, lineno, colno)) {
672 return true;
673 }
674
675 if (OnlyOffsets) {
676 if (!NewbornArrayPush(cx_, result_, NumberValue(offset))) {
677 return false;
678 }
679
680 return true;
681 }
682
683 Rooted<PlainObject*> entry(cx_, NewPlainObject(cx_));
684 if (!entry) {
685 return false;
686 }
687
688 RootedValue value(cx_, NumberValue(offset));
689 if (!DefineDataProperty(cx_, entry, cx_->names().offset, value)) {
690 return false;
691 }
692
693 value = NumberValue(lineno);
694 if (!DefineDataProperty(cx_, entry, cx_->names().lineNumber, value)) {
695 return false;
696 }
697
698 value = NumberValue(colno.oneOriginValue());
699 if (!DefineDataProperty(cx_, entry, cx_->names().columnNumber, value)) {
700 return false;
701 }
702
703 value = BooleanValue(isStepStart);
704 if (!DefineDataProperty(cx_, entry, cx_->names().isStepStart, value)) {
705 return false;
706 }
707
708 if (!NewbornArrayPush(cx_, result_, ObjectValue(*entry))) {
709 return false;
710 }
711 return true;
712 }
713
714 template <typename T>
715 bool parseIntValueImpl(HandleValue value, T* result) {
716 if (!value.isNumber()) {
717 return false;
718 }
719
720 double doubleOffset = value.toNumber();
721 if (doubleOffset < 0 || (unsigned int)doubleOffset != doubleOffset) {
722 return false;
723 }
724
725 *result = doubleOffset;
726 return true;
727 }
728
729 bool parseUint32Value(HandleValue value, uint32_t* result) {
730 return parseIntValueImpl(value, result);
731 }
732 bool parseColumnValue(HandleValue value,
733 JS::LimitedColumnNumberOneOrigin* result) {
734 uint32_t tmp;
735 if (!parseIntValueImpl(value, &tmp)) {
736 return false;
737 }
738 if (tmp == 0) {
739 return false;
740 }
741 *result->addressOfValueForTranscode() = tmp;
742 if (!result->valid()) {
743 return false;
744 }
745 return true;
746 }
747 bool parseSizeTValue(HandleValue value, size_t* result) {
748 return parseIntValueImpl(value, result);
749 }
750
751 template <typename T>
752 bool parseIntValueMaybeImpl(HandleValue value, Maybe<T>* result) {
753 T result_;
754 if (!parseIntValueImpl(value, &result_)) {
755 return false;
756 }
757
758 *result = Some(result_);
759 return true;
760 }
761
762 bool parseUint32Value(HandleValue value, Maybe<uint32_t>* result) {
763 return parseIntValueMaybeImpl(value, result);
764 }
765 bool parseSizeTValue(HandleValue value, Maybe<size_t>* result) {
766 return parseIntValueMaybeImpl(value, result);
767 }
768
769 public:
770 explicit GetPossibleBreakpointsMatcher(JSContext* cx,
771 MutableHandleObject result)
772 : cx_(cx), result_(result) {}
773
774 bool parseQuery(HandleObject query) {
775 RootedValue lineValue(cx_);
776 if (!GetProperty(cx_, query, query, cx_->names().line, &lineValue)) {
777 return false;
778 }
779
780 RootedValue minLineValue(cx_);
781 if (!GetProperty(cx_, query, query, cx_->names().minLine, &minLineValue)) {
782 return false;
783 }
784
785 RootedValue minColumnValue(cx_);
786 if (!GetProperty(cx_, query, query, cx_->names().minColumn,
787 &minColumnValue)) {
788 return false;
789 }
790
791 RootedValue minOffsetValue(cx_);
792 if (!GetProperty(cx_, query, query, cx_->names().minOffset,
793 &minOffsetValue)) {
794 return false;
795 }
796
797 RootedValue maxLineValue(cx_);
798 if (!GetProperty(cx_, query, query, cx_->names().maxLine, &maxLineValue)) {
799 return false;
800 }
801
802 RootedValue maxColumnValue(cx_);
803 if (!GetProperty(cx_, query, query, cx_->names().maxColumn,
804 &maxColumnValue)) {
805 return false;
806 }
807
808 RootedValue maxOffsetValue(cx_);
809 if (!GetProperty(cx_, query, query, cx_->names().maxOffset,
810 &maxOffsetValue)) {
811 return false;
812 }
813
814 if (!minOffsetValue.isUndefined()) {
815 if (!parseSizeTValue(minOffsetValue, &minOffset)) {
816 JS_ReportErrorNumberASCII(
817 cx_, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
818 "getPossibleBreakpoints' 'minOffset'", "not an integer");
819 return false;
820 }
821 }
822 if (!maxOffsetValue.isUndefined()) {
823 if (!parseSizeTValue(maxOffsetValue, &maxOffset)) {
824 JS_ReportErrorNumberASCII(
825 cx_, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
826 "getPossibleBreakpoints' 'maxOffset'", "not an integer");
827 return false;
828 }
829 }
830
831 if (!lineValue.isUndefined()) {
832 if (!minLineValue.isUndefined() || !maxLineValue.isUndefined()) {
833 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
834 JSMSG_UNEXPECTED_TYPE,
835 "getPossibleBreakpoints' 'line'",
836 "not allowed alongside 'minLine'/'maxLine'");
837 return false;
838 }
839
840 uint32_t line;
841 if (!parseUint32Value(lineValue, &line)) {
842 JS_ReportErrorNumberASCII(
843 cx_, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
844 "getPossibleBreakpoints' 'line'", "not an integer");
845 return false;
846 }
847
848 // If no end column is given, we use the default of 0 and wrap to
849 // the next line.
850 minLine = Some(line);
851 maxLine = Some(line + (maxColumnValue.isUndefined() ? 1 : 0));
852 }
853
854 if (!minLineValue.isUndefined()) {
855 if (!parseUint32Value(minLineValue, &minLine)) {
856 JS_ReportErrorNumberASCII(
857 cx_, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
858 "getPossibleBreakpoints' 'minLine'", "not an integer");
859 return false;
860 }
861 }
862
863 if (!minColumnValue.isUndefined()) {
864 if (!minLine) {
865 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
866 JSMSG_UNEXPECTED_TYPE,
867 "getPossibleBreakpoints' 'minColumn'",
868 "not allowed without 'line' or 'minLine'");
869 return false;
870 }
871
872 if (!parseColumnValue(minColumnValue, &minColumn)) {
873 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
874 JSMSG_UNEXPECTED_TYPE,
875 "getPossibleBreakpoints' 'minColumn'",
876 "not a positive integer in valid range");
877 return false;
878 }
879 }
880
881 if (!maxLineValue.isUndefined()) {
882 if (!parseUint32Value(maxLineValue, &maxLine)) {
883 JS_ReportErrorNumberASCII(
884 cx_, GetErrorMessage, nullptr, JSMSG_UNEXPECTED_TYPE,
885 "getPossibleBreakpoints' 'maxLine'", "not an integer");
886 return false;
887 }
888 }
889
890 if (!maxColumnValue.isUndefined()) {
891 if (!maxLine) {
892 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
893 JSMSG_UNEXPECTED_TYPE,
894 "getPossibleBreakpoints' 'maxColumn'",
895 "not allowed without 'line' or 'maxLine'");
896 return false;
897 }
898
899 if (!parseColumnValue(maxColumnValue, &maxColumn)) {
900 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
901 JSMSG_UNEXPECTED_TYPE,
902 "getPossibleBreakpoints' 'maxColumn'",
903 "not a positive integer in valid range");
904 return false;
905 }
906 }
907
908 return true;
909 }
910
911 using ReturnType = bool;
912 ReturnType match(Handle<BaseScript*> base) {
913 RootedScript script(cx_, DelazifyScript(cx_, base));
914 if (!script) {
915 return false;
916 }
917
918 // Second pass: build the result array.
919 result_.set(NewDenseEmptyArray(cx_));
920 if (!result_) {
921 return false;
922 }
923
924 for (BytecodeRangeWithPosition r(cx_, script); !r.empty(); r.popFront()) {
925 if (!r.frontIsBreakablePoint()) {
926 continue;
927 }
928
929 size_t offset = r.frontOffset();
930 uint32_t lineno = r.frontLineNumber();
931 JS::LimitedColumnNumberOneOrigin colno = r.frontColumnNumber();
932
933 if (!maybeAppendEntry(offset, lineno, colno,
934 r.frontIsBreakableStepPoint())) {
935 return false;
936 }
937 }
938
939 return true;
940 }
941 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
942 wasm::Instance& instance = instanceObj->instance();
943
944 Vector<wasm::ExprLoc> offsets(cx_);
945 if (instance.debugEnabled() &&
946 !instance.debug().getAllColumnOffsets(&offsets)) {
947 return false;
948 }
949
950 result_.set(NewDenseEmptyArray(cx_));
951 if (!result_) {
952 return false;
953 }
954
955 for (uint32_t i = 0; i < offsets.length(); i++) {
956 uint32_t lineno = offsets[i].lineno;
957 JS::LimitedColumnNumberOneOrigin column(offsets[i].column);
958 size_t offset = offsets[i].offset;
959 if (!maybeAppendEntry(offset, lineno, column, true)) {
960 return false;
961 }
962 }
963 return true;
964 }
965 };
966
967 bool DebuggerScript::CallData::getPossibleBreakpoints() {
968 RootedObject result(cx);
969 GetPossibleBreakpointsMatcher<false> matcher(cx, &result);
970 if (args.length() >= 1 && !args[0].isUndefined()) {
971 RootedObject queryObject(cx, RequireObject(cx, args[0]));
972 if (!queryObject || !matcher.parseQuery(queryObject)) {
973 return false;
974 }
975 }
976 if (!referent.match(matcher)) {
977 return false;
978 }
979
980 args.rval().setObject(*result);
981 return true;
982 }
983
984 bool DebuggerScript::CallData::getPossibleBreakpointOffsets() {
985 RootedObject result(cx);
986 GetPossibleBreakpointsMatcher<true> matcher(cx, &result);
987 if (args.length() >= 1 && !args[0].isUndefined()) {
988 RootedObject queryObject(cx, RequireObject(cx, args[0]));
989 if (!queryObject || !matcher.parseQuery(queryObject)) {
990 return false;
991 }
992 }
993 if (!referent.match(matcher)) {
994 return false;
995 }
996
997 args.rval().setObject(*result);
998 return true;
999 }
1000
1001 class DebuggerScript::GetOffsetMetadataMatcher {
1002 JSContext* cx_;
1003 size_t offset_;
1004 MutableHandle<PlainObject*> result_;
1005
1006 public:
1007 explicit GetOffsetMetadataMatcher(JSContext* cx, size_t offset,
1008 MutableHandle<PlainObject*> result)
1009 : cx_(cx), offset_(offset), result_(result) {}
1010 using ReturnType = bool;
1011 ReturnType match(Handle<BaseScript*> base) {
1012 RootedScript script(cx_, DelazifyScript(cx_, base));
1013 if (!script) {
1014 return false;
1015 }
1016
1017 if (!EnsureScriptOffsetIsValid(cx_, script, offset_)) {
1018 return false;
1019 }
1020
1021 result_.set(NewPlainObject(cx_));
1022 if (!result_) {
1023 return false;
1024 }
1025
1026 BytecodeRangeWithPosition r(cx_, script);
1027 while (!r.empty() && r.frontOffset() < offset_) {
1028 r.popFront();
1029 }
1030
1031 RootedValue value(cx_, NumberValue(r.frontLineNumber()));
1032 if (!DefineDataProperty(cx_, result_, cx_->names().lineNumber, value)) {
1033 return false;
1034 }
1035
1036 value = NumberValue(r.frontColumnNumber().oneOriginValue());
1037 if (!DefineDataProperty(cx_, result_, cx_->names().columnNumber, value)) {
1038 return false;
1039 }
1040
1041 value = BooleanValue(r.frontIsBreakablePoint());
1042 if (!DefineDataProperty(cx_, result_, cx_->names().isBreakpoint, value)) {
1043 return false;
1044 }
1045
1046 value = BooleanValue(r.frontIsBreakableStepPoint());
1047 if (!DefineDataProperty(cx_, result_, cx_->names().isStepStart, value)) {
1048 return false;
1049 }
1050
1051 return true;
1052 }
1053 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
1054 wasm::Instance& instance = instanceObj->instance();
1055 if (!instance.debugEnabled()) {
1056 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
1057 JSMSG_DEBUG_BAD_OFFSET);
1058 return false;
1059 }
1060
1061 uint32_t lineno;
1062 JS::LimitedColumnNumberOneOrigin column;
1063 if (!instance.debug().getOffsetLocation(offset_, &lineno, &column)) {
1064 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
1065 JSMSG_DEBUG_BAD_OFFSET);
1066 return false;
1067 }
1068
1069 result_.set(NewPlainObject(cx_));
1070 if (!result_) {
1071 return false;
1072 }
1073
1074 RootedValue value(cx_, NumberValue(lineno));
1075 if (!DefineDataProperty(cx_, result_, cx_->names().lineNumber, value)) {
1076 return false;
1077 }
1078
1079 value = NumberValue(column.oneOriginValue());
1080 if (!DefineDataProperty(cx_, result_, cx_->names().columnNumber, value)) {
1081 return false;
1082 }
1083
1084 value.setBoolean(true);
1085 if (!DefineDataProperty(cx_, result_, cx_->names().isBreakpoint, value)) {
1086 return false;
1087 }
1088
1089 value.setBoolean(true);
1090 if (!DefineDataProperty(cx_, result_, cx_->names().isStepStart, value)) {
1091 return false;
1092 }
1093
1094 return true;
1095 }
1096 };
1097
1098 bool DebuggerScript::CallData::getOffsetMetadata() {
1099 if (!args.requireAtLeast(cx, "Debugger.Script.getOffsetMetadata", 1)) {
1100 return false;
1101 }
1102 size_t offset;
1103 if (!ScriptOffset(cx, args[0], &offset)) {
1104 return false;
1105 }
1106
1107 Rooted<PlainObject*> result(cx);
1108 GetOffsetMetadataMatcher matcher(cx, offset, &result);
1109 if (!referent.match(matcher)) {
1110 return false;
1111 }
1112
1113 args.rval().setObject(*result);
1114 return true;
1115 }
1116
1117 namespace {
1118
1119 /*
1120 * FlowGraphSummary::populate(cx, script) computes a summary of script's
1121 * control flow graph used by DebuggerScript_{getAllOffsets,getLineOffsets}.
1122 *
1123 * An instruction on a given line is an entry point for that line if it can be
1124 * reached from (an instruction on) a different line. We distinguish between the
1125 * following cases:
1126 * - hasNoEdges:
1127 * The instruction cannot be reached, so the instruction is not an entry
1128 * point for the line it is on.
1129 * - hasSingleEdge:
1130 * The instruction can be reached from a single line. If this line is
1131 * different from the line the instruction is on, the instruction is an
1132 * entry point for that line.
1133 *
1134 * Similarly, an instruction on a given position (line/column pair) is an
1135 * entry point for that position if it can be reached from (an instruction on) a
1136 * different position. Again, we distinguish between the following cases:
1137 * - hasNoEdges:
1138 * The instruction cannot be reached, so the instruction is not an entry
1139 * point for the position it is on.
1140 * - hasSingleEdge:
1141 * The instruction can be reached from a single position. If this line is
1142 * different from the position the instruction is on, the instruction is
1143 * an entry point for that position.
1144 */
1145 class FlowGraphSummary {
1146 public:
1147 class Entry {
1148 public:
1149 static constexpr uint32_t Line_HasNoEdge = UINT32_MAX;
1150 static constexpr uint32_t Column_HasMultipleEdge = UINT32_MAX;
1151
1152 // NOTE: column can be Column_HasMultipleEdge.
1153 static Entry createWithSingleEdgeOrMultipleEdge(uint32_t lineno,
1154 uint32_t column) {
1155 return Entry(lineno, column);
1156 }
1157
1158 static Entry createWithMultipleEdgesFromSingleLine(uint32_t lineno) {
1159 return Entry(lineno, Column_HasMultipleEdge);
1160 }
1161
1162 static Entry createWithMultipleEdgesFromMultipleLines() {
1163 return Entry(Line_HasNoEdge, Column_HasMultipleEdge);
1164 }
1165
1166 Entry() : lineno_(Line_HasNoEdge), column_(1) {}
1167
1168 bool hasNoEdges() const {
1169 return lineno_ == Line_HasNoEdge && column_ != Column_HasMultipleEdge;
1170 }
1171
1172 bool hasSingleEdge() const {
1173 return lineno_ != Line_HasNoEdge && column_ != Column_HasMultipleEdge;
1174 }
1175
1176 uint32_t lineno() const { return lineno_; }
1177
1178 // Returns 1-origin column number or the sentinel value
1179 // Column_HasMultipleEdge.
1180 uint32_t columnOrSentinel() const { return column_; }
1181
1182 JS::LimitedColumnNumberOneOrigin column() const {
1183 MOZ_ASSERT(column_ != Column_HasMultipleEdge);
1184 return JS::LimitedColumnNumberOneOrigin(column_);
1185 }
1186
1187 private:
1188 Entry(uint32_t lineno, uint32_t column)
1189 : lineno_(lineno), column_(column) {}
1190
1191 // Line number (1-origin).
1192 // Line_HasNoEdge for no edge.
1193 uint32_t lineno_;
1194
1195 // Column number in UTF-16 code units (1-origin).
1196 // Column_HasMultipleEdge for multiple edge.
1197 uint32_t column_;
1198 };
1199
1200 explicit FlowGraphSummary(JSContext* cx) : entries_(cx) {}
1201
1202 Entry& operator[](size_t index) { return entries_[index]; }
1203
1204 bool populate(JSContext* cx, JSScript* script) {
1205 if (!entries_.growBy(script->length())) {
1206 return false;
1207 }
1208 unsigned mainOffset = script->pcToOffset(script->main());
1209 entries_[mainOffset] = Entry::createWithMultipleEdgesFromMultipleLines();
1210
1211 // The following code uses uint32_t for column numbers.
1212 // The value is either 1-origin column number,
1213 // or Entry::Column_HasMultipleEdge.
1214
1215 uint32_t prevLineno = script->lineno();
1216 uint32_t prevColumn = 1;
1217 JSOp prevOp = JSOp::Nop;
1218 for (BytecodeRangeWithPosition r(cx, script); !r.empty(); r.popFront()) {
1219 uint32_t lineno = prevLineno;
1220 uint32_t column = prevColumn;
1221 JSOp op = r.frontOpcode();
1222
1223 if (BytecodeFallsThrough(prevOp)) {
1224 addEdge(prevLineno, prevColumn, r.frontOffset());
1225 }
1226
1227 // If we visit the branch target before we visit the
1228 // branch op itself, just reuse the previous location.
1229 // This is reasonable for the time being because this
1230 // situation can currently only arise from loop heads,
1231 // where this assumption holds.
1232 if (BytecodeIsJumpTarget(op) && !entries_[r.frontOffset()].hasNoEdges()) {
1233 lineno = entries_[r.frontOffset()].lineno();
1234 column = entries_[r.frontOffset()].columnOrSentinel();
1235 }
1236
1237 if (r.frontIsEntryPoint()) {
1238 lineno = r.frontLineNumber();
1239 column = r.frontColumnNumber().oneOriginValue();
1240 }
1241
1242 if (IsJumpOpcode(op)) {
1243 addEdge(lineno, column, r.frontOffset() + GET_JUMP_OFFSET(r.frontPC()));
1244 } else if (op == JSOp::TableSwitch) {
1245 jsbytecode* const switchPC = r.frontPC();
1246 jsbytecode* pc = switchPC;
1247 size_t offset = r.frontOffset();
1248 ptrdiff_t step = JUMP_OFFSET_LEN;
1249 size_t defaultOffset = offset + GET_JUMP_OFFSET(pc);
1250 pc += step;
1251 addEdge(lineno, column, defaultOffset);
1252
1253 int32_t low = GET_JUMP_OFFSET(pc);
1254 pc += JUMP_OFFSET_LEN;
1255 int ncases = GET_JUMP_OFFSET(pc) - low + 1;
1256 pc += JUMP_OFFSET_LEN;
1257
1258 for (int i = 0; i < ncases; i++) {
1259 size_t target = script->tableSwitchCaseOffset(switchPC, i);
1260 addEdge(lineno, column, target);
1261 }
1262 } else if (op == JSOp::Try) {
1263 // As there is no literal incoming edge into the catch block, we
1264 // make a fake one by copying the JSOp::Try location, as-if this
1265 // was an incoming edge of the catch block. This is needed
1266 // because we only report offsets of entry points which have
1267 // valid incoming edges.
1268 for (const TryNote& tn : script->trynotes()) {
1269 if (tn.start == r.frontOffset() + JSOpLength_Try) {
1270 uint32_t catchOffset = tn.start + tn.length;
1271 if (tn.kind() == TryNoteKind::Catch ||
1272 tn.kind() == TryNoteKind::Finally) {
1273 addEdge(lineno, column, catchOffset);
1274 }
1275 }
1276 }
1277 }
1278
1279 prevLineno = lineno;
1280 prevColumn = column;
1281 prevOp = op;
1282 }
1283
1284 return true;
1285 }
1286
1287 private:
1288 // sourceColumn is either 1-origin column number,
1289 // or Entry::Column_HasMultipleEdge.
1290 void addEdge(uint32_t sourceLineno, uint32_t sourceColumn,
1291 size_t targetOffset) {
1292 if (entries_[targetOffset].hasNoEdges()) {
1293 entries_[targetOffset] =
1294 Entry::createWithSingleEdgeOrMultipleEdge(sourceLineno, sourceColumn);
1295 } else if (entries_[targetOffset].lineno() != sourceLineno) {
1296 entries_[targetOffset] =
1297 Entry::createWithMultipleEdgesFromMultipleLines();
1298 } else if (entries_[targetOffset].columnOrSentinel() != sourceColumn) {
1299 entries_[targetOffset] =
1300 Entry::createWithMultipleEdgesFromSingleLine(sourceLineno);
1301 }
1302 }
1303
1304 Vector<Entry> entries_;
1305 };
1306
1307 } /* anonymous namespace */
1308
1309 class DebuggerScript::GetOffsetLocationMatcher {
1310 JSContext* cx_;
1311 size_t offset_;
1312 MutableHandle<PlainObject*> result_;
1313
1314 public:
1315 explicit GetOffsetLocationMatcher(JSContext* cx, size_t offset,
1316 MutableHandle<PlainObject*> result)
1317 : cx_(cx), offset_(offset), result_(result) {}
1318 using ReturnType = bool;
1319 ReturnType match(Handle<BaseScript*> base) {
1320 RootedScript script(cx_, DelazifyScript(cx_, base));
1321 if (!script) {
1322 return false;
1323 }
1324
1325 if (!EnsureScriptOffsetIsValid(cx_, script, offset_)) {
1326 return false;
1327 }
1328
1329 FlowGraphSummary flowData(cx_);
1330 if (!flowData.populate(cx_, script)) {
1331 return false;
1332 }
1333
1334 result_.set(NewPlainObject(cx_));
1335 if (!result_) {
1336 return false;
1337 }
1338
1339 BytecodeRangeWithPosition r(cx_, script);
1340 while (!r.empty() && r.frontOffset() < offset_) {
1341 r.popFront();
1342 }
1343
1344 size_t offset = r.frontOffset();
1345 bool isEntryPoint = r.frontIsEntryPoint();
1346
1347 // Line numbers are only correctly defined on entry points. Thus looks
1348 // either for the next valid offset in the flowData, being the last entry
1349 // point flowing into the current offset, or for the next valid entry point.
1350 while (!r.frontIsEntryPoint() &&
1351 !flowData[r.frontOffset()].hasSingleEdge()) {
1352 r.popFront();
1353 MOZ_ASSERT(!r.empty());
1354 }
1355
1356 // If this is an entry point, take the line number associated with the entry
1357 // point, otherwise settle on the next instruction and take the incoming
1358 // edge position.
1359 uint32_t lineno;
1360 JS::LimitedColumnNumberOneOrigin column;
1361 if (r.frontIsEntryPoint()) {
1362 lineno = r.frontLineNumber();
1363 column = r.frontColumnNumber();
1364 } else {
1365 MOZ_ASSERT(flowData[r.frontOffset()].hasSingleEdge());
1366 lineno = flowData[r.frontOffset()].lineno();
1367 column = flowData[r.frontOffset()].column();
1368 }
1369
1370 RootedValue value(cx_, NumberValue(lineno));
1371 if (!DefineDataProperty(cx_, result_, cx_->names().lineNumber, value)) {
1372 return false;
1373 }
1374
1375 value = NumberValue(column.oneOriginValue());
1376 if (!DefineDataProperty(cx_, result_, cx_->names().columnNumber, value)) {
1377 return false;
1378 }
1379
1380 // The same entry point test that is used by getAllColumnOffsets.
1381 isEntryPoint = (isEntryPoint && !flowData[offset].hasNoEdges() &&
1382 (flowData[offset].lineno() != r.frontLineNumber() ||
1383 flowData[offset].columnOrSentinel() !=
1384 r.frontColumnNumber().oneOriginValue()));
1385 value.setBoolean(isEntryPoint);
1386 if (!DefineDataProperty(cx_, result_, cx_->names().isEntryPoint, value)) {
1387 return false;
1388 }
1389
1390 return true;
1391 }
1392 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
1393 wasm::Instance& instance = instanceObj->instance();
1394 if (!instance.debugEnabled()) {
1395 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
1396 JSMSG_DEBUG_BAD_OFFSET);
1397 return false;
1398 }
1399
1400 uint32_t lineno;
1401 JS::LimitedColumnNumberOneOrigin column;
1402 if (!instance.debug().getOffsetLocation(offset_, &lineno, &column)) {
1403 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
1404 JSMSG_DEBUG_BAD_OFFSET);
1405 return false;
1406 }
1407
1408 result_.set(NewPlainObject(cx_));
1409 if (!result_) {
1410 return false;
1411 }
1412
1413 RootedValue value(cx_, NumberValue(lineno));
1414 if (!DefineDataProperty(cx_, result_, cx_->names().lineNumber, value)) {
1415 return false;
1416 }
1417
1418 value = NumberValue(column.oneOriginValue());
1419 if (!DefineDataProperty(cx_, result_, cx_->names().columnNumber, value)) {
1420 return false;
1421 }
1422
1423 value.setBoolean(true);
1424 if (!DefineDataProperty(cx_, result_, cx_->names().isEntryPoint, value)) {
1425 return false;
1426 }
1427
1428 return true;
1429 }
1430 };
1431
1432 bool DebuggerScript::CallData::getOffsetLocation() {
1433 if (!args.requireAtLeast(cx, "Debugger.Script.getOffsetLocation", 1)) {
1434 return false;
1435 }
1436 size_t offset;
1437 if (!ScriptOffset(cx, args[0], &offset)) {
1438 return false;
1439 }
1440
1441 Rooted<PlainObject*> result(cx);
1442 GetOffsetLocationMatcher matcher(cx, offset, &result);
1443 if (!referent.match(matcher)) {
1444 return false;
1445 }
1446
1447 args.rval().setObject(*result);
1448 return true;
1449 }
1450
1451 // Return whether an opcode is considered effectful: it can have direct side
1452 // effects that can be observed outside of the current frame. Opcodes are not
1453 // effectful if they only modify the current frame's state, modify objects
1454 // created by the current frame, or can potentially call other scripts or
1455 // natives which could have side effects.
1456 static bool BytecodeIsEffectful(JSScript* script, size_t offset) {
1457 jsbytecode* pc = script->offsetToPC(offset);
1458 JSOp op = JSOp(*pc);
1459 switch (op) {
1460 case JSOp::SetProp:
1461 case JSOp::StrictSetProp:
1462 case JSOp::SetPropSuper:
1463 case JSOp::StrictSetPropSuper:
1464 case JSOp::SetElem:
1465 case JSOp::StrictSetElem:
1466 case JSOp::SetElemSuper:
1467 case JSOp::StrictSetElemSuper:
1468 case JSOp::SetName:
1469 case JSOp::StrictSetName:
1470 case JSOp::SetGName:
1471 case JSOp::StrictSetGName:
1472 case JSOp::DelProp:
1473 case JSOp::StrictDelProp:
1474 case JSOp::DelElem:
1475 case JSOp::StrictDelElem:
1476 case JSOp::DelName:
1477 case JSOp::SetAliasedVar:
1478 case JSOp::InitHomeObject:
1479 case JSOp::SetIntrinsic:
1480 case JSOp::InitGLexical:
1481 case JSOp::GlobalOrEvalDeclInstantiation:
1482 case JSOp::SetFunName:
1483 case JSOp::MutateProto:
1484 case JSOp::DynamicImport:
1485 case JSOp::InitialYield:
1486 case JSOp::Yield:
1487 case JSOp::Await:
1488 case JSOp::CanSkipAwait:
1489 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1490 case JSOp::AddDisposable:
1491 #endif
1492 return true;
1493
1494 case JSOp::Nop:
1495 case JSOp::NopDestructuring:
1496 case JSOp::NopIsAssignOp:
1497 case JSOp::TryDestructuring:
1498 case JSOp::Lineno:
1499 case JSOp::JumpTarget:
1500 case JSOp::Undefined:
1501 case JSOp::JumpIfTrue:
1502 case JSOp::JumpIfFalse:
1503 case JSOp::Return:
1504 case JSOp::RetRval:
1505 case JSOp::And:
1506 case JSOp::Or:
1507 case JSOp::Coalesce:
1508 case JSOp::Try:
1509 case JSOp::Throw:
1510 case JSOp::ThrowWithStack:
1511 #ifdef ENABLE_EXPLICIT_RESOURCE_MANAGEMENT
1512 case JSOp::TakeDisposeCapability:
1513 case JSOp::CreateSuppressedError:
1514 #endif
1515 case JSOp::Goto:
1516 case JSOp::TableSwitch:
1517 case JSOp::Case:
1518 case JSOp::Default:
1519 case JSOp::BitNot:
1520 case JSOp::BitAnd:
1521 case JSOp::BitOr:
1522 case JSOp::BitXor:
1523 case JSOp::Lsh:
1524 case JSOp::Rsh:
1525 case JSOp::Ursh:
1526 case JSOp::Add:
1527 case JSOp::Sub:
1528 case JSOp::Mul:
1529 case JSOp::Div:
1530 case JSOp::Mod:
1531 case JSOp::Pow:
1532 case JSOp::Pos:
1533 case JSOp::ToNumeric:
1534 case JSOp::Neg:
1535 case JSOp::Inc:
1536 case JSOp::Dec:
1537 case JSOp::ToString:
1538 case JSOp::Eq:
1539 case JSOp::Ne:
1540 case JSOp::StrictEq:
1541 case JSOp::StrictNe:
1542 case JSOp::StrictConstantEq:
1543 case JSOp::StrictConstantNe:
1544 case JSOp::Lt:
1545 case JSOp::Le:
1546 case JSOp::Gt:
1547 case JSOp::Ge:
1548 case JSOp::Double:
1549 case JSOp::BigInt:
1550 case JSOp::String:
1551 case JSOp::Symbol:
1552 case JSOp::Zero:
1553 case JSOp::One:
1554 case JSOp::Null:
1555 case JSOp::Void:
1556 case JSOp::Hole:
1557 case JSOp::False:
1558 case JSOp::True:
1559 case JSOp::Arguments:
1560 case JSOp::Rest:
1561 case JSOp::GetArg:
1562 case JSOp::GetFrameArg:
1563 case JSOp::SetArg:
1564 case JSOp::GetLocal:
1565 case JSOp::SetLocal:
1566 case JSOp::GetActualArg:
1567 case JSOp::ArgumentsLength:
1568 case JSOp::ThrowSetConst:
1569 case JSOp::CheckLexical:
1570 case JSOp::CheckAliasedLexical:
1571 case JSOp::InitLexical:
1572 case JSOp::Uninitialized:
1573 case JSOp::Pop:
1574 case JSOp::PopN:
1575 case JSOp::DupAt:
1576 case JSOp::NewArray:
1577 case JSOp::NewInit:
1578 case JSOp::NewObject:
1579 case JSOp::InitElem:
1580 case JSOp::InitHiddenElem:
1581 case JSOp::InitLockedElem:
1582 case JSOp::InitElemInc:
1583 case JSOp::InitElemArray:
1584 case JSOp::InitProp:
1585 case JSOp::InitLockedProp:
1586 case JSOp::InitHiddenProp:
1587 case JSOp::InitPropGetter:
1588 case JSOp::InitHiddenPropGetter:
1589 case JSOp::InitPropSetter:
1590 case JSOp::InitHiddenPropSetter:
1591 case JSOp::InitElemGetter:
1592 case JSOp::InitHiddenElemGetter:
1593 case JSOp::InitElemSetter:
1594 case JSOp::InitHiddenElemSetter:
1595 case JSOp::SpreadCall:
1596 case JSOp::Call:
1597 case JSOp::CallContent:
1598 case JSOp::CallIgnoresRv:
1599 case JSOp::CallIter:
1600 case JSOp::CallContentIter:
1601 case JSOp::New:
1602 case JSOp::NewContent:
1603 case JSOp::Eval:
1604 case JSOp::StrictEval:
1605 case JSOp::Int8:
1606 case JSOp::Uint16:
1607 case JSOp::ResumeKind:
1608 case JSOp::GetGName:
1609 case JSOp::GetName:
1610 case JSOp::GetIntrinsic:
1611 case JSOp::GetImport:
1612 case JSOp::BindName:
1613 case JSOp::BindUnqualifiedName:
1614 case JSOp::BindUnqualifiedGName:
1615 case JSOp::BindVar:
1616 case JSOp::Dup:
1617 case JSOp::Dup2:
1618 case JSOp::Swap:
1619 case JSOp::Pick:
1620 case JSOp::Unpick:
1621 case JSOp::GetAliasedDebugVar:
1622 case JSOp::GetAliasedVar:
1623 case JSOp::Uint24:
1624 case JSOp::Int32:
1625 case JSOp::LoopHead:
1626 case JSOp::GetElem:
1627 case JSOp::Not:
1628 case JSOp::FunctionThis:
1629 case JSOp::GlobalThis:
1630 case JSOp::NonSyntacticGlobalThis:
1631 case JSOp::Callee:
1632 case JSOp::EnvCallee:
1633 case JSOp::SuperBase:
1634 case JSOp::GetPropSuper:
1635 case JSOp::GetElemSuper:
1636 case JSOp::GetProp:
1637 case JSOp::RegExp:
1638 case JSOp::CallSiteObj:
1639 case JSOp::Object:
1640 case JSOp::Typeof:
1641 case JSOp::TypeofExpr:
1642 case JSOp::TypeofEq:
1643 case JSOp::ToAsyncIter:
1644 case JSOp::ToPropertyKey:
1645 case JSOp::Lambda:
1646 case JSOp::PushLexicalEnv:
1647 case JSOp::PopLexicalEnv:
1648 case JSOp::FreshenLexicalEnv:
1649 case JSOp::RecreateLexicalEnv:
1650 case JSOp::PushClassBodyEnv:
1651 case JSOp::Iter:
1652 case JSOp::MoreIter:
1653 case JSOp::IsNoIter:
1654 case JSOp::EndIter:
1655 case JSOp::CloseIter:
1656 case JSOp::OptimizeGetIterator:
1657 case JSOp::IsNullOrUndefined:
1658 case JSOp::In:
1659 case JSOp::HasOwn:
1660 case JSOp::CheckPrivateField:
1661 case JSOp::NewPrivateName:
1662 case JSOp::SetRval:
1663 case JSOp::Instanceof:
1664 case JSOp::DebugLeaveLexicalEnv:
1665 case JSOp::Debugger:
1666 case JSOp::ImplicitThis:
1667 case JSOp::NewTarget:
1668 case JSOp::CheckIsObj:
1669 case JSOp::CheckObjCoercible:
1670 case JSOp::DebugCheckSelfHosted:
1671 case JSOp::IsConstructing:
1672 case JSOp::OptimizeSpreadCall:
1673 case JSOp::ImportMeta:
1674 case JSOp::EnterWith:
1675 case JSOp::LeaveWith:
1676 case JSOp::SpreadNew:
1677 case JSOp::SpreadEval:
1678 case JSOp::StrictSpreadEval:
1679 case JSOp::CheckClassHeritage:
1680 case JSOp::FunWithProto:
1681 case JSOp::ObjWithProto:
1682 case JSOp::BuiltinObject:
1683 case JSOp::CheckThis:
1684 case JSOp::CheckReturn:
1685 case JSOp::CheckThisReinit:
1686 case JSOp::SuperFun:
1687 case JSOp::SpreadSuperCall:
1688 case JSOp::SuperCall:
1689 case JSOp::PushVarEnv:
1690 case JSOp::GetBoundName:
1691 case JSOp::Exception:
1692 case JSOp::ExceptionAndStack:
1693 case JSOp::IsGenClosing:
1694 case JSOp::FinalYieldRval:
1695 case JSOp::Resume:
1696 case JSOp::CheckResumeKind:
1697 case JSOp::AfterYield:
1698 case JSOp::MaybeExtractAwaitValue:
1699 case JSOp::Generator:
1700 case JSOp::AsyncAwait:
1701 case JSOp::AsyncResolve:
1702 case JSOp::AsyncReject:
1703 case JSOp::Finally:
1704 case JSOp::GetRval:
1705 case JSOp::ThrowMsg:
1706 case JSOp::ForceInterpreter:
1707 return false;
1708
1709 case JSOp::InitAliasedLexical: {
1710 uint32_t hops = EnvironmentCoordinate(pc).hops();
1711 if (hops == 0) {
1712 // Initializing aliased lexical in the current scope is almost same
1713 // as JSOp::InitLexical.
1714 return false;
1715 }
1716
1717 // Otherwise this can touch an environment outside of the current scope.
1718 return true;
1719 }
1720 }
1721
1722 MOZ_ASSERT_UNREACHABLE("Invalid opcode");
1723 return false;
1724 }
1725
1726 bool DebuggerScript::CallData::getEffectfulOffsets() {
1727 if (!ensureScript()) {
1728 return false;
1729 }
1730
1731 RootedObject result(cx, NewDenseEmptyArray(cx));
1732 if (!result) {
1733 return false;
1734 }
1735 for (BytecodeRange r(cx, script); !r.empty(); r.popFront()) {
1736 size_t offset = r.frontOffset();
1737 if (!BytecodeIsEffectful(script, offset)) {
1738 continue;
1739 }
1740
1741 if (IsGeneratorSlotInitialization(script, offset, cx)) {
1742 // This is engine-internal operation and not visible outside the
1743 // currently executing frame.
1744 //
1745 // Also this offset is not allowed for setting breakpoint.
1746 continue;
1747 }
1748
1749 if (!NewbornArrayPush(cx, result, NumberValue(offset))) {
1750 return false;
1751 }
1752 }
1753
1754 args.rval().setObject(*result);
1755 return true;
1756 }
1757
1758 bool DebuggerScript::CallData::getAllOffsets() {
1759 if (!ensureScript()) {
1760 return false;
1761 }
1762
1763 // First pass: determine which offsets in this script are jump targets and
1764 // which line numbers jump to them.
1765 FlowGraphSummary flowData(cx);
1766 if (!flowData.populate(cx, script)) {
1767 return false;
1768 }
1769
1770 // Second pass: build the result array.
1771 RootedObject result(cx, NewDenseEmptyArray(cx));
1772 if (!result) {
1773 return false;
1774 }
1775 for (BytecodeRangeWithPosition r(cx, script); !r.empty(); r.popFront()) {
1776 if (!r.frontIsEntryPoint()) {
1777 continue;
1778 }
1779
1780 size_t offset = r.frontOffset();
1781 uint32_t lineno = r.frontLineNumber();
1782
1783 // Make a note, if the current instruction is an entry point for the current
1784 // line.
1785 if (!flowData[offset].hasNoEdges() && flowData[offset].lineno() != lineno) {
1786 // Get the offsets array for this line.
1787 RootedObject offsets(cx);
1788 RootedValue offsetsv(cx);
1789
1790 RootedId id(cx, PropertyKey::Int(lineno));
1791
1792 bool found;
1793 if (!HasOwnProperty(cx, result, id, &found)) {
1794 return false;
1795 }
1796 if (found && !GetProperty(cx, result, result, id, &offsetsv)) {
1797 return false;
1798 }
1799
1800 if (offsetsv.isObject()) {
1801 offsets = &offsetsv.toObject();
1802 } else {
1803 MOZ_ASSERT(offsetsv.isUndefined());
1804
1805 // Create an empty offsets array for this line.
1806 // Store it in the result array.
1807 RootedId id(cx);
1808 RootedValue v(cx, NumberValue(lineno));
1809 offsets = NewDenseEmptyArray(cx);
1810 if (!offsets || !PrimitiveValueToId<CanGC>(cx, v, &id)) {
1811 return false;
1812 }
1813
1814 RootedValue value(cx, ObjectValue(*offsets));
1815 if (!DefineDataProperty(cx, result, id, value)) {
1816 return false;
1817 }
1818 }
1819
1820 // Append the current offset to the offsets array.
1821 if (!NewbornArrayPush(cx, offsets, NumberValue(offset))) {
1822 return false;
1823 }
1824 }
1825 }
1826
1827 args.rval().setObject(*result);
1828 return true;
1829 }
1830
1831 class DebuggerScript::GetAllColumnOffsetsMatcher {
1832 JSContext* cx_;
1833 MutableHandleObject result_;
1834
1835 bool appendColumnOffsetEntry(uint32_t lineno,
1836 JS::LimitedColumnNumberOneOrigin column,
1837 size_t offset) {
1838 Rooted<PlainObject*> entry(cx_, NewPlainObject(cx_));
1839 if (!entry) {
1840 return false;
1841 }
1842
1843 RootedValue value(cx_, NumberValue(lineno));
1844 if (!DefineDataProperty(cx_, entry, cx_->names().lineNumber, value)) {
1845 return false;
1846 }
1847
1848 value = NumberValue(column.oneOriginValue());
1849 if (!DefineDataProperty(cx_, entry, cx_->names().columnNumber, value)) {
1850 return false;
1851 }
1852
1853 value = NumberValue(offset);
1854 if (!DefineDataProperty(cx_, entry, cx_->names().offset, value)) {
1855 return false;
1856 }
1857
1858 return NewbornArrayPush(cx_, result_, ObjectValue(*entry));
1859 }
1860
1861 public:
1862 explicit GetAllColumnOffsetsMatcher(JSContext* cx, MutableHandleObject result)
1863 : cx_(cx), result_(result) {}
1864 using ReturnType = bool;
1865 ReturnType match(Handle<BaseScript*> base) {
1866 RootedScript script(cx_, DelazifyScript(cx_, base));
1867 if (!script) {
1868 return false;
1869 }
1870
1871 // First pass: determine which offsets in this script are jump targets
1872 // and which positions jump to them.
1873 FlowGraphSummary flowData(cx_);
1874 if (!flowData.populate(cx_, script)) {
1875 return false;
1876 }
1877
1878 // Second pass: build the result array.
1879 result_.set(NewDenseEmptyArray(cx_));
1880 if (!result_) {
1881 return false;
1882 }
1883
1884 for (BytecodeRangeWithPosition r(cx_, script); !r.empty(); r.popFront()) {
1885 uint32_t lineno = r.frontLineNumber();
1886 JS::LimitedColumnNumberOneOrigin column = r.frontColumnNumber();
1887 size_t offset = r.frontOffset();
1888
1889 // Make a note, if the current instruction is an entry point for
1890 // the current position.
1891 if (r.frontIsEntryPoint() && !flowData[offset].hasNoEdges() &&
1892 (flowData[offset].lineno() != lineno ||
1893 flowData[offset].columnOrSentinel() != column.oneOriginValue())) {
1894 if (!appendColumnOffsetEntry(lineno, column, offset)) {
1895 return false;
1896 }
1897 }
1898 }
1899 return true;
1900 }
1901 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
1902 wasm::Instance& instance = instanceObj->instance();
1903
1904 Vector<wasm::ExprLoc> offsets(cx_);
1905 if (instance.debugEnabled() &&
1906 !instance.debug().getAllColumnOffsets(&offsets)) {
1907 return false;
1908 }
1909
1910 result_.set(NewDenseEmptyArray(cx_));
1911 if (!result_) {
1912 return false;
1913 }
1914
1915 for (uint32_t i = 0; i < offsets.length(); i++) {
1916 uint32_t lineno = offsets[i].lineno;
1917 JS::LimitedColumnNumberOneOrigin column(offsets[i].column);
1918 size_t offset = offsets[i].offset;
1919 if (!appendColumnOffsetEntry(lineno, column, offset)) {
1920 return false;
1921 }
1922 }
1923 return true;
1924 }
1925 };
1926
1927 bool DebuggerScript::CallData::getAllColumnOffsets() {
1928 RootedObject result(cx);
1929 GetAllColumnOffsetsMatcher matcher(cx, &result);
1930 if (!referent.match(matcher)) {
1931 return false;
1932 }
1933
1934 args.rval().setObject(*result);
1935 return true;
1936 }
1937
1938 class DebuggerScript::GetLineOffsetsMatcher {
1939 JSContext* cx_;
1940 uint32_t lineno_;
1941 MutableHandleObject result_;
1942
1943 public:
1944 explicit GetLineOffsetsMatcher(JSContext* cx, uint32_t lineno,
1945 MutableHandleObject result)
1946 : cx_(cx), lineno_(lineno), result_(result) {}
1947 using ReturnType = bool;
1948 ReturnType match(Handle<BaseScript*> base) {
1949 RootedScript script(cx_, DelazifyScript(cx_, base));
1950 if (!script) {
1951 return false;
1952 }
1953
1954 // First pass: determine which offsets in this script are jump targets and
1955 // which line numbers jump to them.
1956 FlowGraphSummary flowData(cx_);
1957 if (!flowData.populate(cx_, script)) {
1958 return false;
1959 }
1960
1961 result_.set(NewDenseEmptyArray(cx_));
1962 if (!result_) {
1963 return false;
1964 }
1965
1966 // Second pass: build the result array.
1967 for (BytecodeRangeWithPosition r(cx_, script); !r.empty(); r.popFront()) {
1968 if (!r.frontIsEntryPoint()) {
1969 continue;
1970 }
1971
1972 size_t offset = r.frontOffset();
1973
1974 // If the op at offset is an entry point, append offset to result.
1975 if (r.frontLineNumber() == lineno_ && !flowData[offset].hasNoEdges() &&
1976 flowData[offset].lineno() != lineno_) {
1977 if (!NewbornArrayPush(cx_, result_, NumberValue(offset))) {
1978 return false;
1979 }
1980 }
1981 }
1982
1983 return true;
1984 }
1985 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
1986 wasm::Instance& instance = instanceObj->instance();
1987
1988 Vector<uint32_t> offsets(cx_);
1989 if (instance.debugEnabled() &&
1990 !instance.debug().getLineOffsets(lineno_, &offsets)) {
1991 return false;
1992 }
1993
1994 result_.set(NewDenseEmptyArray(cx_));
1995 if (!result_) {
1996 return false;
1997 }
1998
1999 for (uint32_t i = 0; i < offsets.length(); i++) {
2000 if (!NewbornArrayPush(cx_, result_, NumberValue(offsets[i]))) {
2001 return false;
2002 }
2003 }
2004 return true;
2005 }
2006 };
2007
2008 bool DebuggerScript::CallData::getLineOffsets() {
2009 if (!args.requireAtLeast(cx, "Debugger.Script.getLineOffsets", 1)) {
2010 return false;
2011 }
2012
2013 // Parse lineno argument.
2014 RootedValue linenoValue(cx, args[0]);
2015 uint32_t lineno;
2016 if (!ToNumber(cx, &linenoValue)) {
2017 return false;
2018 }
2019 {
2020 double d = linenoValue.toNumber();
2021 lineno = uint32_t(d);
2022 if (lineno != d) {
2023 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
2024 JSMSG_DEBUG_BAD_LINE);
2025 return false;
2026 }
2027 }
2028
2029 RootedObject result(cx);
2030 GetLineOffsetsMatcher matcher(cx, lineno, &result);
2031 if (!referent.match(matcher)) {
2032 return false;
2033 }
2034
2035 args.rval().setObject(*result);
2036 return true;
2037 }
2038
2039 struct DebuggerScript::SetBreakpointMatcher {
2040 JSContext* cx_;
2041 Debugger* dbg_;
2042 size_t offset_;
2043 RootedObject handler_;
2044 RootedObject debuggerObject_;
2045
2046 bool wrapCrossCompartmentEdges() {
2047 if (!cx_->compartment()->wrap(cx_, &handler_) ||
2048 !cx_->compartment()->wrap(cx_, &debuggerObject_)) {
2049 return false;
2050 }
2051
2052 // If the Debugger's compartment has killed incoming wrappers, we may not
2053 // have gotten usable results from the 'wrap' calls. Treat it as a
2054 // failure.
2055 if (IsDeadProxyObject(handler_) || IsDeadProxyObject(debuggerObject_)) {
2056 ReportAccessDenied(cx_);
2057 return false;
2058 }
2059
2060 return true;
2061 }
2062
2063 public:
2064 explicit SetBreakpointMatcher(JSContext* cx, Debugger* dbg, size_t offset,
2065 HandleObject handler)
2066 : cx_(cx),
2067 dbg_(dbg),
2068 offset_(offset),
2069 handler_(cx, handler),
2070 debuggerObject_(cx_, dbg_->toJSObject()) {}
2071
2072 using ReturnType = bool;
2073
2074 ReturnType match(Handle<BaseScript*> base) {
2075 RootedScript script(cx_, DelazifyScript(cx_, base));
2076 if (!script) {
2077 return false;
2078 }
2079
2080 if (!dbg_->observesScript(script)) {
2081 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
2082 JSMSG_DEBUG_NOT_DEBUGGING);
2083 return false;
2084 }
2085
2086 if (!EnsureScriptOffsetIsValid(cx_, script, offset_)) {
2087 return false;
2088 }
2089
2090 if (!EnsureBreakpointIsAllowed(cx_, script, offset_)) {
2091 return false;
2092 }
2093
2094 // Ensure observability *before* setting the breakpoint. If the script is
2095 // not already a debuggee, trying to ensure observability after setting
2096 // the breakpoint (and thus marking the script as a debuggee) will skip
2097 // actually ensuring observability.
2098 if (!dbg_->ensureExecutionObservabilityOfScript(cx_, script)) {
2099 return false;
2100 }
2101
2102 // A Breakpoint belongs logically to its script's compartment, so its
2103 // references to its Debugger and handler must be properly wrapped.
2104 AutoRealm ar(cx_, script);
2105 if (!wrapCrossCompartmentEdges()) {
2106 return false;
2107 }
2108
2109 jsbytecode* pc = script->offsetToPC(offset_);
2110 JSBreakpointSite* site =
2111 DebugScript::getOrCreateBreakpointSite(cx_, script, pc);
2112 if (!site) {
2113 return false;
2114 }
2115
2116 if (!cx_->zone()->new_<Breakpoint>(dbg_, debuggerObject_, site, handler_)) {
2117 site->destroyIfEmpty(cx_->runtime()->gcContext());
2118 return false;
2119 }
2120 AddCellMemory(script, sizeof(Breakpoint), MemoryUse::Breakpoint);
2121
2122 return true;
2123 }
2124 ReturnType match(Handle<WasmInstanceObject*> wasmInstance) {
2125 wasm::Instance& instance = wasmInstance->instance();
2126 if (!instance.debugEnabled() ||
2127 !instance.debug().hasBreakpointTrapAtOffset(offset_)) {
2128 JS_ReportErrorNumberASCII(cx_, GetErrorMessage, nullptr,
2129 JSMSG_DEBUG_BAD_OFFSET);
2130 return false;
2131 }
2132
2133 // A Breakpoint belongs logically to its Instance's compartment, so its
2134 // references to its Debugger and handler must be properly wrapped.
2135 AutoRealm ar(cx_, wasmInstance);
2136 if (!wrapCrossCompartmentEdges()) {
2137 return false;
2138 }
2139
2140 WasmBreakpointSite* site = instance.getOrCreateBreakpointSite(cx_, offset_);
2141 if (!site) {
2142 return false;
2143 }
2144
2145 if (!cx_->zone()->new_<Breakpoint>(dbg_, debuggerObject_, site, handler_)) {
2146 site->destroyIfEmpty(cx_->runtime()->gcContext());
2147 return false;
2148 }
2149 AddCellMemory(wasmInstance, sizeof(Breakpoint), MemoryUse::Breakpoint);
2150
2151 return true;
2152 }
2153 };
2154
2155 bool DebuggerScript::CallData::setBreakpoint() {
2156 if (!args.requireAtLeast(cx, "Debugger.Script.setBreakpoint", 2)) {
2157 return false;
2158 }
2159 Debugger* dbg = obj->owner();
2160
2161 size_t offset;
2162 if (!ScriptOffset(cx, args[0], &offset)) {
2163 return false;
2164 }
2165
2166 RootedObject handler(cx, RequireObject(cx, args[1]));
2167 if (!handler) {
2168 return false;
2169 }
2170
2171 SetBreakpointMatcher matcher(cx, dbg, offset, handler);
2172 if (!referent.match(matcher)) {
2173 return false;
2174 }
2175 args.rval().setUndefined();
2176 return true;
2177 }
2178
2179 bool DebuggerScript::CallData::getBreakpoints() {
2180 if (!ensureScript()) {
2181 return false;
2182 }
2183 Debugger* dbg = obj->owner();
2184
2185 jsbytecode* pc;
2186 if (args.length() > 0) {
2187 size_t offset;
2188 if (!ScriptOffset(cx, args[0], &offset) ||
2189 !EnsureScriptOffsetIsValid(cx, script, offset)) {
2190 return false;
2191 }
2192 pc = script->offsetToPC(offset);
2193 } else {
2194 pc = nullptr;
2195 }
2196
2197 RootedObject arr(cx, NewDenseEmptyArray(cx));
2198 if (!arr) {
2199 return false;
2200 }
2201
2202 for (unsigned i = 0; i < script->length(); i++) {
2203 JSBreakpointSite* site =
2204 DebugScript::getBreakpointSite(script, script->offsetToPC(i));
2205 if (!site) {
2206 continue;
2207 }
2208 if (!pc || site->pc == pc) {
2209 for (Breakpoint* bp = site->firstBreakpoint(); bp;
2210 bp = bp->nextInSite()) {
2211 if (bp->debugger == dbg) {
2212 RootedObject handler(cx, bp->getHandler());
2213 if (!cx->compartment()->wrap(cx, &handler) ||
2214 !NewbornArrayPush(cx, arr, ObjectValue(*handler))) {
2215 return false;
2216 }
2217 }
2218 }
2219 }
2220 }
2221 args.rval().setObject(*arr);
2222 return true;
2223 }
2224
2225 class DebuggerScript::ClearBreakpointMatcher {
2226 JSContext* cx_;
2227 Debugger* dbg_;
2228 RootedObject handler_;
2229
2230 public:
2231 ClearBreakpointMatcher(JSContext* cx, Debugger* dbg, JSObject* handler)
2232 : cx_(cx), dbg_(dbg), handler_(cx, handler) {}
2233 using ReturnType = bool;
2234
2235 ReturnType match(Handle<BaseScript*> base) {
2236 RootedScript script(cx_, DelazifyScript(cx_, base));
2237 if (!script) {
2238 return false;
2239 }
2240
2241 // A Breakpoint belongs logically to its script's compartment, so it holds
2242 // its handler via a cross-compartment wrapper. But the handler passed to
2243 // `clearBreakpoint` is same-compartment with the Debugger. Wrap it here,
2244 // so that `DebugScript::clearBreakpointsIn` gets the right value to
2245 // search for.
2246 AutoRealm ar(cx_, script);
2247 if (!cx_->compartment()->wrap(cx_, &handler_)) {
2248 return false;
2249 }
2250
2251 DebugScript::clearBreakpointsIn(cx_->runtime()->gcContext(), script, dbg_,
2252 handler_);
2253 return true;
2254 }
2255 ReturnType match(Handle<WasmInstanceObject*> instanceObj) {
2256 wasm::Instance& instance = instanceObj->instance();
2257 if (!instance.debugEnabled()) {
2258 return true;
2259 }
2260
2261 // A Breakpoint belongs logically to its instance's compartment, so it
2262 // holds its handler via a cross-compartment wrapper. But the handler
2263 // passed to `clearBreakpoint` is same-compartment with the Debugger. Wrap
2264 // it here, so that `DebugState::clearBreakpointsIn` gets the right value
2265 // to search for.
2266 AutoRealm ar(cx_, instanceObj);
2267 if (!cx_->compartment()->wrap(cx_, &handler_)) {
2268 return false;
2269 }
2270
2271 instance.debug().clearBreakpointsIn(cx_->runtime()->gcContext(),
2272 instanceObj, dbg_, handler_);
2273 return true;
2274 }
2275 };
2276
2277 bool DebuggerScript::CallData::clearBreakpoint() {
2278 if (!args.requireAtLeast(cx, "Debugger.Script.clearBreakpoint", 1)) {
2279 return false;
2280 }
2281 Debugger* dbg = obj->owner();
2282
2283 JSObject* handler = RequireObject(cx, args[0]);
2284 if (!handler) {
2285 return false;
2286 }
2287
2288 ClearBreakpointMatcher matcher(cx, dbg, handler);
2289 if (!referent.match(matcher)) {
2290 return false;
2291 }
2292
2293 args.rval().setUndefined();
2294 return true;
2295 }
2296
2297 bool DebuggerScript::CallData::clearAllBreakpoints() {
2298 Debugger* dbg = obj->owner();
2299 ClearBreakpointMatcher matcher(cx, dbg, nullptr);
2300 if (!referent.match(matcher)) {
2301 return false;
2302 }
2303 args.rval().setUndefined();
2304 return true;
2305 }
2306
2307 class DebuggerScript::IsInCatchScopeMatcher {
2308 JSContext* cx_;
2309 size_t offset_;
2310 bool isInCatch_;
2311
2312 public:
2313 explicit IsInCatchScopeMatcher(JSContext* cx, size_t offset)
2314 : cx_(cx), offset_(offset), isInCatch_(false) {}
2315 using ReturnType = bool;
2316
2317 inline bool isInCatch() const { return isInCatch_; }
2318
2319 ReturnType match(Handle<BaseScript*> base) {
2320 RootedScript script(cx_, DelazifyScript(cx_, base));
2321 if (!script) {
2322 return false;
2323 }
2324
2325 if (!EnsureScriptOffsetIsValid(cx_, script, offset_)) {
2326 return false;
2327 }
2328
2329 MOZ_ASSERT(!isInCatch_);
2330 for (const TryNote& tn : script->trynotes()) {
2331 bool inRange = tn.start <= offset_ && offset_ < tn.start + tn.length;
2332 if (inRange && tn.kind() == TryNoteKind::Catch) {
2333 isInCatch_ = true;
2334 } else if (isInCatch_) {
2335 // For-of loops generate a synthetic catch block to handle
2336 // closing the iterator when throwing an exception. The
2337 // debugger should ignore these synthetic catch blocks, so
2338 // we skip any Catch trynote that is immediately followed
2339 // by a ForOf trynote.
2340 if (inRange && tn.kind() == TryNoteKind::ForOf) {
2341 isInCatch_ = false;
2342 continue;
2343 }
2344 return true;
2345 }
2346 }
2347
2348 return true;
2349 }
2350 ReturnType match(Handle<WasmInstanceObject*> instance) {
2351 isInCatch_ = false;
2352 return true;
2353 }
2354 };
2355
2356 bool DebuggerScript::CallData::isInCatchScope() {
2357 if (!args.requireAtLeast(cx, "Debugger.Script.isInCatchScope", 1)) {
2358 return false;
2359 }
2360
2361 size_t offset;
2362 if (!ScriptOffset(cx, args[0], &offset)) {
2363 return false;
2364 }
2365
2366 IsInCatchScopeMatcher matcher(cx, offset);
2367 if (!referent.match(matcher)) {
2368 return false;
2369 }
2370 args.rval().setBoolean(matcher.isInCatch());
2371 return true;
2372 }
2373
2374 bool DebuggerScript::CallData::getOffsetsCoverage() {
2375 if (!ensureScript()) {
2376 return false;
2377 }
2378
2379 Debugger* dbg = obj->owner();
2380 if (dbg->observesCoverage() != Debugger::Observing) {
2381 args.rval().setNull();
2382 return true;
2383 }
2384
2385 // If the script has no coverage information, then skip this and return null
2386 // instead.
2387 if (!script->hasScriptCounts()) {
2388 args.rval().setNull();
2389 return true;
2390 }
2391
2392 ScriptCounts* sc = &script->getScriptCounts();
2393
2394 // If the main ever got visited, then assume that any code before main got
2395 // visited once.
2396 uint64_t hits = 0;
2397 const PCCounts* counts =
2398 sc->maybeGetPCCounts(script->pcToOffset(script->main()));
2399 if (counts->numExec()) {
2400 hits = 1;
2401 }
2402
2403 // Build an array of objects which are composed of 4 properties:
2404 // - offset PC offset of the current opcode.
2405 // - lineNumber Line of the current opcode.
2406 // - columnNumber Column of the current opcode.
2407 // - count Number of times the instruction got executed.
2408 RootedObject result(cx, NewDenseEmptyArray(cx));
2409 if (!result) {
2410 return false;
2411 }
2412
2413 RootedId offsetId(cx, NameToId(cx->names().offset));
2414 RootedId lineNumberId(cx, NameToId(cx->names().lineNumber));
2415 RootedId columnNumberId(cx, NameToId(cx->names().columnNumber));
2416 RootedId countId(cx, NameToId(cx->names().count));
2417
2418 RootedObject item(cx);
2419 RootedValue offsetValue(cx);
2420 RootedValue lineNumberValue(cx);
2421 RootedValue columnNumberValue(cx);
2422 RootedValue countValue(cx);
2423
2424 // Iterate linearly over the bytecode.
2425 for (BytecodeRangeWithPosition r(cx, script); !r.empty(); r.popFront()) {
2426 size_t offset = r.frontOffset();
2427
2428 // The beginning of each non-branching sequences of instruction set the
2429 // number of execution of the current instruction and any following
2430 // instruction.
2431 counts = sc->maybeGetPCCounts(offset);
2432 if (counts) {
2433 hits = counts->numExec();
2434 }
2435
2436 offsetValue.setNumber(double(offset));
2437 lineNumberValue.setNumber(double(r.frontLineNumber()));
2438 columnNumberValue.setNumber(double(r.frontColumnNumber().oneOriginValue()));
2439 countValue.setNumber(double(hits));
2440
2441 // Create a new object with the offset, line number, column number, the
2442 // number of hit counts, and append it to the array.
2443 item = NewPlainObjectWithProto(cx, nullptr);
2444 if (!item || !DefineDataProperty(cx, item, offsetId, offsetValue) ||
2445 !DefineDataProperty(cx, item, lineNumberId, lineNumberValue) ||
2446 !DefineDataProperty(cx, item, columnNumberId, columnNumberValue) ||
2447 !DefineDataProperty(cx, item, countId, countValue) ||
2448 !NewbornArrayPush(cx, result, ObjectValue(*item))) {
2449 return false;
2450 }
2451
2452 // If the current instruction has thrown, then decrement the hit counts
2453 // with the number of throws.
2454 counts = sc->maybeGetThrowCounts(offset);
2455 if (counts) {
2456 hits -= counts->numExec();
2457 }
2458 }
2459
2460 args.rval().setObject(*result);
2461 return true;
2462 }
2463
2464 /* static */
2465 bool DebuggerScript::construct(JSContext* cx, unsigned argc, Value* vp) {
2466 JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NO_CONSTRUCTOR,
2467 "Debugger.Script");
2468 return false;
2469 }
2470
2471 const JSPropertySpec DebuggerScript::properties_[] = {
2472 JS_DEBUG_PSG("isGeneratorFunction", getIsGeneratorFunction),
2473 JS_DEBUG_PSG("isAsyncFunction", getIsAsyncFunction),
2474 JS_DEBUG_PSG("isFunction", getIsFunction),
2475 JS_DEBUG_PSG("isModule", getIsModule),
2476 JS_DEBUG_PSG("displayName", getDisplayName),
2477 JS_DEBUG_PSG("parameterNames", getParameterNames),
2478 JS_DEBUG_PSG("url", getUrl),
2479 JS_DEBUG_PSG("startLine", getStartLine),
2480 JS_DEBUG_PSG("startColumn", getStartColumn),
2481 JS_DEBUG_PSG("lineCount", getLineCount),
2482 JS_DEBUG_PSG("source", getSource),
2483 JS_DEBUG_PSG("sourceStart", getSourceStart),
2484 JS_DEBUG_PSG("sourceLength", getSourceLength),
2485 JS_DEBUG_PSG("mainOffset", getMainOffset),
2486 JS_DEBUG_PSG("global", getGlobal),
2487 JS_DEBUG_PSG("format", getFormat),
2488 JS_PS_END,
2489 };
2490
2491 const JSFunctionSpec DebuggerScript::methods_[] = {
2492 JS_DEBUG_FN("getChildScripts", getChildScripts, 0),
2493 JS_DEBUG_FN("getPossibleBreakpoints", getPossibleBreakpoints, 0),
2494 JS_DEBUG_FN("getPossibleBreakpointOffsets", getPossibleBreakpointOffsets,
2495 0),
2496 JS_DEBUG_FN("setBreakpoint", setBreakpoint, 2),
2497 JS_DEBUG_FN("getBreakpoints", getBreakpoints, 1),
2498 JS_DEBUG_FN("clearBreakpoint", clearBreakpoint, 1),
2499 JS_DEBUG_FN("clearAllBreakpoints", clearAllBreakpoints, 0),
2500 JS_DEBUG_FN("isInCatchScope", isInCatchScope, 1),
2501 JS_DEBUG_FN("getOffsetMetadata", getOffsetMetadata, 1),
2502 JS_DEBUG_FN("getOffsetsCoverage", getOffsetsCoverage, 0),
2503 JS_DEBUG_FN("getEffectfulOffsets", getEffectfulOffsets, 1),
2504
2505 // The following APIs are deprecated due to their reliance on the
2506 // under-defined 'entrypoint' concept. Make use of getPossibleBreakpoints,
2507 // getPossibleBreakpointOffsets, or getOffsetMetadata instead.
2508 JS_DEBUG_FN("getAllOffsets", getAllOffsets, 0),
2509 JS_DEBUG_FN("getAllColumnOffsets", getAllColumnOffsets, 0),
2510 JS_DEBUG_FN("getLineOffsets", getLineOffsets, 1),
2511 JS_DEBUG_FN("getOffsetLocation", getOffsetLocation, 0),
2512 JS_FS_END,
2513 };