-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathDebugger.cpp
7619 lines (6524 loc) · 247 KB
/
Debugger.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
* vim: set ts=8 sts=2 et sw=2 tw=80:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "debugger/Debugger-inl.h"
#include "mozilla/Attributes.h" // for MOZ_STACK_CLASS, MOZ_RAII
#include "mozilla/DebugOnly.h" // for DebugOnly
#include "mozilla/DoublyLinkedList.h" // for DoublyLinkedList<>::Iterator
#include "mozilla/HashTable.h" // for HashSet<>::Range, HashMapEntry
#include "mozilla/Maybe.h" // for Maybe, Nothing, Some
#include "mozilla/ScopeExit.h" // for MakeScopeExit, ScopeExit
#include "mozilla/Sprintf.h" // for SprintfLiteral
#include "mozilla/ThreadLocal.h" // for ThreadLocal
#include "mozilla/TimeStamp.h" // for TimeStamp
#include "mozilla/UniquePtr.h" // for UniquePtr
#include "mozilla/Variant.h" // for AsVariant, AsVariantTemporary
#include "mozilla/Vector.h" // for Vector, Vector<>::ConstRange
#include <algorithm> // for std::find, std::max
#include <functional> // for function
#include <stddef.h> // for size_t
#include <stdint.h> // for uint32_t, uint64_t, int32_t
#include <string.h> // for strlen, strcmp
#include <type_traits> // for std::underlying_type_t
#include <utility> // for std::move
#include "jsapi.h" // for CallArgs, CallArgsFromVp
#include "jstypes.h" // for JS_PUBLIC_API
#include "builtin/Array.h" // for NewDenseFullyAllocatedArray
#include "debugger/DebugAPI.h" // for ResumeMode, DebugAPI
#include "debugger/DebuggerMemory.h" // for DebuggerMemory
#include "debugger/DebugScript.h" // for DebugScript
#include "debugger/Environment.h" // for DebuggerEnvironment
#ifdef MOZ_EXECUTION_TRACING
# include "debugger/ExecutionTracer.h" // for ExecutionTracer::onEnterFrame, ExecutionTracer::onLeaveFrame
#endif
#include "debugger/Frame.h" // for DebuggerFrame
#include "debugger/NoExecute.h" // for EnterDebuggeeNoExecute
#include "debugger/Object.h" // for DebuggerObject
#include "debugger/Script.h" // for DebuggerScript
#include "debugger/Source.h" // for DebuggerSource
#include "frontend/CompilationStencil.h" // for CompilationStencil
#include "frontend/FrontendContext.h" // for AutoReportFrontendContext
#include "frontend/Parser.h" // for Parser
#include "gc/GC.h" // for IterateScripts
#include "gc/GCContext.h" // for JS::GCContext
#include "gc/GCMarker.h" // for GCMarker
#include "gc/GCRuntime.h" // for GCRuntime, AutoEnterIteration
#include "gc/HashUtil.h" // for DependentAddPtr
#include "gc/Marking.h" // for IsAboutToBeFinalized
#include "gc/PublicIterators.h" // for RealmsIter, CompartmentsIter
#include "gc/Statistics.h" // for Statistics::SliceData
#include "gc/Tracer.h" // for TraceEdge
#include "gc/Zone.h" // for Zone
#include "gc/ZoneAllocator.h" // for ZoneAllocPolicy
#include "jit/BaselineDebugModeOSR.h" // for RecompileOnStackBaselineScriptsForDebugMode
#include "jit/BaselineJIT.h" // for FinishDiscardBaselineScript
#include "jit/Invalidation.h" // for RecompileInfoVector
#include "jit/JitContext.h" // for JitContext
#include "jit/JitOptions.h" // for fuzzingSafe
#include "jit/JitScript.h" // for JitScript
#include "jit/JSJitFrameIter.h" // for InlineFrameIterator
#include "jit/RematerializedFrame.h" // for RematerializedFrame
#include "js/CallAndConstruct.h" // JS::IsCallable
#include "js/Conversions.h" // for ToBoolean, ToUint32
#include "js/Debug.h" // for Builder::Object, Builder
#include "js/friend/ErrorMessages.h" // for GetErrorMessage, JSMSG_*
#include "js/GCAPI.h" // for GarbageCollectionEvent
#include "js/GCVariant.h" // for GCVariant
#include "js/HeapAPI.h" // for ExposeObjectToActiveJS
#include "js/Promise.h" // for AutoDebuggerJobQueueInterruption
#include "js/PropertyAndElement.h" // for JS_GetProperty
#include "js/Proxy.h" // for PropertyDescriptor
#include "js/SourceText.h" // for SourceText
#include "js/StableStringChars.h" // for AutoStableStringChars
#include "js/UbiNode.h" // for Node, RootList, Edge
#include "js/UbiNodeBreadthFirst.h" // for BreadthFirst
#include "js/Wrapper.h" // for CheckedUnwrapStatic
#include "util/Identifier.h" // for IsIdentifier
#include "util/Text.h" // for DuplicateString, js_strlen
#include "vm/ArrayObject.h" // for ArrayObject
#include "vm/AsyncFunction.h" // for AsyncFunctionGeneratorObject
#include "vm/AsyncIteration.h" // for AsyncGeneratorObject
#include "vm/BytecodeUtil.h" // for JSDVG_IGNORE_STACK
#include "vm/Compartment.h" // for CrossCompartmentKey
#include "vm/EnvironmentObject.h" // for IsSyntacticEnvironment
#include "vm/ErrorReporting.h" // for ReportErrorToGlobal
#include "vm/GeneratorObject.h" // for AbstractGeneratorObject
#include "vm/GlobalObject.h" // for GlobalObject
#include "vm/Interpreter.h" // for Call, ReportIsNotFunction
#include "vm/Iteration.h" // for CreateIterResultObject
#include "vm/JSAtomUtils.h" // for Atomize, AtomizeUTF8Chars, AtomIsMarked, AtomToId, ClassName
#include "vm/JSContext.h" // for JSContext
#include "vm/JSFunction.h" // for JSFunction
#include "vm/JSObject.h" // for JSObject, RequireObject,
#include "vm/JSScript.h" // for BaseScript, ScriptSourceObject
#include "vm/ObjectOperations.h" // for DefineDataProperty
#include "vm/PlainObject.h" // for js::PlainObject
#include "vm/PromiseObject.h" // for js::PromiseObject
#include "vm/ProxyObject.h" // for ProxyObject, JSObject::is
#include "vm/Realm.h" // for AutoRealm, Realm
#include "vm/Runtime.h" // for ReportOutOfMemory, JSRuntime
#include "vm/SavedFrame.h" // for SavedFrame
#include "vm/SavedStacks.h" // for SavedStacks
#include "vm/Scope.h" // for Scope
#include "vm/StringType.h" // for JSString, PropertyName
#include "vm/WrapperObject.h" // for CrossCompartmentWrapperObject
#include "wasm/WasmDebug.h" // for DebugState
#include "wasm/WasmInstance.h" // for Instance
#include "wasm/WasmJS.h" // for WasmInstanceObject
#include "wasm/WasmRealm.h" // for Realm
#include "wasm/WasmTypeDecls.h" // for WasmInstanceObjectVector
#include "debugger/DebugAPI-inl.h"
#include "debugger/Environment-inl.h" // for DebuggerEnvironment::owner
#include "debugger/Frame-inl.h" // for DebuggerFrame::hasGeneratorInfo
#include "debugger/Object-inl.h" // for DebuggerObject::owner and isInstance.
#include "debugger/Script-inl.h" // for DebuggerScript::getReferent
#include "gc/GC-inl.h" // for ZoneCellIter
#include "gc/Marking-inl.h" // for MaybeForwarded
#include "gc/StableCellHasher-inl.h"
#include "gc/WeakMap-inl.h" // for DebuggerWeakMap::trace
#include "vm/Compartment-inl.h" // for Compartment::wrap
#include "vm/GeckoProfiler-inl.h" // for AutoSuppressProfilerSampling
#include "vm/JSAtomUtils-inl.h" // for AtomToId, ValueToId
#include "vm/JSContext-inl.h" // for JSContext::check
#include "vm/JSObject-inl.h" // for JSObject::isCallable, NewTenuredObjectWithGivenProto
#include "vm/JSScript-inl.h" // for JSScript::isDebuggee, JSScript
#include "vm/NativeObject-inl.h" // for NativeObject::ensureDenseInitializedLength
#include "vm/ObjectOperations-inl.h" // for GetProperty, HasProperty
#include "vm/Realm-inl.h" // for AutoRealm::AutoRealm
#include "vm/Stack-inl.h" // for AbstractFramePtr::script
namespace js {
namespace frontend {
class FullParseHandler;
}
namespace gc {
struct Cell;
}
namespace jit {
class BaselineFrame;
}
} /* namespace js */
using namespace js;
using JS::AutoStableStringChars;
using JS::CompileOptions;
using JS::dbg::Builder;
using mozilla::AsVariant;
using mozilla::DebugOnly;
using mozilla::MakeScopeExit;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;
using mozilla::TimeStamp;
/*** Utils ******************************************************************/
bool js::IsInterpretedNonSelfHostedFunction(JSFunction* fun) {
return fun->isInterpreted() && !fun->isSelfHostedBuiltin();
}
JSScript* js::GetOrCreateFunctionScript(JSContext* cx, HandleFunction fun) {
MOZ_ASSERT(IsInterpretedNonSelfHostedFunction(fun));
AutoRealm ar(cx, fun);
return JSFunction::getOrCreateScript(cx, fun);
}
ArrayObject* js::GetFunctionParameterNamesArray(JSContext* cx,
HandleFunction fun) {
RootedValueVector names(cx);
// The default value for each argument is |undefined|.
if (!names.growBy(fun->nargs())) {
return nullptr;
}
if (IsInterpretedNonSelfHostedFunction(fun) && fun->nargs() > 0) {
RootedScript script(cx, GetOrCreateFunctionScript(cx, fun));
if (!script) {
return nullptr;
}
MOZ_ASSERT(fun->nargs() == script->numArgs());
PositionalFormalParameterIter fi(script);
for (size_t i = 0; i < fun->nargs(); i++, fi++) {
MOZ_ASSERT(fi.argumentSlot() == i);
if (JSAtom* atom = fi.name()) {
// Skip any internal, non-identifier names, like for example ".args".
if (IsIdentifier(atom)) {
cx->markAtom(atom);
names[i].setString(atom);
}
}
}
}
return NewDenseCopiedArray(cx, names.length(), names.begin());
}
bool js::ValueToIdentifier(JSContext* cx, HandleValue v, MutableHandleId id) {
if (!ToPropertyKey(cx, v, id)) {
return false;
}
if (!id.isAtom() || !IsIdentifier(id.toAtom())) {
RootedValue val(cx, v);
ReportValueError(cx, JSMSG_UNEXPECTED_TYPE, JSDVG_SEARCH_STACK, val,
nullptr, "not an identifier");
return false;
}
return true;
}
class js::AutoRestoreRealmDebugMode {
Realm* realm_;
unsigned bits_;
public:
explicit AutoRestoreRealmDebugMode(Realm* realm)
: realm_(realm), bits_(realm->debugModeBits_) {
MOZ_ASSERT(realm_);
}
~AutoRestoreRealmDebugMode() {
if (realm_) {
realm_->debugModeBits_ = bits_;
}
}
void release() { realm_ = nullptr; }
};
/* static */
bool DebugAPI::slowPathCheckNoExecute(JSContext* cx, HandleScript script) {
MOZ_ASSERT(cx->realm()->isDebuggee());
MOZ_ASSERT(cx->noExecuteDebuggerTop);
return EnterDebuggeeNoExecute::reportIfFoundInStack(cx, script);
}
static void PropagateForcedReturn(JSContext* cx, AbstractFramePtr frame,
HandleValue rval) {
// The Debugger's hooks may return a value that affects the completion
// value of the given frame. For example, a hook may return `{ return: 42 }`
// to terminate the frame and return `42` as the final frame result.
// To accomplish this, the debugger treats these return values as if
// execution of the JS function has been terminated without a pending
// exception, but with a special flag. When the error is handled by the
// interpreter or JIT, the special flag and the error state will be cleared
// and execution will continue from the end of the frame.
MOZ_ASSERT(!cx->isExceptionPending());
cx->setPropagatingForcedReturn();
frame.setReturnValue(rval);
}
[[nodiscard]] static bool AdjustGeneratorResumptionValue(JSContext* cx,
AbstractFramePtr frame,
ResumeMode& resumeMode,
MutableHandleValue vp);
[[nodiscard]] static bool ApplyFrameResumeMode(JSContext* cx,
AbstractFramePtr frame,
ResumeMode resumeMode,
HandleValue rv,
Handle<SavedFrame*> exnStack) {
RootedValue rval(cx, rv);
// The value passed in here is unwrapped and has no guarantees about what
// compartment it may be associated with, so we explicitly wrap it into the
// debuggee compartment.
if (!cx->compartment()->wrap(cx, &rval)) {
return false;
}
if (!AdjustGeneratorResumptionValue(cx, frame, resumeMode, &rval)) {
return false;
}
switch (resumeMode) {
case ResumeMode::Continue:
break;
case ResumeMode::Throw:
// If we have a stack from the original throw, use it instead of
// associating the throw with the current execution point.
if (exnStack) {
cx->setPendingException(rval, exnStack);
} else {
cx->setPendingException(rval, ShouldCaptureStack::Always);
}
return false;
case ResumeMode::Terminate:
cx->reportUncatchableException();
return false;
case ResumeMode::Return:
PropagateForcedReturn(cx, frame, rval);
return false;
default:
MOZ_CRASH("bad Debugger::onEnterFrame resume mode");
}
return true;
}
static bool ApplyFrameResumeMode(JSContext* cx, AbstractFramePtr frame,
ResumeMode resumeMode, HandleValue rval) {
Rooted<SavedFrame*> nullStack(cx);
return ApplyFrameResumeMode(cx, frame, resumeMode, rval, nullStack);
}
bool js::ValueToStableChars(JSContext* cx, const char* fnname,
HandleValue value,
AutoStableStringChars& stableChars) {
if (!value.isString()) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
JSMSG_NOT_EXPECTED_TYPE, fnname, "string",
InformalValueTypeName(value));
return false;
}
Rooted<JSLinearString*> linear(cx, value.toString()->ensureLinear(cx));
if (!linear) {
return false;
}
if (!stableChars.initTwoByte(cx, linear)) {
return false;
}
return true;
}
bool EvalOptions::setFilename(JSContext* cx, const char* filename) {
JS::UniqueChars copy;
if (filename) {
copy = DuplicateString(cx, filename);
if (!copy) {
return false;
}
}
filename_ = std::move(copy);
return true;
}
bool js::ParseEvalOptions(JSContext* cx, HandleValue value,
EvalOptions& options) {
if (!value.isObject()) {
return true;
}
RootedObject opts(cx, &value.toObject());
RootedValue v(cx);
if (!JS_GetProperty(cx, opts, "url", &v)) {
return false;
}
if (!v.isUndefined()) {
RootedString url_str(cx, ToString<CanGC>(cx, v));
if (!url_str) {
return false;
}
UniqueChars url_bytes = JS_EncodeStringToUTF8(cx, url_str);
if (!url_bytes) {
return false;
}
if (!options.setFilename(cx, url_bytes.get())) {
return false;
}
}
if (!JS_GetProperty(cx, opts, "lineNumber", &v)) {
return false;
}
if (!v.isUndefined()) {
uint32_t lineno;
if (!ToUint32(cx, v, &lineno)) {
return false;
}
options.setLineno(lineno);
}
if (!JS_GetProperty(cx, opts, "hideFromDebugger", &v)) {
return false;
}
options.setHideFromDebugger(ToBoolean(v));
if (options.kind() == EvalOptions::EnvKind::GlobalWithExtraOuterBindings) {
if (!JS_GetProperty(cx, opts, "useInnerBindings", &v)) {
return false;
}
if (ToBoolean(v)) {
options.setUseInnerBindings();
}
}
return true;
}
/*** Breakpoints ************************************************************/
bool BreakpointSite::isEmpty() const { return breakpoints.isEmpty(); }
void BreakpointSite::trace(JSTracer* trc) {
for (auto p = breakpoints.begin(); p; p++) {
p->trace(trc);
}
}
void BreakpointSite::finalize(JS::GCContext* gcx) {
while (!breakpoints.isEmpty()) {
breakpoints.begin()->delete_(gcx);
}
}
Breakpoint* BreakpointSite::firstBreakpoint() const {
if (isEmpty()) {
return nullptr;
}
return &(*breakpoints.begin());
}
bool BreakpointSite::hasBreakpoint(Breakpoint* toFind) {
const BreakpointList::Iterator bp(toFind);
for (auto p = breakpoints.begin(); p; p++) {
if (p == bp) {
return true;
}
}
return false;
}
Breakpoint::Breakpoint(Debugger* debugger, HandleObject wrappedDebugger,
BreakpointSite* site, HandleObject handler)
: debugger(debugger),
wrappedDebugger(wrappedDebugger),
site(site),
handler(handler) {
MOZ_ASSERT(UncheckedUnwrap(wrappedDebugger) == debugger->object);
MOZ_ASSERT(handler->compartment() == wrappedDebugger->compartment());
debugger->breakpoints.pushBack(this);
site->breakpoints.pushBack(this);
}
void Breakpoint::trace(JSTracer* trc) {
TraceEdge(trc, &wrappedDebugger, "breakpoint owner");
TraceEdge(trc, &handler, "breakpoint handler");
}
void Breakpoint::delete_(JS::GCContext* gcx) {
debugger->breakpoints.remove(this);
site->breakpoints.remove(this);
gc::Cell* cell = site->owningCell();
gcx->delete_(cell, this, MemoryUse::Breakpoint);
}
void Breakpoint::remove(JS::GCContext* gcx) {
BreakpointSite* savedSite = site;
delete_(gcx);
savedSite->destroyIfEmpty(gcx);
}
Breakpoint* Breakpoint::nextInDebugger() { return debuggerLink.mNext; }
Breakpoint* Breakpoint::nextInSite() { return siteLink.mNext; }
JSBreakpointSite::JSBreakpointSite(JSScript* script, jsbytecode* pc)
: script(script), pc(pc) {
MOZ_ASSERT(!DebugAPI::hasBreakpointsAt(script, pc));
}
void JSBreakpointSite::remove(JS::GCContext* gcx) {
DebugScript::destroyBreakpointSite(gcx, script, pc);
}
void JSBreakpointSite::trace(JSTracer* trc) {
BreakpointSite::trace(trc);
TraceEdge(trc, &script, "breakpoint script");
}
void JSBreakpointSite::delete_(JS::GCContext* gcx) {
BreakpointSite::finalize(gcx);
gcx->delete_(script, this, MemoryUse::BreakpointSite);
}
gc::Cell* JSBreakpointSite::owningCell() { return script; }
Realm* JSBreakpointSite::realm() const { return script->realm(); }
WasmBreakpointSite::WasmBreakpointSite(WasmInstanceObject* instanceObject_,
uint32_t offset_)
: instanceObject(instanceObject_), offset(offset_) {
MOZ_ASSERT(instanceObject_);
MOZ_ASSERT(instanceObject_->instance().debugEnabled());
}
void WasmBreakpointSite::trace(JSTracer* trc) {
BreakpointSite::trace(trc);
TraceEdge(trc, &instanceObject, "breakpoint Wasm instance");
}
void WasmBreakpointSite::remove(JS::GCContext* gcx) {
instanceObject->instance().destroyBreakpointSite(gcx, offset);
}
void WasmBreakpointSite::delete_(JS::GCContext* gcx) {
BreakpointSite::finalize(gcx);
gcx->delete_(instanceObject, this, MemoryUse::BreakpointSite);
}
gc::Cell* WasmBreakpointSite::owningCell() { return instanceObject; }
Realm* WasmBreakpointSite::realm() const { return instanceObject->realm(); }
/*** Debugger hook dispatch *************************************************/
Debugger::Debugger(JSContext* cx, NativeObject* dbg)
: object(dbg),
debuggees(cx->zone()),
uncaughtExceptionHook(nullptr),
allowUnobservedAsmJS(false),
allowUnobservedWasm(false),
exclusiveDebuggerOnEval(false),
inspectNativeCallArguments(false),
collectCoverageInfo(false),
shouldAvoidSideEffects(false),
observedGCs(cx->zone()),
allocationsLog(cx),
trackingAllocationSites(false),
allocationSamplingProbability(1.0),
maxAllocationsLogLength(DEFAULT_MAX_LOG_LENGTH),
allocationsLogOverflowed(false),
frames(cx->zone()),
generatorFrames(cx),
scripts(cx),
sources(cx),
objects(cx),
environments(cx),
wasmInstanceScripts(cx),
wasmInstanceSources(cx) {
cx->check(dbg);
cx->runtime()->debuggerList().insertBack(this);
}
template <typename ElementAccess>
static void RemoveDebuggerEntry(
mozilla::DoublyLinkedList<Debugger, ElementAccess>& list, Debugger* dbg) {
// The "probably" here is because there could technically be multiple lists
// with this type signature and theoretically the debugger could be an entry
// in a different one. That is not actually possible however because there
// is only one list the debugger could be in.
if (list.ElementProbablyInList(dbg)) {
list.remove(dbg);
}
}
Debugger::~Debugger() {
MOZ_ASSERT(debuggees.empty());
allocationsLog.clear();
// Breakpoints should hold us alive, so any breakpoints remaining must be set
// in dying JSScripts. We should clean them up, but this never asserts. I'm
// not sure why.
MOZ_ASSERT(breakpoints.isEmpty());
// We don't have to worry about locking here since Debugger is not
// background finalized.
JSContext* cx = TlsContext.get();
RemoveDebuggerEntry(cx->runtime()->onNewGlobalObjectWatchers(), this);
RemoveDebuggerEntry(cx->runtime()->onGarbageCollectionWatchers(), this);
}
#ifdef DEBUG
/* static */
bool Debugger::isChildJSObject(JSObject* obj) {
return obj->getClass() == &DebuggerFrame::class_ ||
obj->getClass() == &DebuggerScript::class_ ||
obj->getClass() == &DebuggerSource::class_ ||
obj->getClass() == &DebuggerObject::class_ ||
obj->getClass() == &DebuggerEnvironment::class_;
}
#endif
bool Debugger::hasMemory() const {
return object->getReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE).isObject();
}
DebuggerMemory& Debugger::memory() const {
MOZ_ASSERT(hasMemory());
return object->getReservedSlot(JSSLOT_DEBUG_MEMORY_INSTANCE)
.toObject()
.as<DebuggerMemory>();
}
/*** Debugger accessors *******************************************************/
bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
MutableHandleValue vp) {
Rooted<DebuggerFrame*> result(cx);
if (!Debugger::getFrame(cx, iter, &result)) {
return false;
}
vp.setObject(*result);
return true;
}
bool Debugger::getFrame(JSContext* cx, MutableHandle<DebuggerFrame*> result) {
RootedObject proto(
cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
Rooted<NativeObject*> debugger(cx, object);
// Since there is no frame/generator data to associate with this frame, this
// will create a new, "terminated" Debugger.Frame object.
Rooted<DebuggerFrame*> frame(
cx, DebuggerFrame::create(cx, proto, debugger, nullptr, nullptr));
if (!frame) {
return false;
}
result.set(frame);
return true;
}
bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
MutableHandle<DebuggerFrame*> result) {
AbstractFramePtr referent = iter.abstractFramePtr();
MOZ_ASSERT_IF(referent.hasScript(), !referent.script()->selfHosted());
FrameMap::AddPtr p = frames.lookupForAdd(referent);
if (!p) {
Rooted<AbstractGeneratorObject*> genObj(cx);
if (referent.isGeneratorFrame()) {
if (referent.isFunctionFrame()) {
AutoRealm ar(cx, referent.callee());
genObj = GetGeneratorObjectForFrame(cx, referent);
} else {
MOZ_ASSERT(referent.isModuleFrame());
AutoRealm ar(cx, referent.script()->module());
genObj = GetGeneratorObjectForFrame(cx, referent);
}
// If this frame has a generator associated with it, but no on-stack
// Debugger.Frame object was found, there should not be a suspended
// Debugger.Frame either because otherwise slowPathOnResumeFrame would
// have already populated the "frames" map with a Debugger.Frame.
MOZ_ASSERT_IF(genObj, !generatorFrames.has(genObj));
// If the frame's generator is closed, there is no way to associate the
// generator with the frame successfully because there is no way to
// get the generator's callee script, and even if we could, having it
// there would in no way affect the behavior of the frame.
if (genObj && genObj->isClosed()) {
genObj = nullptr;
}
// If no AbstractGeneratorObject exists yet, we create a Debugger.Frame
// below anyway, and Debugger::onNewGenerator() will associate it
// with the AbstractGeneratorObject later when we hit JSOp::Generator.
}
// Create and populate the Debugger.Frame object.
RootedObject proto(
cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
Rooted<NativeObject*> debugger(cx, object);
Rooted<DebuggerFrame*> frame(
cx, DebuggerFrame::create(cx, proto, debugger, &iter, genObj));
if (!frame) {
return false;
}
auto terminateDebuggerFrameGuard = MakeScopeExit([&] {
terminateDebuggerFrame(cx->gcContext(), this, frame, referent);
});
if (genObj) {
DependentAddPtr<GeneratorWeakMap> genPtr(cx, generatorFrames, genObj);
if (!genPtr.add(cx, generatorFrames, genObj, frame)) {
return false;
}
}
if (!ensureExecutionObservabilityOfFrame(cx, referent)) {
return false;
}
if (!frames.add(p, referent, frame)) {
ReportOutOfMemory(cx);
return false;
}
terminateDebuggerFrameGuard.release();
}
result.set(p->value());
return true;
}
bool Debugger::getFrame(JSContext* cx, Handle<AbstractGeneratorObject*> genObj,
MutableHandle<DebuggerFrame*> result) {
// To create a Debugger.Frame for a running generator, we'd also need a
// FrameIter for its stack frame. We could make this work by searching the
// stack for the generator's frame, but for the moment, we only need this
// function to handle generators we've found on promises' reaction records,
// which should always be suspended.
MOZ_ASSERT(genObj->isSuspended());
// Do we have an existing Debugger.Frame for this generator?
DependentAddPtr<GeneratorWeakMap> p(cx, generatorFrames, genObj);
if (p) {
MOZ_ASSERT(&p->value()->unwrappedGenerator() == genObj);
result.set(p->value());
return true;
}
// Create a new Debugger.Frame.
RootedObject proto(
cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
Rooted<NativeObject*> debugger(cx, object);
result.set(DebuggerFrame::create(cx, proto, debugger, nullptr, genObj));
if (!result) {
return false;
}
if (!p.add(cx, generatorFrames, genObj, result)) {
terminateDebuggerFrame(cx->gcContext(), this, result, NullFramePtr());
return false;
}
return true;
}
static bool DebuggerExists(
GlobalObject* global, const std::function<bool(Debugger* dbg)>& predicate) {
// The GC analysis can't determine that the predicate can't GC, so let it know
// explicitly.
JS::AutoSuppressGCAnalysis nogc;
for (Realm::DebuggerVectorEntry& entry : global->getDebuggers(nogc)) {
// Callbacks should not create new references to the debugger, so don't
// use a barrier. This allows this method to be called during GC.
if (predicate(entry.dbg.unbarrieredGet())) {
return true;
}
}
return false;
}
/* static */
bool Debugger::hasLiveHook(GlobalObject* global, Hook which) {
return DebuggerExists(global,
[=](Debugger* dbg) { return dbg->getHook(which); });
}
/* static */
bool DebugAPI::debuggerObservesAllExecution(GlobalObject* global) {
return DebuggerExists(
global, [=](Debugger* dbg) { return dbg->observesAllExecution(); });
}
/* static */
bool DebugAPI::debuggerObservesCoverage(GlobalObject* global) {
return DebuggerExists(global,
[=](Debugger* dbg) { return dbg->observesCoverage(); });
}
/* static */
bool DebugAPI::debuggerObservesAsmJS(GlobalObject* global) {
return DebuggerExists(global,
[=](Debugger* dbg) { return dbg->observesAsmJS(); });
}
/* static */
bool DebugAPI::debuggerObservesWasm(GlobalObject* global) {
return DebuggerExists(global,
[=](Debugger* dbg) { return dbg->observesWasm(); });
}
/* static */
bool DebugAPI::debuggerObservesNativeCall(GlobalObject* global) {
return DebuggerExists(
global, [=](Debugger* dbg) { return dbg->observesNativeCalls(); });
}
/* static */
bool DebugAPI::hasExceptionUnwindHook(GlobalObject* global) {
return Debugger::hasLiveHook(global, Debugger::OnExceptionUnwind);
}
/* static */
bool DebugAPI::hasDebuggerStatementHook(GlobalObject* global) {
return Debugger::hasLiveHook(global, Debugger::OnDebuggerStatement);
}
template <typename HookIsEnabledFun /* bool (Debugger*) */>
bool DebuggerList<HookIsEnabledFun>::init(JSContext* cx) {
// Determine which debuggers will receive this event, and in what order.
// Make a copy of the list, since the original is mutable and we will be
// calling into arbitrary JS.
Handle<GlobalObject*> global = cx->global();
JS::AutoAssertNoGC nogc;
for (Realm::DebuggerVectorEntry& entry : global->getDebuggers(nogc)) {
Debugger* dbg = entry.dbg;
if (dbg->isHookCallAllowed(cx) && hookIsEnabled(dbg)) {
if (!debuggers.append(ObjectValue(*dbg->toJSObject()))) {
return false;
}
}
}
return true;
}
template <typename HookIsEnabledFun /* bool (Debugger*) */>
template <typename FireHookFun /* bool (Debugger*) */>
bool DebuggerList<HookIsEnabledFun>::dispatchHook(JSContext* cx,
FireHookFun fireHook) {
// Preserve the debuggee's microtask event queue while we run the hooks, so
// the debugger's microtask checkpoints don't run from the debuggee's
// microtasks, and vice versa.
JS::AutoDebuggerJobQueueInterruption adjqi;
if (!adjqi.init(cx)) {
return false;
}
// Deliver the event to each debugger, checking again to make sure it
// should still be delivered.
Handle<GlobalObject*> global = cx->global();
for (Value* p = debuggers.begin(); p != debuggers.end(); p++) {
Debugger* dbg = Debugger::fromJSObject(&p->toObject());
EnterDebuggeeNoExecute nx(cx, *dbg, adjqi);
if (dbg->debuggees.has(global) && hookIsEnabled(dbg)) {
bool result =
dbg->enterDebuggerHook(cx, [&]() -> bool { return fireHook(dbg); });
adjqi.runJobs();
if (!result) {
return false;
}
}
}
return true;
}
template <typename HookIsEnabledFun /* bool (Debugger*) */>
template <typename FireHookFun /* bool (Debugger*) */>
void DebuggerList<HookIsEnabledFun>::dispatchQuietHook(JSContext* cx,
FireHookFun fireHook) {
bool result =
dispatchHook(cx, [&](Debugger* dbg) -> bool { return fireHook(dbg); });
// dispatchHook may fail due to OOM. This OOM is not handlable at the
// callsites of dispatchQuietHook in the engine.
if (!result) {
cx->clearPendingException();
}
}
template <typename HookIsEnabledFun /* bool (Debugger*) */>
template <typename FireHookFun /* bool (Debugger*, ResumeMode&, MutableHandleValue vp) */>
bool DebuggerList<HookIsEnabledFun>::dispatchResumptionHook(
JSContext* cx, AbstractFramePtr frame, FireHookFun fireHook) {
ResumeMode resumeMode = ResumeMode::Continue;
RootedValue rval(cx);
return dispatchHook(cx,
[&](Debugger* dbg) -> bool {
return fireHook(dbg, resumeMode, &rval);
}) &&
ApplyFrameResumeMode(cx, frame, resumeMode, rval);
}
JSObject* Debugger::getHook(Hook hook) const {
MOZ_ASSERT(hook >= 0 && hook < HookCount);
const Value& v = object->getReservedSlot(JSSLOT_DEBUG_HOOK_START +
std::underlying_type_t<Hook>(hook));
return v.isUndefined() ? nullptr : &v.toObject();
}
bool Debugger::hasAnyLiveHooks() const {
// A onNewGlobalObject hook does not hold its Debugger live, so its behavior
// is nondeterministic. This behavior is not satisfying, but it is at least
// documented.
if (getHook(OnDebuggerStatement) || getHook(OnExceptionUnwind) ||
getHook(OnNewScript) || getHook(OnEnterFrame)) {
return true;
}
return false;
}
/* static */
bool DebugAPI::slowPathOnEnterFrame(JSContext* cx, AbstractFramePtr frame) {
#ifdef MOZ_EXECUTION_TRACING
if (cx->hasExecutionTracer()) {
cx->getExecutionTracer().onEnterFrame(cx, frame);
}
#endif
return Debugger::dispatchResumptionHook(
cx, frame,
[frame](Debugger* dbg) -> bool {
return dbg->observesFrame(frame) && dbg->observesEnterFrame();
},
[&](Debugger* dbg, ResumeMode& resumeMode, MutableHandleValue vp)
-> bool { return dbg->fireEnterFrame(cx, resumeMode, vp); });
}
/* static */
bool DebugAPI::slowPathOnResumeFrame(JSContext* cx, AbstractFramePtr frame) {
#ifdef MOZ_EXECUTION_TRACING
if (cx->hasExecutionTracer()) {
cx->getExecutionTracer().onEnterFrame(cx, frame);
}
#endif
// Don't count on this method to be called every time a generator is
// resumed! This is called only if the frame's debuggee bit is set,
// i.e. the script has breakpoints or the frame is stepping.
MOZ_ASSERT(frame.isGeneratorFrame());
MOZ_ASSERT(frame.isDebuggee());
Rooted<AbstractGeneratorObject*> genObj(
cx, GetGeneratorObjectForFrame(cx, frame));
MOZ_ASSERT(genObj);
// If there is an OOM, we mark all of the Debugger.Frame objects terminated
// because we want to ensure that none of the frames are in a partially
// initialized state where they are in "generatorFrames" but not "frames".
auto terminateDebuggerFramesGuard = MakeScopeExit([&] {
Debugger::terminateDebuggerFrames(cx, frame);
MOZ_ASSERT(!DebugAPI::inFrameMaps(frame));
});
// For each debugger, if there is an existing Debugger.Frame object for the
// resumed `frame`, update it with the new frame pointer and make sure the
// frame is observable.
FrameIter iter(cx);
MOZ_ASSERT(iter.abstractFramePtr() == frame);
{
JS::AutoAssertNoGC nogc;
for (Realm::DebuggerVectorEntry& entry :
frame.global()->getDebuggers(nogc)) {
Debugger* dbg = entry.dbg;
if (Debugger::GeneratorWeakMap::Ptr generatorEntry =
dbg->generatorFrames.lookup(genObj)) {
DebuggerFrame* frameObj = generatorEntry->value();
MOZ_ASSERT(&frameObj->unwrappedGenerator() == genObj);
if (!dbg->frames.putNew(frame, frameObj)) {
ReportOutOfMemory(cx);
return false;
}
if (!frameObj->resume(iter)) {
return false;
}
}
}
}
terminateDebuggerFramesGuard.release();
return slowPathOnEnterFrame(cx, frame);
}
/* static */
NativeResumeMode DebugAPI::slowPathOnNativeCall(JSContext* cx,
const CallArgs& args,
CallReason reason) {
if (!cx->realm()->debuggerObservesNativeCall()) {
return NativeResumeMode::Continue;
}
DebuggerList debuggerList(cx, [](Debugger* dbg) -> bool {
return dbg->getHook(Debugger::OnNativeCall);
});
if (!debuggerList.init(cx)) {
return NativeResumeMode::Abort;
}
if (debuggerList.empty()) {
return NativeResumeMode::Continue;
}
// The onNativeCall hook is fired when self hosted functions are called,
// and any other self hosted function or C++ native that is directly called
// by the self hosted function is considered to be part of the same
// native call, except for the following 4 cases:
//