-
Notifications
You must be signed in to change notification settings - Fork 54
/
Debugger.h
2255 lines (1962 loc) · 90.7 KB
/
Debugger.h
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/. */
#ifndef vm_Debugger_h
#define vm_Debugger_h
#include "mozilla/DoublyLinkedList.h"
#include "mozilla/GuardObjects.h"
#include "mozilla/LinkedList.h"
#include "mozilla/Range.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Vector.h"
#include "ds/TraceableFifo.h"
#include "gc/Barrier.h"
#include "gc/WeakMap.h"
#include "js/Debug.h"
#include "js/GCVariant.h"
#include "js/HashTable.h"
#include "js/Promise.h"
#include "js/Result.h"
#include "js/RootingAPI.h"
#include "js/Utility.h"
#include "js/Wrapper.h"
#include "proxy/DeadObjectProxy.h"
#include "vm/GeneratorObject.h"
#include "vm/GlobalObject.h"
#include "vm/JSContext.h"
#include "vm/Realm.h"
#include "vm/SavedStacks.h"
#include "vm/Stack.h"
/*
* Windows 3.x used a cooperative multitasking model, with a Yield macro that
* let you relinquish control to other cooperative threads. Microsoft replaced
* it with an empty macro long ago. We should be free to use it in our code.
*/
#undef Yield
namespace js {
class AbstractGeneratorObject;
class Breakpoint;
class DebuggerMemory;
class PromiseObject;
class ScriptedOnStepHandler;
class ScriptedOnPopHandler;
class WasmInstanceObject;
/**
* Tells how the JS engine should resume debuggee execution after firing a
* debugger hook. Most debugger hooks get to choose how the debuggee proceeds;
* see js/src/doc/Debugger/Conventions.md under "Resumption Values".
*
* Debugger::processHandlerResult() translates between JavaScript values and
* this enum.
*
* The values `ResumeMode::Throw` and `ResumeMode::Return` are always
* associated with a value (the exception value or return value). Sometimes
* this is represented as an explicit `JS::Value` variable or parameter,
* declared alongside the `ResumeMode`. In other cases, especially when
* ResumeMode is used as a return type (as in Debugger::onEnterFrame), the
* value is stashed in `cx`'s pending exception slot or the topmost frame's
* return value slot.
*/
enum class ResumeMode {
/**
* The debuggee should continue unchanged.
*
* This corresponds to a resumption value of `undefined`.
*/
Continue,
/**
* Throw an exception in the debuggee.
*
* This corresponds to a resumption value of `{throw: <value>}`.
*/
Throw,
/**
* Terminate the debuggee, as if it had been cancelled via the "slow
* script" ribbon.
*
* This corresponds to a resumption value of `null`.
*/
Terminate,
/**
* Force the debuggee to return from the current frame.
*
* This corresponds to a resumption value of `{return: <value>}`.
*/
Return,
};
/**
* A completion value, describing how some sort of JavaScript evaluation
* completed. This is used to tell an onPop handler what's going on with the
* frame, and to report the outcome of call, apply, setProperty, and getProperty
* operations.
*
* Local variables of type Completion should be held in Rooted locations,
* and passed using Handle and MutableHandle.
*/
class Completion {
public:
struct Return {
explicit Return(const Value& value) : value(value) {}
Value value;
void trace(JSTracer* trc) {
JS::UnsafeTraceRoot(trc, &value, "js::Completion::Return::value");
}
};
struct Throw {
Throw(const Value& exception, SavedFrame* stack)
: exception(exception), stack(stack) {}
Value exception;
SavedFrame* stack;
void trace(JSTracer* trc) {
JS::UnsafeTraceRoot(trc, &exception, "js::Completion::Throw::exception");
JS::UnsafeTraceRoot(trc, &stack, "js::Completion::Throw::stack");
}
};
struct Terminate {
void trace(JSTracer* trc) {}
};
struct InitialYield {
explicit InitialYield(AbstractGeneratorObject* generatorObject)
: generatorObject(generatorObject) {}
AbstractGeneratorObject* generatorObject;
void trace(JSTracer* trc) {
JS::UnsafeTraceRoot(trc, &generatorObject,
"js::Completion::InitialYield::generatorObject");
}
};
struct Yield {
Yield(AbstractGeneratorObject* generatorObject, const Value& iteratorResult)
: generatorObject(generatorObject), iteratorResult(iteratorResult) {}
AbstractGeneratorObject* generatorObject;
Value iteratorResult;
void trace(JSTracer* trc) {
JS::UnsafeTraceRoot(trc, &generatorObject,
"js::Completion::Yield::generatorObject");
JS::UnsafeTraceRoot(trc, &iteratorResult,
"js::Completion::Yield::iteratorResult");
}
};
struct Await {
Await(AbstractGeneratorObject* generatorObject, const Value& awaitee)
: generatorObject(generatorObject), awaitee(awaitee) {}
AbstractGeneratorObject* generatorObject;
Value awaitee;
void trace(JSTracer* trc) {
JS::UnsafeTraceRoot(trc, &generatorObject,
"js::Completion::Await::generatorObject");
JS::UnsafeTraceRoot(trc, &awaitee, "js::Completion::Await::awaitee");
}
};
// The JS::Result macros want to assign to an existing variable, so having a
// default constructor is handy.
Completion() : variant(Terminate()) {}
// Construct a completion from a specific variant.
//
// Unfortunately, using a template here would prevent the implicit definitions
// of the copy and move constructor and assignment operators, which is icky.
explicit Completion(Return&& variant)
: variant(std::forward<Return>(variant)) {}
explicit Completion(Throw&& variant)
: variant(std::forward<Throw>(variant)) {}
explicit Completion(Terminate&& variant)
: variant(std::forward<Terminate>(variant)) {}
explicit Completion(InitialYield&& variant)
: variant(std::forward<InitialYield>(variant)) {}
explicit Completion(Yield&& variant)
: variant(std::forward<Yield>(variant)) {}
explicit Completion(Await&& variant)
: variant(std::forward<Await>(variant)) {}
// Capture a JavaScript operation result as a Completion value. This clears
// any exception and stack from cx, taking ownership of them itself.
static Completion fromJSResult(JSContext* cx, bool ok, const Value& rv);
// Construct a completion given an AbstractFramePtr that is being popped. This
// clears any exception and stack from cx, taking ownership of them itself.
static Completion fromJSFramePop(JSContext* cx, AbstractFramePtr frame,
const jsbytecode* pc, bool ok);
template <typename V>
bool is() const {
return variant.template is<V>();
}
template <typename V>
V& as() {
return variant.template as<V>();
}
template <typename V>
const V& as() const {
return variant.template as<V>();
}
void trace(JSTracer* trc);
/* True if this completion is a suspension of a generator or async call. */
bool suspending() const {
return variant.is<InitialYield>() || variant.is<Yield>() ||
variant.is<Await>();
}
/*
* If this completion is a suspension of a generator or async call, return the
* call's generator object, nullptr otherwise.
*/
AbstractGeneratorObject* maybeGeneratorObject() const;
/* Set `result` to a Debugger API completion value describing this completion.
*/
bool buildCompletionValue(JSContext* cx, Debugger* dbg,
MutableHandleValue result) const;
/*
* Set `resumeMode`, `value`, and `exnStack` to values describing this
* completion.
*/
void toResumeMode(ResumeMode& resumeMode, MutableHandleValue value,
MutableHandleSavedFrame exnStack) const;
/*
* Given a `ResumeMode` and value (typically derived from a resumption value
* returned by a Debugger hook), update this completion as requested.
*/
void updateForNextHandler(ResumeMode resumeMode, HandleValue value);
private:
using Variant =
mozilla::Variant<Return, Throw, Terminate, InitialYield, Yield, Await>;
struct BuildValueMatcher;
struct ToResumeModeMatcher;
Variant variant;
};
typedef HashSet<WeakHeapPtrGlobalObject,
MovableCellHasher<WeakHeapPtrGlobalObject>, ZoneAllocPolicy>
WeakGlobalObjectSet;
#ifdef DEBUG
extern void CheckDebuggeeThing(JSScript* script, bool invisibleOk);
extern void CheckDebuggeeThing(LazyScript* script, bool invisibleOk);
extern void CheckDebuggeeThing(JSObject* obj, bool invisibleOk);
#endif
/*
* A weakmap from GC thing keys to JSObject values that supports the keys being
* in different compartments to the values. All values must be in the same
* compartment.
*
* The purpose of this is to allow the garbage collector to easily find edges
* from debuggee object compartments to debugger compartments when calculating
* the compartment groups. Note that these edges are the inverse of the edges
* stored in the cross compartment map.
*
* The current implementation results in all debuggee object compartments being
* swept in the same group as the debugger. This is a conservative approach,
* and compartments may be unnecessarily grouped, however it results in a
* simpler and faster implementation.
*
* If InvisibleKeysOk is true, then the map can have keys in invisible-to-
* debugger compartments. If it is false, we assert that such entries are never
* created.
*
* Also note that keys in these weakmaps can be in any compartment, debuggee or
* not, because they are not deleted when a compartment is no longer a
* debuggee: the values need to maintain object identity across add/remove/add
* transitions. (Frames are an exception to the rule. Existing Debugger.Frame
* objects are killed when debugging is disabled for their compartment, and if
* it's re-enabled later, new Frame objects are created.)
*/
template <class UnbarrieredKey, bool InvisibleKeysOk = false>
class DebuggerWeakMap
: private WeakMap<HeapPtr<UnbarrieredKey>, HeapPtr<JSObject*>> {
private:
typedef HeapPtr<UnbarrieredKey> Key;
typedef HeapPtr<JSObject*> Value;
typedef HashMap<JS::Zone*, uintptr_t, DefaultHasher<JS::Zone*>,
ZoneAllocPolicy>
CountMap;
JS::Compartment* compartment;
public:
typedef WeakMap<Key, Value> Base;
explicit DebuggerWeakMap(JSContext* cx)
: Base(cx), compartment(cx->compartment()) {}
public:
// Expose those parts of HashMap public interface that are used by Debugger
// methods.
using Entry = typename Base::Entry;
using Ptr = typename Base::Ptr;
using AddPtr = typename Base::AddPtr;
using Range = typename Base::Range;
using Lookup = typename Base::Lookup;
// Expose WeakMap public interface.
using Base::all;
using Base::has;
using Base::lookup;
using Base::lookupForAdd;
using Base::remove;
using Base::trace;
class Enum : public Base::Enum {
public:
explicit Enum(DebuggerWeakMap& map) : Base::Enum(map) {}
};
template <typename KeyInput, typename ValueInput>
bool relookupOrAdd(AddPtr& p, const KeyInput& k, const ValueInput& v) {
MOZ_ASSERT(v->compartment() == this->compartment);
#ifdef DEBUG
CheckDebuggeeThing(k, InvisibleKeysOk);
#endif
MOZ_ASSERT(!Base::has(k));
bool ok = Base::relookupOrAdd(p, k, v);
return ok;
}
public:
template <void(traceValueEdges)(JSTracer*, JSObject*)>
void traceCrossCompartmentEdges(JSTracer* tracer) {
for (Enum e(*this); !e.empty(); e.popFront()) {
traceValueEdges(tracer, e.front().value());
Key key = e.front().key();
TraceEdge(tracer, &key, "Debugger WeakMap key");
if (key != e.front().key()) {
e.rekeyFront(key);
}
key.unsafeSet(nullptr);
}
}
private:
#ifdef JS_GC_ZEAL
// Let the weak map marking verifier know that this map can
// contain keys in other zones.
virtual bool allowKeysInOtherZones() const override { return true; }
#endif
};
class LeaveDebuggeeNoExecute;
// Suppresses all debuggee NX checks, i.e., allow all execution. Used to allow
// certain whitelisted operations to execute code.
//
// WARNING
// WARNING Do not use this unless you know what you are doing!
// WARNING
class AutoSuppressDebuggeeNoExecuteChecks {
EnterDebuggeeNoExecute** stack_;
EnterDebuggeeNoExecute* prev_;
public:
explicit AutoSuppressDebuggeeNoExecuteChecks(JSContext* cx) {
stack_ = &cx->noExecuteDebuggerTop.ref();
prev_ = *stack_;
*stack_ = nullptr;
}
~AutoSuppressDebuggeeNoExecuteChecks() {
MOZ_ASSERT(!*stack_);
*stack_ = prev_;
}
};
class MOZ_RAII EvalOptions {
JS::UniqueChars filename_;
unsigned lineno_ = 1;
public:
EvalOptions() = default;
~EvalOptions() = default;
const char* filename() const { return filename_.get(); }
unsigned lineno() const { return lineno_; }
MOZ_MUST_USE bool setFilename(JSContext* cx, const char* filename);
void setLineno(unsigned lineno) { lineno_ = lineno; }
};
/*
* Env is the type of what ES5 calls "lexical environments" (runtime activations
* of lexical scopes). This is currently just JSObject, and is implemented by
* CallObject, LexicalEnvironmentObject, and WithEnvironmentObject, among
* others--but environments and objects are really two different concepts.
*/
typedef JSObject Env;
// One of a real JSScript, a real LazyScript, or synthesized.
//
// If synthesized, the referent is one of the following:
//
// 1. A WasmInstanceObject, denoting a synthesized toplevel wasm module
// script.
// 2. A wasm JSFunction, denoting a synthesized wasm function script.
// NYI!
typedef mozilla::Variant<JSScript*, LazyScript*, WasmInstanceObject*>
DebuggerScriptReferent;
// Either a ScriptSourceObject, for ordinary JS, or a WasmInstanceObject,
// denoting the synthesized source of a wasm module.
typedef mozilla::Variant<ScriptSourceObject*, WasmInstanceObject*>
DebuggerSourceReferent;
class Debugger : private mozilla::LinkedListElement<Debugger> {
friend class Breakpoint;
friend class DebuggerFrame;
friend class DebuggerMemory;
friend struct JSRuntime::GlobalObjectWatchersLinkAccess<Debugger>;
friend class SavedStacks;
friend class ScriptedOnStepHandler;
friend class ScriptedOnPopHandler;
friend class mozilla::LinkedListElement<Debugger>;
friend class mozilla::LinkedList<Debugger>;
friend bool(::JS_DefineDebuggerObject)(JSContext* cx, JS::HandleObject obj);
friend bool(::JS::dbg::IsDebugger)(JSObject&);
friend bool(::JS::dbg::GetDebuggeeGlobals)(JSContext*, JSObject&,
MutableHandleObjectVector);
friend bool JS::dbg::FireOnGarbageCollectionHookRequired(JSContext* cx);
friend bool JS::dbg::FireOnGarbageCollectionHook(
JSContext* cx, JS::dbg::GarbageCollectionEvent::Ptr&& data);
public:
enum Hook {
OnDebuggerStatement,
OnExceptionUnwind,
OnNewScript,
OnEnterFrame,
OnNewGlobalObject,
OnNewPromise,
OnPromiseSettled,
OnGarbageCollection,
HookCount
};
enum {
JSSLOT_DEBUG_PROTO_START,
JSSLOT_DEBUG_FRAME_PROTO = JSSLOT_DEBUG_PROTO_START,
JSSLOT_DEBUG_ENV_PROTO,
JSSLOT_DEBUG_OBJECT_PROTO,
JSSLOT_DEBUG_SCRIPT_PROTO,
JSSLOT_DEBUG_SOURCE_PROTO,
JSSLOT_DEBUG_MEMORY_PROTO,
JSSLOT_DEBUG_PROTO_STOP,
JSSLOT_DEBUG_HOOK_START = JSSLOT_DEBUG_PROTO_STOP,
JSSLOT_DEBUG_HOOK_STOP = JSSLOT_DEBUG_HOOK_START + HookCount,
JSSLOT_DEBUG_MEMORY_INSTANCE = JSSLOT_DEBUG_HOOK_STOP,
JSSLOT_DEBUG_COUNT
};
class ExecutionObservableSet {
public:
typedef HashSet<Zone*>::Range ZoneRange;
virtual Zone* singleZone() const { return nullptr; }
virtual JSScript* singleScriptForZoneInvalidation() const {
return nullptr;
}
virtual const HashSet<Zone*>* zones() const { return nullptr; }
virtual bool shouldRecompileOrInvalidate(JSScript* script) const = 0;
virtual bool shouldMarkAsDebuggee(FrameIter& iter) const = 0;
};
// This enum is converted to and compare with bool values; NotObserving
// must be 0 and Observing must be 1.
enum IsObserving { NotObserving = 0, Observing = 1 };
// Return true if the given realm is a debuggee of this debugger,
// false otherwise.
bool isDebuggeeUnbarriered(const Realm* realm) const;
// Return true if this Debugger observed a debuggee that participated in the
// GC identified by the given GC number. Return false otherwise.
// May return false negatives if we have hit OOM.
bool observedGC(uint64_t majorGCNumber) const {
return observedGCs.has(majorGCNumber);
}
// Notify this Debugger that one or more of its debuggees is participating
// in the GC identified by the given GC number.
bool debuggeeIsBeingCollected(uint64_t majorGCNumber) {
return observedGCs.put(majorGCNumber);
}
bool isEnabled() const { return enabled; }
static SavedFrame* getObjectAllocationSite(JSObject& obj);
struct AllocationsLogEntry {
AllocationsLogEntry(HandleObject frame, mozilla::TimeStamp when,
const char* className, HandleAtom ctorName, size_t size,
bool inNursery)
: frame(frame),
when(when),
className(className),
ctorName(ctorName),
size(size),
inNursery(inNursery) {
MOZ_ASSERT_IF(frame, UncheckedUnwrap(frame)->is<SavedFrame>() ||
IsDeadProxyObject(frame));
}
HeapPtr<JSObject*> frame;
mozilla::TimeStamp when;
const char* className;
HeapPtr<JSAtom*> ctorName;
size_t size;
bool inNursery;
void trace(JSTracer* trc) {
TraceNullableEdge(trc, &frame, "Debugger::AllocationsLogEntry::frame");
TraceNullableEdge(trc, &ctorName,
"Debugger::AllocationsLogEntry::ctorName");
}
};
// Barrier methods so we can have WeakHeapPtr<Debugger*>.
static void readBarrier(Debugger* dbg) {
InternalBarrierMethods<JSObject*>::readBarrier(dbg->object);
}
static void writeBarrierPost(Debugger** vp, Debugger* prev, Debugger* next) {}
#ifdef DEBUG
static void assertThingIsNotGray(Debugger* dbg) { return; }
#endif
/*
* Return true if the given global is being observed by at least one
* Debugger that is tracking allocations.
*/
static bool isObservedByDebuggerTrackingAllocations(
const GlobalObject& debuggee);
private:
GCPtrNativeObject object; /* The Debugger object. Strong reference. */
WeakGlobalObjectSet
debuggees; /* Debuggee globals. Cross-compartment weak references. */
JS::ZoneSet debuggeeZones; /* Set of zones that we have debuggees in. */
js::GCPtrObject uncaughtExceptionHook; /* Strong reference. */
bool enabled;
bool allowUnobservedAsmJS;
// Whether to enable code coverage on the Debuggee.
bool collectCoverageInfo;
template <typename T>
struct DebuggerLinkAccess {
static mozilla::DoublyLinkedListElement<T>& Get(T* aThis) {
return aThis->debuggerLink;
}
};
// List of all js::Breakpoints in this debugger.
using BreakpointList =
mozilla::DoublyLinkedList<js::Breakpoint,
DebuggerLinkAccess<js::Breakpoint>>;
BreakpointList breakpoints;
// The set of GC numbers for which one or more of this Debugger's observed
// debuggees participated in.
using GCNumberSet =
HashSet<uint64_t, DefaultHasher<uint64_t>, ZoneAllocPolicy>;
GCNumberSet observedGCs;
using AllocationsLog = js::TraceableFifo<AllocationsLogEntry>;
AllocationsLog allocationsLog;
bool trackingAllocationSites;
double allocationSamplingProbability;
size_t maxAllocationsLogLength;
bool allocationsLogOverflowed;
static const size_t DEFAULT_MAX_LOG_LENGTH = 5000;
MOZ_MUST_USE bool appendAllocationSite(JSContext* cx, HandleObject obj,
HandleSavedFrame frame,
mozilla::TimeStamp when);
/*
* Recompute the set of debuggee zones based on the set of debuggee globals.
*/
void recomputeDebuggeeZoneSet();
/*
* Return true if there is an existing object metadata callback for the
* given global's compartment that will prevent our instrumentation of
* allocations.
*/
static bool cannotTrackAllocations(const GlobalObject& global);
/*
* Add allocations tracking for objects allocated within the given
* debuggee's compartment. The given debuggee global must be observed by at
* least one Debugger that is enabled and tracking allocations.
*/
static MOZ_MUST_USE bool addAllocationsTracking(
JSContext* cx, Handle<GlobalObject*> debuggee);
/*
* Remove allocations tracking for objects allocated within the given
* global's compartment. This is a no-op if there are still Debuggers
* observing this global and who are tracking allocations.
*/
static void removeAllocationsTracking(GlobalObject& global);
/*
* Add or remove allocations tracking for all debuggees.
*/
MOZ_MUST_USE bool addAllocationsTrackingForAllDebuggees(JSContext* cx);
void removeAllocationsTrackingForAllDebuggees();
/*
* If this Debugger is enabled, and has a onNewGlobalObject handler, then
* this link is inserted into the list headed by
* JSRuntime::onNewGlobalObjectWatchers.
*/
mozilla::DoublyLinkedListElement<Debugger> onNewGlobalObjectWatchersLink;
/*
* Map from stack frames that are currently on the stack to Debugger.Frame
* instances.
*
* The keys are always live stack frames. We drop them from this map as
* soon as they leave the stack (see slowPathOnLeaveFrame) and in
* removeDebuggee.
*
* We don't trace the keys of this map (the frames are on the stack and
* thus necessarily live), but we do trace the values. It's like a WeakMap
* that way, but since stack frames are not gc-things, the implementation
* has to be different.
*/
typedef HashMap<AbstractFramePtr, HeapPtr<DebuggerFrame*>,
DefaultHasher<AbstractFramePtr>, ZoneAllocPolicy>
FrameMap;
FrameMap frames;
/*
* Map from generator objects to their Debugger.Frame instances.
*
* When a Debugger.Frame is created for a generator frame, it is added to
* this map and remains there for the lifetime of the generator, whether
* that frame is on the stack at the moment or not. This is in addition to
* the entry in `frames` that exists as long as the generator frame is on
* the stack.
*
* We need to keep the Debugger.Frame object alive to deliver it to the
* onEnterFrame handler on resume, and to retain onStep and onPop hooks.
*
* An entry is present in this table when:
* - both the debuggee generator object and the Debugger.Frame object exist
* - the Debugger.Frame's owner is still an enabled debugger of
* the debuggee compartment
* regardless of whether the frame is currently suspended. (This list is
* meant to explain why we update the table in the particular places where
* we do so.)
*
* An entry in this table exists if and only if the Debugger.Frame's
* GENERATOR_INFO_SLOT is set.
*/
typedef DebuggerWeakMap<JSObject*> GeneratorWeakMap;
GeneratorWeakMap generatorFrames;
/* An ephemeral map from JSScript* to Debugger.Script instances. */
typedef DebuggerWeakMap<JSScript*> ScriptWeakMap;
ScriptWeakMap scripts;
using LazyScriptWeakMap = DebuggerWeakMap<LazyScript*>;
LazyScriptWeakMap lazyScripts;
using LazyScriptVector = JS::GCVector<LazyScript*>;
// The map from debuggee source script objects to their Debugger.Source
// instances.
typedef DebuggerWeakMap<JSObject*, true> SourceWeakMap;
SourceWeakMap sources;
// The map from debuggee objects to their Debugger.Object instances.
typedef DebuggerWeakMap<JSObject*> ObjectWeakMap;
ObjectWeakMap objects;
// The map from debuggee Envs to Debugger.Environment instances.
ObjectWeakMap environments;
// The map from WasmInstanceObjects to synthesized Debugger.Script
// instances.
typedef DebuggerWeakMap<WasmInstanceObject*> WasmInstanceWeakMap;
WasmInstanceWeakMap wasmInstanceScripts;
// The map from WasmInstanceObjects to synthesized Debugger.Source
// instances.
WasmInstanceWeakMap wasmInstanceSources;
// Keep track of tracelogger last drained identifiers to know if there are
// lost events.
#ifdef NIGHTLY_BUILD
uint32_t traceLoggerLastDrainedSize;
uint32_t traceLoggerLastDrainedIteration;
#endif
uint32_t traceLoggerScriptedCallsLastDrainedSize;
uint32_t traceLoggerScriptedCallsLastDrainedIteration;
class QueryBase;
class ScriptQuery;
class SourceQuery;
class ObjectQuery;
enum class FromSweep { No, Yes };
MOZ_MUST_USE bool addDebuggeeGlobal(JSContext* cx, Handle<GlobalObject*> obj);
void removeDebuggeeGlobal(FreeOp* fop, GlobalObject* global,
WeakGlobalObjectSet::Enum* debugEnum,
FromSweep fromSweep);
enum class CallUncaughtExceptionHook { No, Yes };
/*
* Apply the resumption information in (resumeMode, vp) to `frame` in
* anticipation of returning to the debuggee.
*
* This is the usual path for returning from the debugger to the debuggee
* when we have a resumption value to apply. This does final checks on the
* result value and exits the debugger's realm by calling `ar.reset()`.
* Some hooks don't call this because they don't allow the debugger to
* control resumption; those just call `ar.reset()` and return.
*/
ResumeMode leaveDebugger(mozilla::Maybe<AutoRealm>& ar,
AbstractFramePtr frame,
const mozilla::Maybe<HandleValue>& maybeThisv,
CallUncaughtExceptionHook callHook,
ResumeMode resumeMode, MutableHandleValue vp);
/*
* Report and clear the pending exception on ar.context, if any, and return
* ResumeMode::Terminate.
*/
ResumeMode reportUncaughtException(mozilla::Maybe<AutoRealm>& ar);
/*
* Cope with an error or exception in a debugger hook.
*
* If callHook is true, then call the uncaughtExceptionHook, if any. If, in
* addition, vp is given, then parse the value returned by
* uncaughtExceptionHook as a resumption value.
*
* If there is no uncaughtExceptionHook, or if it fails, report and clear
* the pending exception on ar.context and return ResumeMode::Terminate.
*
* This always calls `ar.reset()`; ar is a parameter because this method
* must do some things in the debugger realm and some things in the
* debuggee realm.
*/
ResumeMode handleUncaughtException(mozilla::Maybe<AutoRealm>& ar);
ResumeMode handleUncaughtException(
mozilla::Maybe<AutoRealm>& ar, MutableHandleValue vp,
const mozilla::Maybe<HandleValue>& thisVForCheck = mozilla::Nothing(),
AbstractFramePtr frame = NullFramePtr());
ResumeMode handleUncaughtExceptionHelper(
mozilla::Maybe<AutoRealm>& ar, MutableHandleValue* vp,
const mozilla::Maybe<HandleValue>& thisVForCheck, AbstractFramePtr frame);
/*
* Handle the result of a hook that is expected to return a resumption
* value <https://wiki.mozilla.org/Debugger#Resumption_Values>. This is
* called when we return from a debugging hook to debuggee code. The
* interpreter wants a (ResumeMode, Value) pair telling it how to proceed.
*
* Precondition: ar is entered. We are in the debugger compartment.
*
* Postcondition: This called ar.reset(). See handleUncaughtException.
*
* If `success` is false, the hook failed. If an exception is pending in
* ar.context(), return handleUncaughtException(ar, vp, callhook).
* Otherwise just return ResumeMode::Terminate.
*
* If `success` is true, there must be no exception pending in ar.context().
* `rv` may be:
*
* undefined - Return `ResumeMode::Continue` to continue execution
* normally.
*
* {return: value} or {throw: value} - Call unwrapDebuggeeValue to
* unwrap `value`. Store the result in `*vp` and return
* `ResumeMode::Return` or `ResumeMode::Throw`. The interpreter
* will force the current frame to return or throw an exception.
*
* null - Return `ResumeMode::Terminate` to terminate the debuggee with
* an uncatchable error.
*
* anything else - Make a new TypeError the pending exception and
* return handleUncaughtException(ar, vp, callHook).
*/
ResumeMode processHandlerResult(mozilla::Maybe<AutoRealm>& ar, bool success,
const Value& rv, AbstractFramePtr frame,
jsbytecode* pc, MutableHandleValue vp);
ResumeMode processParsedHandlerResult(mozilla::Maybe<AutoRealm>& ar,
AbstractFramePtr frame, jsbytecode* pc,
bool success, ResumeMode resumeMode,
MutableHandleValue vp);
GlobalObject* unwrapDebuggeeArgument(JSContext* cx, const Value& v);
static void traceObject(JSTracer* trc, JSObject* obj);
void trace(JSTracer* trc);
friend struct js::GCManagedDeletePolicy<Debugger>;
void traceForMovingGC(JSTracer* trc);
void traceCrossCompartmentEdges(JSTracer* tracer);
static const ClassOps classOps_;
public:
static const Class class_;
private:
static MOZ_MUST_USE bool getHookImpl(JSContext* cx, CallArgs& args,
Debugger& dbg, Hook which);
static MOZ_MUST_USE bool setHookImpl(JSContext* cx, CallArgs& args,
Debugger& dbg, Hook which);
static bool getEnabled(JSContext* cx, unsigned argc, Value* vp);
static bool setEnabled(JSContext* cx, unsigned argc, Value* vp);
static bool getOnDebuggerStatement(JSContext* cx, unsigned argc, Value* vp);
static bool setOnDebuggerStatement(JSContext* cx, unsigned argc, Value* vp);
static bool getOnExceptionUnwind(JSContext* cx, unsigned argc, Value* vp);
static bool setOnExceptionUnwind(JSContext* cx, unsigned argc, Value* vp);
static bool getOnNewScript(JSContext* cx, unsigned argc, Value* vp);
static bool setOnNewScript(JSContext* cx, unsigned argc, Value* vp);
static bool getOnEnterFrame(JSContext* cx, unsigned argc, Value* vp);
static bool setOnEnterFrame(JSContext* cx, unsigned argc, Value* vp);
static bool getOnNewGlobalObject(JSContext* cx, unsigned argc, Value* vp);
static bool setOnNewGlobalObject(JSContext* cx, unsigned argc, Value* vp);
static bool getOnNewPromise(JSContext* cx, unsigned argc, Value* vp);
static bool setOnNewPromise(JSContext* cx, unsigned argc, Value* vp);
static bool getOnPromiseSettled(JSContext* cx, unsigned argc, Value* vp);
static bool setOnPromiseSettled(JSContext* cx, unsigned argc, Value* vp);
static bool getUncaughtExceptionHook(JSContext* cx, unsigned argc, Value* vp);
static bool setUncaughtExceptionHook(JSContext* cx, unsigned argc, Value* vp);
static bool getAllowUnobservedAsmJS(JSContext* cx, unsigned argc, Value* vp);
static bool setAllowUnobservedAsmJS(JSContext* cx, unsigned argc, Value* vp);
static bool getCollectCoverageInfo(JSContext* cx, unsigned argc, Value* vp);
static bool setCollectCoverageInfo(JSContext* cx, unsigned argc, Value* vp);
static bool getMemory(JSContext* cx, unsigned argc, Value* vp);
static bool addDebuggee(JSContext* cx, unsigned argc, Value* vp);
static bool addAllGlobalsAsDebuggees(JSContext* cx, unsigned argc, Value* vp);
static bool removeDebuggee(JSContext* cx, unsigned argc, Value* vp);
static bool removeAllDebuggees(JSContext* cx, unsigned argc, Value* vp);
static bool hasDebuggee(JSContext* cx, unsigned argc, Value* vp);
static bool getDebuggees(JSContext* cx, unsigned argc, Value* vp);
static bool getNewestFrame(JSContext* cx, unsigned argc, Value* vp);
static bool clearAllBreakpoints(JSContext* cx, unsigned argc, Value* vp);
static bool findScripts(JSContext* cx, unsigned argc, Value* vp);
static bool findSources(JSContext* cx, unsigned argc, Value* vp);
static bool findObjects(JSContext* cx, unsigned argc, Value* vp);
static bool findAllGlobals(JSContext* cx, unsigned argc, Value* vp);
static bool makeGlobalObjectReference(JSContext* cx, unsigned argc,
Value* vp);
static bool setupTraceLoggerScriptCalls(JSContext* cx, unsigned argc,
Value* vp);
static bool drainTraceLoggerScriptCalls(JSContext* cx, unsigned argc,
Value* vp);
static bool startTraceLogger(JSContext* cx, unsigned argc, Value* vp);
static bool endTraceLogger(JSContext* cx, unsigned argc, Value* vp);
static bool isCompilableUnit(JSContext* cx, unsigned argc, Value* vp);
static bool recordReplayProcessKind(JSContext* cx, unsigned argc, Value* vp);
#ifdef NIGHTLY_BUILD
static bool setupTraceLogger(JSContext* cx, unsigned argc, Value* vp);
static bool drainTraceLogger(JSContext* cx, unsigned argc, Value* vp);
#endif
static bool adoptDebuggeeValue(JSContext* cx, unsigned argc, Value* vp);
static bool adoptSource(JSContext* cx, unsigned argc, Value* vp);
static bool construct(JSContext* cx, unsigned argc, Value* vp);
static const JSPropertySpec properties[];
static const JSFunctionSpec methods[];
static const JSFunctionSpec static_methods[];
static void removeFromFrameMapsAndClearBreakpointsIn(JSContext* cx,
AbstractFramePtr frame,
bool suspending = false);
static bool updateExecutionObservabilityOfFrames(
JSContext* cx, const ExecutionObservableSet& obs, IsObserving observing);
static bool updateExecutionObservabilityOfScripts(
JSContext* cx, const ExecutionObservableSet& obs, IsObserving observing);
static bool updateExecutionObservability(JSContext* cx,
ExecutionObservableSet& obs,
IsObserving observing);
template <typename FrameFn /* void (DebuggerFrame*) */>
static void forEachDebuggerFrame(AbstractFramePtr frame, FrameFn fn);
/*
* Return a vector containing all Debugger.Frame instances referring to
* |frame|. |global| is |frame|'s global object; if nullptr or omitted, we
* compute it ourselves from |frame|.
*/
using DebuggerFrameVector = GCVector<DebuggerFrame*>;
static MOZ_MUST_USE bool getDebuggerFrames(
AbstractFramePtr frame, MutableHandle<DebuggerFrameVector> frames);
public:
static MOZ_MUST_USE bool ensureExecutionObservabilityOfOsrFrame(
JSContext* cx, AbstractFramePtr osrSourceFrame);
// Public for DebuggerScript_setBreakpoint.
static MOZ_MUST_USE bool ensureExecutionObservabilityOfScript(
JSContext* cx, JSScript* script);
// Whether the Debugger instance needs to observe all non-AOT JS
// execution of its debugees.
IsObserving observesAllExecution() const;
// Whether the Debugger instance needs to observe AOT-compiled asm.js
// execution of its debuggees.
IsObserving observesAsmJS() const;
// Whether the Debugger instance needs to observe coverage of any JavaScript
// execution.
IsObserving observesCoverage() const;
private:
static MOZ_MUST_USE bool ensureExecutionObservabilityOfFrame(
JSContext* cx, AbstractFramePtr frame);
static MOZ_MUST_USE bool ensureExecutionObservabilityOfRealm(
JSContext* cx, JS::Realm* realm);
static bool hookObservesAllExecution(Hook which);
MOZ_MUST_USE bool updateObservesAllExecutionOnDebuggees(
JSContext* cx, IsObserving observing);
MOZ_MUST_USE bool updateObservesCoverageOnDebuggees(JSContext* cx,
IsObserving observing);
void updateObservesAsmJSOnDebuggees(IsObserving observing);
JSObject* getHook(Hook hook) const;
bool hasAnyLiveHooks(JSRuntime* rt) const;
static MOZ_MUST_USE bool slowPathCheckNoExecute(JSContext* cx,
HandleScript script);
static ResumeMode slowPathOnEnterFrame(JSContext* cx, AbstractFramePtr frame);
static ResumeMode slowPathOnResumeFrame(JSContext* cx,
AbstractFramePtr frame);
static MOZ_MUST_USE bool slowPathOnLeaveFrame(JSContext* cx,
AbstractFramePtr frame,
jsbytecode* pc, bool ok);
static MOZ_MUST_USE bool slowPathOnNewGenerator(
JSContext* cx, AbstractFramePtr frame,
Handle<AbstractGeneratorObject*> genObj);
static ResumeMode slowPathOnDebuggerStatement(JSContext* cx,
AbstractFramePtr frame);
static ResumeMode slowPathOnExceptionUnwind(JSContext* cx,
AbstractFramePtr frame);
static void slowPathOnNewScript(JSContext* cx, HandleScript script);
static void slowPathOnNewWasmInstance(
JSContext* cx, Handle<WasmInstanceObject*> wasmInstance);
static void slowPathOnNewGlobalObject(JSContext* cx,
Handle<GlobalObject*> global);
static MOZ_MUST_USE bool slowPathOnLogAllocationSite(
JSContext* cx, HandleObject obj, HandleSavedFrame frame,
mozilla::TimeStamp when, GlobalObject::DebuggerVector& dbgs);
static void slowPathPromiseHook(JSContext* cx, Hook hook,
Handle<PromiseObject*> promise);
template <typename HookIsEnabledFun /* bool (Debugger*) */,
typename FireHookFun /* ResumeMode (Debugger*) */>
static ResumeMode dispatchHook(JSContext* cx, HookIsEnabledFun hookIsEnabled,
FireHookFun fireHook);
ResumeMode fireDebuggerStatement(JSContext* cx, MutableHandleValue vp);
ResumeMode fireExceptionUnwind(JSContext* cx, MutableHandleValue vp);
ResumeMode fireEnterFrame(JSContext* cx, MutableHandleValue vp);