-
Notifications
You must be signed in to change notification settings - Fork 54
/
Debugger.cpp
13297 lines (11342 loc) · 416 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 "vm/Debugger-inl.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/ScopeExit.h"
#include "mozilla/Sprintf.h"
#include "mozilla/TypeTraits.h"
#include <utility>
#include "jsfriendapi.h"
#include "jsnum.h"
#include "frontend/BytecodeCompilation.h"
#include "frontend/Parser.h"
#include "gc/FreeOp.h"
#include "gc/HashUtil.h"
#include "gc/Marking.h"
#include "gc/Policy.h"
#include "gc/PublicIterators.h"
#include "jit/BaselineDebugModeOSR.h"
#include "jit/BaselineJIT.h"
#include "js/CharacterEncoding.h"
#include "js/Date.h"
#include "js/Promise.h"
#include "js/PropertyDescriptor.h"
#include "js/PropertySpec.h"
#include "js/SourceText.h"
#include "js/StableStringChars.h"
#include "js/UbiNodeBreadthFirst.h"
#include "js/Vector.h"
#include "js/Wrapper.h"
#include "proxy/ScriptedProxyHandler.h"
#include "util/Text.h"
#include "vm/ArgumentsObject.h"
#include "vm/AsyncFunction.h"
#include "vm/AsyncIteration.h"
#include "vm/DebuggerMemory.h"
#include "vm/GeckoProfiler.h"
#include "vm/GeneratorObject.h"
#include "vm/JSContext.h"
#include "vm/JSObject.h"
#include "vm/Realm.h"
#include "vm/TraceLogging.h"
#include "vm/WrapperObject.h"
#include "wasm/WasmInstance.h"
#include "gc/GC-inl.h"
#include "vm/BytecodeUtil-inl.h"
#include "vm/Compartment-inl.h"
#include "vm/GeckoProfiler-inl.h"
#include "vm/JSObject-inl.h"
#include "vm/JSScript-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/Stack-inl.h"
using namespace js;
using JS::AutoStableStringChars;
using JS::CompileOptions;
using JS::SourceOwnership;
using JS::SourceText;
using JS::dbg::AutoEntryMonitor;
using JS::dbg::Builder;
using js::frontend::IsIdentifier;
using mozilla::AsVariant;
using mozilla::DebugOnly;
using mozilla::MakeScopeExit;
using mozilla::Maybe;
using mozilla::Nothing;
using mozilla::Some;
using mozilla::TimeDuration;
using mozilla::TimeStamp;
/*** Forward declarations, ClassOps and Classes *****************************/
static void DebuggerFrame_finalize(FreeOp* fop, JSObject* obj);
static void DebuggerFrame_trace(JSTracer* trc, JSObject* obj);
static void DebuggerEnv_trace(JSTracer* trc, JSObject* obj);
static void DebuggerObject_trace(JSTracer* trc, JSObject* obj);
static void DebuggerScript_trace(JSTracer* trc, JSObject* obj);
static void DebuggerSource_trace(JSTracer* trc, JSObject* obj);
enum {
JSSLOT_DEBUGFRAME_OWNER,
JSSLOT_DEBUGFRAME_ARGUMENTS,
JSSLOT_DEBUGFRAME_ONSTEP_HANDLER,
JSSLOT_DEBUGFRAME_ONPOP_HANDLER,
JSSLOT_DEBUGFRAME_COUNT
};
inline js::Debugger* js::DebuggerFrame::owner() const {
JSObject* dbgobj = &getReservedSlot(JSSLOT_DEBUGFRAME_OWNER).toObject();
return Debugger::fromJSObject(dbgobj);
}
const ClassOps DebuggerFrame::classOps_ = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
DebuggerFrame_finalize,
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
DebuggerFrame_trace};
const Class DebuggerFrame::class_ = {
"Frame",
JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_DEBUGFRAME_COUNT) |
JSCLASS_BACKGROUND_FINALIZE,
&DebuggerFrame::classOps_};
enum { JSSLOT_DEBUGARGUMENTS_FRAME, JSSLOT_DEBUGARGUMENTS_COUNT };
const Class DebuggerArguments::class_ = {
"Arguments", JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_DEBUGARGUMENTS_COUNT)};
const ClassOps DebuggerEnvironment::classOps_ = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* finalize */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
DebuggerEnv_trace};
const Class DebuggerEnvironment::class_ = {
"Environment",
JSCLASS_HAS_PRIVATE |
JSCLASS_HAS_RESERVED_SLOTS(DebuggerEnvironment::RESERVED_SLOTS),
&classOps_};
enum { JSSLOT_DEBUGOBJECT_OWNER, JSSLOT_DEBUGOBJECT_COUNT };
const ClassOps DebuggerObject::classOps_ = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* finalize */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
DebuggerObject_trace};
const Class DebuggerObject::class_ = {
"Object", JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(RESERVED_SLOTS),
&classOps_};
enum { JSSLOT_DEBUGSCRIPT_OWNER, JSSLOT_DEBUGSCRIPT_COUNT };
static const ClassOps DebuggerScript_classOps = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* finalize */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
DebuggerScript_trace};
static const Class DebuggerScript_class = {
"Script",
JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_DEBUGSCRIPT_COUNT),
&DebuggerScript_classOps};
enum {
JSSLOT_DEBUGSOURCE_OWNER,
JSSLOT_DEBUGSOURCE_TEXT,
JSSLOT_DEBUGSOURCE_COUNT
};
static const ClassOps DebuggerSource_classOps = {nullptr, /* addProperty */
nullptr, /* delProperty */
nullptr, /* enumerate */
nullptr, /* newEnumerate */
nullptr, /* resolve */
nullptr, /* mayResolve */
nullptr, /* finalize */
nullptr, /* call */
nullptr, /* hasInstance */
nullptr, /* construct */
DebuggerSource_trace};
static const Class DebuggerSource_class = {
"Source",
JSCLASS_HAS_PRIVATE | JSCLASS_HAS_RESERVED_SLOTS(JSSLOT_DEBUGSOURCE_COUNT),
&DebuggerSource_classOps};
/*** Utils ******************************************************************/
static inline bool EnsureFunctionHasScript(JSContext* cx, HandleFunction fun) {
if (fun->isInterpretedLazy()) {
AutoRealm ar(cx, fun);
return !!JSFunction::getOrCreateScript(cx, fun);
}
return true;
}
static inline JSScript* GetOrCreateFunctionScript(JSContext* cx,
HandleFunction fun) {
MOZ_ASSERT(fun->isInterpreted());
if (!EnsureFunctionHasScript(cx, fun)) {
return nullptr;
}
return fun->nonLazyScript();
}
static bool ValueToIdentifier(JSContext* cx, HandleValue v,
MutableHandleId id) {
if (!ValueToId<CanGC>(cx, v, id)) {
return false;
}
if (!JSID_IS_ATOM(id) || !IsIdentifier(JSID_TO_ATOM(id))) {
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; }
};
// Given a Debugger instance dbg, if it is enabled, prevents all its debuggee
// compartments from executing scripts. Attempts to run script will throw an
// instance of Debugger.DebuggeeWouldRun from the topmost locked Debugger's
// compartment.
class MOZ_RAII js::EnterDebuggeeNoExecute {
friend class js::LeaveDebuggeeNoExecute;
Debugger& dbg_;
EnterDebuggeeNoExecute** stack_;
EnterDebuggeeNoExecute* prev_;
// Non-nullptr when unlocked temporarily by a LeaveDebuggeeNoExecute.
LeaveDebuggeeNoExecute* unlocked_;
// When DebuggeeWouldRun is a warning instead of an error, whether we've
// reported a warning already.
bool reported_;
public:
// Mark execution in dbg's debuggees as forbidden, for the lifetime of this
// object. Require an AutoDebuggerJobQueueInterruption in scope.
explicit EnterDebuggeeNoExecute(
JSContext* cx, Debugger& dbg,
const JS::AutoDebuggerJobQueueInterruption& adjqiProof)
: dbg_(dbg), unlocked_(nullptr), reported_(false) {
MOZ_ASSERT(adjqiProof.initialized());
stack_ = &cx->noExecuteDebuggerTop.ref();
prev_ = *stack_;
*stack_ = this;
}
~EnterDebuggeeNoExecute() {
MOZ_ASSERT(*stack_ == this);
*stack_ = prev_;
}
Debugger& debugger() const { return dbg_; }
#ifdef DEBUG
static bool isLockedInStack(JSContext* cx, Debugger& dbg) {
for (EnterDebuggeeNoExecute* it = cx->noExecuteDebuggerTop; it;
it = it->prev_) {
if (&it->debugger() == &dbg) {
return !it->unlocked_;
}
}
return false;
}
#endif
// Given a JSContext entered into a debuggee realm, find the lock
// that locks it. Returns nullptr if not found.
static EnterDebuggeeNoExecute* findInStack(JSContext* cx) {
Realm* debuggee = cx->realm();
for (EnterDebuggeeNoExecute* it = cx->noExecuteDebuggerTop; it;
it = it->prev_) {
Debugger& dbg = it->debugger();
if (!it->unlocked_ && dbg.isEnabled() &&
dbg.observesGlobal(debuggee->maybeGlobal())) {
return it;
}
}
return nullptr;
}
// Given a JSContext entered into a debuggee compartment, report a
// warning or an error if there is a lock that locks it.
static bool reportIfFoundInStack(JSContext* cx, HandleScript script) {
if (EnterDebuggeeNoExecute* nx = findInStack(cx)) {
bool warning = !cx->options().throwOnDebuggeeWouldRun();
if (!warning || !nx->reported_) {
AutoRealm ar(cx, nx->debugger().toJSObject());
nx->reported_ = true;
if (cx->options().dumpStackOnDebuggeeWouldRun()) {
fprintf(stdout, "Dumping stack for DebuggeeWouldRun:\n");
DumpBacktrace(cx);
}
const char* filename =
script->filename() ? script->filename() : "(none)";
char linenoStr[15];
SprintfLiteral(linenoStr, "%u", script->lineno());
unsigned flags = warning ? JSREPORT_WARNING : JSREPORT_ERROR;
// FIXME: filename should be UTF-8 (bug 987069).
return JS_ReportErrorFlagsAndNumberLatin1(
cx, flags, GetErrorMessage, nullptr, JSMSG_DEBUGGEE_WOULD_RUN,
filename, linenoStr);
}
}
return true;
}
};
// Given a JSContext entered into a debuggee compartment, if it is in
// an NX section, unlock the topmost EnterDebuggeeNoExecute instance.
//
// Does nothing if debuggee is not in an NX section. For example, this
// situation arises when invocation functions are called without entering
// Debugger code, e.g., calling D.O.p.executeInGlobal or D.O.p.apply.
class MOZ_RAII js::LeaveDebuggeeNoExecute {
EnterDebuggeeNoExecute* prevLocked_;
public:
explicit LeaveDebuggeeNoExecute(JSContext* cx)
: prevLocked_(EnterDebuggeeNoExecute::findInStack(cx)) {
if (prevLocked_) {
MOZ_ASSERT(!prevLocked_->unlocked_);
prevLocked_->unlocked_ = this;
}
}
~LeaveDebuggeeNoExecute() {
if (prevLocked_) {
MOZ_ASSERT(prevLocked_->unlocked_ == this);
prevLocked_->unlocked_ = nullptr;
}
}
};
/* static */
bool Debugger::slowPathCheckNoExecute(JSContext* cx, HandleScript script) {
MOZ_ASSERT(cx->realm()->isDebuggee());
MOZ_ASSERT(cx->noExecuteDebuggerTop);
return EnterDebuggeeNoExecute::reportIfFoundInStack(cx, script);
}
static inline void NukeDebuggerWrapper(NativeObject* wrapper) {
// In some OOM failure cases, we need to destroy the edge to the referent,
// to avoid trying to trace it during untimely collections.
wrapper->setPrivate(nullptr);
}
static bool 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;
}
RootedLinearString 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;
}
static bool 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_EncodeStringToLatin1(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);
}
return true;
}
static bool RequireGlobalObject(JSContext* cx, HandleValue dbgobj,
HandleObject referent) {
RootedObject obj(cx, referent);
if (!obj->is<GlobalObject>()) {
const char* isWrapper = "";
const char* isWindowProxy = "";
// Help the poor programmer by pointing out wrappers around globals...
if (obj->is<WrapperObject>()) {
obj = js::UncheckedUnwrap(obj);
isWrapper = "a wrapper around ";
}
// ... and WindowProxies around Windows.
if (IsWindowProxy(obj)) {
obj = ToWindowIfWindowProxy(obj);
isWindowProxy = "a WindowProxy referring to ";
}
if (obj->is<GlobalObject>()) {
ReportValueError(cx, JSMSG_DEBUG_WRAPPER_IN_WAY, JSDVG_SEARCH_STACK,
dbgobj, nullptr, isWrapper, isWindowProxy);
} else {
ReportValueError(cx, JSMSG_DEBUG_BAD_REFERENT, JSDVG_SEARCH_STACK, dbgobj,
nullptr, "a global object");
}
return false;
}
return true;
}
/*** Breakpoints ************************************************************/
BreakpointSite::BreakpointSite(Type type) : type_(type), enabledCount(0) {}
void BreakpointSite::inc(FreeOp* fop) {
enabledCount++;
if (enabledCount == 1) {
recompile(fop);
}
}
void BreakpointSite::dec(FreeOp* fop) {
MOZ_ASSERT(enabledCount > 0);
enabledCount--;
if (enabledCount == 0) {
recompile(fop);
}
}
bool BreakpointSite::isEmpty() const { return breakpoints.isEmpty(); }
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, BreakpointSite* site,
JSObject* handler)
: debugger(debugger), site(site), handler(handler) {
MOZ_ASSERT(handler->compartment() == debugger->object->compartment());
debugger->breakpoints.pushBack(this);
site->breakpoints.pushBack(this);
}
void Breakpoint::destroy(FreeOp* fop,
MayDestroySite mayDestroySite /* true */) {
if (debugger->enabled) {
site->dec(fop);
}
debugger->breakpoints.remove(this);
site->breakpoints.remove(this);
if (mayDestroySite == MayDestroySite::True) {
site->destroyIfEmpty(fop);
}
fop->delete_(this);
}
Breakpoint* Breakpoint::nextInDebugger() { return debuggerLink.mNext; }
Breakpoint* Breakpoint::nextInSite() { return siteLink.mNext; }
JSBreakpointSite::JSBreakpointSite(JSScript* script, jsbytecode* pc)
: BreakpointSite(Type::JS), script(script), pc(pc) {
MOZ_ASSERT(!script->hasBreakpointsAt(pc));
}
void JSBreakpointSite::recompile(FreeOp* fop) {
if (script->hasBaselineScript()) {
script->baselineScript()->toggleDebugTraps(script, pc);
}
}
void JSBreakpointSite::destroyIfEmpty(FreeOp* fop) {
if (isEmpty()) {
script->destroyBreakpointSite(fop, pc);
}
}
WasmBreakpointSite::WasmBreakpointSite(wasm::DebugState* debug_,
uint32_t offset_)
: BreakpointSite(Type::Wasm), debug(debug_), offset(offset_) {
MOZ_ASSERT(debug_);
}
void WasmBreakpointSite::recompile(FreeOp* fop) {
debug->toggleBreakpointTrap(fop->runtime(), offset, isEnabled());
}
void WasmBreakpointSite::destroyIfEmpty(FreeOp* fop) {
if (isEmpty()) {
debug->destroyBreakpointSite(fop, offset);
}
}
/*** Debugger hook dispatch *************************************************/
Debugger::Debugger(JSContext* cx, NativeObject* dbg)
: object(dbg),
debuggees(cx->zone()),
uncaughtExceptionHook(nullptr),
enabled(true),
allowUnobservedAsmJS(false),
collectCoverageInfo(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),
lazyScripts(cx),
sources(cx),
objects(cx),
environments(cx),
wasmInstanceScripts(cx),
wasmInstanceSources(cx),
#ifdef NIGHTLY_BUILD
traceLoggerLastDrainedSize(0),
traceLoggerLastDrainedIteration(0),
#endif
traceLoggerScriptedCallsLastDrainedSize(0),
traceLoggerScriptedCallsLastDrainedIteration(0) {
cx->check(dbg);
#ifdef JS_TRACE_LOGGING
TraceLoggerThread* logger = TraceLoggerForCurrentThread(cx);
if (logger) {
# ifdef NIGHTLY_BUILD
logger->getIterationAndSize(&traceLoggerLastDrainedIteration,
&traceLoggerLastDrainedSize);
# endif
logger->getIterationAndSize(&traceLoggerScriptedCallsLastDrainedIteration,
&traceLoggerScriptedCallsLastDrainedSize);
}
#endif
cx->runtime()->debuggerList().insertBack(this);
}
Debugger::~Debugger() {
MOZ_ASSERT(debuggees.empty());
allocationsLog.clear();
// We don't have to worry about locking here since Debugger is not
// background finalized.
JSContext* cx = TlsContext.get();
if (onNewGlobalObjectWatchersLink.mPrev ||
onNewGlobalObjectWatchersLink.mNext ||
cx->runtime()->onNewGlobalObjectWatchers().begin() ==
JSRuntime::WatchersList::Iterator(this)) {
cx->runtime()->onNewGlobalObjectWatchers().remove(this);
}
}
JS_STATIC_ASSERT(unsigned(JSSLOT_DEBUGFRAME_OWNER) ==
unsigned(JSSLOT_DEBUGSCRIPT_OWNER));
JS_STATIC_ASSERT(unsigned(JSSLOT_DEBUGFRAME_OWNER) ==
unsigned(JSSLOT_DEBUGSOURCE_OWNER));
JS_STATIC_ASSERT(unsigned(JSSLOT_DEBUGFRAME_OWNER) ==
unsigned(JSSLOT_DEBUGOBJECT_OWNER));
JS_STATIC_ASSERT(unsigned(JSSLOT_DEBUGFRAME_OWNER) ==
unsigned(DebuggerEnvironment::OWNER_SLOT));
/* static */
Debugger* Debugger::fromChildJSObject(JSObject* obj) {
MOZ_ASSERT(obj->getClass() == &DebuggerFrame::class_ ||
obj->getClass() == &DebuggerScript_class ||
obj->getClass() == &DebuggerSource_class ||
obj->getClass() == &DebuggerObject::class_ ||
obj->getClass() == &DebuggerEnvironment::class_);
JSObject* dbgobj = &obj->as<NativeObject>()
.getReservedSlot(JSSLOT_DEBUGOBJECT_OWNER)
.toObject();
return fromJSObject(dbgobj);
}
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>();
}
bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
MutableHandleValue vp) {
RootedDebuggerFrame result(cx);
if (!Debugger::getFrame(cx, iter, &result)) {
return false;
}
vp.setObject(*result);
return true;
}
bool Debugger::getFrame(JSContext* cx, const FrameIter& iter,
MutableHandleDebuggerFrame result) {
AbstractFramePtr referent = iter.abstractFramePtr();
MOZ_ASSERT_IF(referent.hasScript(), !referent.script()->selfHosted());
if (referent.hasScript() &&
!referent.script()->ensureHasAnalyzedArgsUsage(cx)) {
return false;
}
FrameMap::AddPtr p = frames.lookupForAdd(referent);
if (!p) {
RootedDebuggerFrame frame(cx);
// If this is a generator frame, there may be an existing
// Debugger.Frame object that isn't in `frames` because the generator
// was suspended, popping the stack frame, and later resumed (and we
// were not stepping, so did not pass through slowPathOnResumeFrame).
Rooted<AbstractGeneratorObject*> genObj(cx);
GeneratorWeakMap::AddPtr gp;
if (referent.isGeneratorFrame()) {
{
AutoRealm ar(cx, referent.callee());
genObj = GetGeneratorObjectForFrame(cx, referent);
}
if (genObj) {
gp = generatorFrames.lookupForAdd(genObj);
if (gp) {
frame = &gp->value()->as<DebuggerFrame>();
// We have found an existing Debugger.Frame object. But
// since it was previously popped (see comment above), it
// is not currently "live". We must revive it.
if (!frame->resume(iter)) {
return false;
}
if (!ensureExecutionObservabilityOfFrame(cx, referent)) {
return false;
}
}
}
// 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.
}
if (!frame) {
// Create and populate the Debugger.Frame object.
RootedObject proto(
cx, &object->getReservedSlot(JSSLOT_DEBUG_FRAME_PROTO).toObject());
RootedNativeObject debugger(cx, object);
frame = DebuggerFrame::create(cx, proto, iter, debugger);
if (!frame) {
return false;
}
if (!ensureExecutionObservabilityOfFrame(cx, referent)) {
return false;
}
if (genObj) {
DebuggerFrame* frameObj = frame;
if (!generatorFrames.relookupOrAdd(gp, genObj, frameObj)) {
ReportOutOfMemory(cx);
return false;
}
}
}
if (!frames.add(p, referent, frame)) {
NukeDebuggerWrapper(frame);
if (genObj) {
generatorFrames.remove(genObj);
}
ReportOutOfMemory(cx);
return false;
}
}
result.set(&p->value()->as<DebuggerFrame>());
return true;
}
bool Debugger::addGeneratorFrame(JSContext* cx,
Handle<AbstractGeneratorObject*> genObj,
HandleDebuggerFrame frameObj) {
GeneratorWeakMap::AddPtr p = generatorFrames.lookupForAdd(genObj);
if (p) {
MOZ_ASSERT(p->value() == frameObj);
} else {
if (!generatorFrames.relookupOrAdd(p, genObj, frameObj)) {
ReportOutOfMemory(cx);
return false;
}
}
return true;
}
/* static */
bool Debugger::hasLiveHook(GlobalObject* global, Hook which) {
if (GlobalObject::DebuggerVector* debuggers = global->getDebuggers()) {
for (auto p = debuggers->begin(); p != debuggers->end(); p++) {
Debugger* dbg = *p;
if (dbg->enabled && dbg->getHook(which)) {
return true;
}
}
}
return false;
}
JSObject* Debugger::getHook(Hook hook) const {
MOZ_ASSERT(hook >= 0 && hook < HookCount);
const Value& v = object->getReservedSlot(JSSLOT_DEBUG_HOOK_START + hook);
return v.isUndefined() ? nullptr : &v.toObject();
}
bool Debugger::hasAnyLiveHooks(JSRuntime* rt) const {
if (!enabled) {
return false;
}
// 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;
}
// If any breakpoints are in live scripts, return true.
for (Breakpoint* bp = firstBreakpoint(); bp; bp = bp->nextInDebugger()) {
switch (bp->site->type()) {
case BreakpointSite::Type::JS:
if (IsMarkedUnbarriered(rt, &bp->site->asJS()->script)) {
return true;
}
break;
case BreakpointSite::Type::Wasm:
if (IsMarkedUnbarriered(rt, &bp->asWasm()->wasmInstance)) {
return true;
}
break;
}
}
// Check for hooks in live stack frames.
for (FrameMap::Range r = frames.all(); !r.empty(); r.popFront()) {
DebuggerFrame& frameObj = r.front().value()->as<DebuggerFrame>();
if (frameObj.hasAnyLiveHooks()) {
return true;
}
}
// Check for hooks set on suspended generator frames.
for (GeneratorWeakMap::Range r = generatorFrames.all(); !r.empty();
r.popFront()) {
JSObject* key = r.front().key();
DebuggerFrame& frameObj = r.front().value()->as<DebuggerFrame>();
if (IsMarkedUnbarriered(rt, &key) && frameObj.hasAnyLiveHooks()) {
return true;
}
}
return false;
}
/* static */
ResumeMode Debugger::slowPathOnEnterFrame(JSContext* cx,
AbstractFramePtr frame) {
RootedValue rval(cx);
ResumeMode resumeMode = dispatchHook(cx,
[frame](Debugger* dbg) -> bool {
return dbg->observesFrame(frame) &&
dbg->observesEnterFrame();
},
[&](Debugger* dbg) -> ResumeMode {
return dbg->fireEnterFrame(cx, &rval);
});
switch (resumeMode) {
case ResumeMode::Continue:
break;
case ResumeMode::Throw:
cx->setPendingException(rval);
break;
case ResumeMode::Terminate:
cx->clearPendingException();
break;
case ResumeMode::Return:
frame.setReturnValue(rval);
break;
default:
MOZ_CRASH("bad Debugger::onEnterFrame resume mode");
}
return resumeMode;
}
/* static */
ResumeMode Debugger::slowPathOnResumeFrame(JSContext* cx,
AbstractFramePtr frame) {
// 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);
// 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.
if (GlobalObject::DebuggerVector* debuggers =
frame.global()->getDebuggers()) {
for (Debugger* dbg : *debuggers) {
if (GeneratorWeakMap::Ptr entry = dbg->generatorFrames.lookup(genObj)) {
DebuggerFrame* frameObj = &entry->value()->as<DebuggerFrame>();
if (!dbg->frames.putNew(frame, frameObj)) {
ReportOutOfMemory(cx);
return ResumeMode::Throw;
}
FrameIter iter(cx);
MOZ_ASSERT(iter.abstractFramePtr() == frame);
if (!frameObj->resume(iter)) {
return ResumeMode::Throw;
}
if (!ensureExecutionObservabilityOfFrame(cx, frame)) {
return ResumeMode::Throw;
}
}
}
}
return slowPathOnEnterFrame(cx, frame);
}
static void DebuggerFrame_maybeDecrementFrameScriptStepModeCount(
FreeOp* fop, AbstractFramePtr frame, NativeObject* frameobj);
/*
* RAII class to mark a generator as "running" temporarily while running
* debugger code.
*
* When Debugger::slowPathOnLeaveFrame is called for a frame that is yielding
* or awaiting, its generator is in the "suspended" state. Letting script
* observe this state, with the generator on stack yet also reenterable, would
* be bad, so we mark it running while we fire events.
*/
class MOZ_RAII AutoSetGeneratorRunning {
int32_t resumeIndex_;
Rooted<AbstractGeneratorObject*> genObj_;
public:
AutoSetGeneratorRunning(JSContext* cx,
Handle<AbstractGeneratorObject*> genObj)
: resumeIndex_(0), genObj_(cx, genObj) {
if (genObj) {
if (!genObj->isClosed() && genObj->isSuspended()) {
// Yielding or awaiting.
resumeIndex_ = genObj->resumeIndex();
genObj->setRunning();
} else {
// Returning or throwing. The generator is already closed, if
// it was ever exposed at all.
genObj_ = nullptr;
}
}
}
~AutoSetGeneratorRunning() {
if (genObj_) {
MOZ_ASSERT(genObj_->isRunning());
genObj_->setResumeIndex(resumeIndex_);
}
}
};
/*
* Handle leaving a frame with debuggers watching. |frameOk| indicates whether
* the frame is exiting normally or abruptly. Set |cx|'s exception and/or
* |cx->fp()|'s return value, and return a new success value.
*/
/* static */
bool Debugger::slowPathOnLeaveFrame(JSContext* cx, AbstractFramePtr frame,
jsbytecode* pc, bool frameOk) {
mozilla::DebugOnly<Handle<GlobalObject*>> debuggeeGlobal = cx->global();
// Determine if we are suspending this frame or popping it forever.
bool suspending = false;
Rooted<AbstractGeneratorObject*> genObj(cx);
if (frame.isGeneratorFrame()) {
// If we're leaving successfully at a yield opcode, we're probably
// suspending; the `isClosed()` check detects a debugger forced return
// from an `onStep` handler, which looks almost the same.
genObj = GetGeneratorObjectForFrame(cx, frame);
suspending =
frameOk && pc &&
(*pc == JSOP_INITIALYIELD || *pc == JSOP_YIELD || *pc == JSOP_AWAIT) &&
!genObj->isClosed();