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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
|
/* 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/. */
"use strict";
// protocol.js uses objects as exceptions in order to define
// error packets.
/* eslint-disable no-throw-literal */
const DebuggerNotificationObserver = require("DebuggerNotificationObserver");
const Services = require("Services");
const { Cr, Ci } = require("chrome");
const { Pool } = require("devtools/shared/protocol/Pool");
const { createValueGrip } = require("devtools/server/actors/object/utils");
const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
const DevToolsUtils = require("devtools/shared/DevToolsUtils");
const Debugger = require("Debugger");
const { assert, dumpn, reportException } = DevToolsUtils;
const { threadSpec } = require("devtools/shared/specs/thread");
const {
getAvailableEventBreakpoints,
eventBreakpointForNotification,
eventsRequireNotifications,
firstStatementBreakpointId,
makeEventBreakpointMessage,
} = require("devtools/server/actors/utils/event-breakpoints");
const {
WatchpointMap,
} = require("devtools/server/actors/utils/watchpoint-map");
const {
getDebuggerSourceURL,
} = require("devtools/server/actors/utils/source-url");
const { logEvent } = require("devtools/server/actors/utils/logEvent");
loader.lazyRequireGetter(
this,
"EnvironmentActor",
"devtools/server/actors/environment",
true
);
loader.lazyRequireGetter(
this,
"BreakpointActorMap",
"devtools/server/actors/utils/breakpoint-actor-map",
true
);
loader.lazyRequireGetter(
this,
"PauseScopedObjectActor",
"devtools/server/actors/pause-scoped",
true
);
loader.lazyRequireGetter(
this,
"EventLoopStack",
"devtools/server/actors/utils/event-loop",
true
);
loader.lazyRequireGetter(
this,
["FrameActor", "getSavedFrameParent", "isValidSavedFrame"],
"devtools/server/actors/frame",
true
);
loader.lazyRequireGetter(
this,
"HighlighterEnvironment",
"devtools/server/actors/highlighters",
true
);
loader.lazyRequireGetter(
this,
"PausedDebuggerOverlay",
"devtools/server/actors/highlighters/paused-debugger",
true
);
const PROMISE_REACTIONS = new WeakMap();
function cacheReactionsForFrame(frame) {
if (frame.asyncPromise) {
const reactions = frame.asyncPromise.getPromiseReactions();
const existingReactions = PROMISE_REACTIONS.get(frame.asyncPromise);
if (
reactions.length > 0 &&
(!existingReactions || reactions.length > existingReactions.length)
) {
PROMISE_REACTIONS.set(frame.asyncPromise, reactions);
}
}
}
function createStepForReactionTracking(onStep) {
return function() {
cacheReactionsForFrame(this);
return onStep ? onStep.apply(this, arguments) : undefined;
};
}
const getAsyncParentFrame = frame => {
if (!frame.asyncPromise) {
return null;
}
// We support returning Frame actors for frames that are suspended
// at an 'await', and here we want to walk upward to look for the first
// frame that will be resumed when the current frame's promise resolves.
let reactions =
PROMISE_REACTIONS.get(frame.asyncPromise) ||
frame.asyncPromise.getPromiseReactions();
while (true) {
// We loop here because we may have code like:
//
// async function inner(){ debugger; }
//
// async function outer() {
// await Promise.resolve().then(() => inner());
// }
//
// where we can see that when `inner` resolves, we will resume from
// `outer`, even though there is a layer of promises between, and
// that layer could be any number of promises deep.
if (!(reactions[0] instanceof Debugger.Object)) {
break;
}
reactions = reactions[0].getPromiseReactions();
}
if (reactions[0] instanceof Debugger.Frame) {
return reactions[0];
}
return null;
};
const RESTARTED_FRAMES = new WeakSet();
// Thread actor possible states:
const STATES = {
// Before ThreadActor.attach is called:
DETACHED: "detached",
// After the actor is destroyed:
EXITED: "exited",
// States possible in between DETACHED AND EXITED:
// Default state, when the thread isn't paused,
RUNNING: "running",
// When paused on any type of breakpoint, or, when the client requested an interrupt.
PAUSED: "paused",
};
/**
* JSD2 actors.
*/
/**
* Creates a ThreadActor.
*
* ThreadActors manage a JSInspector object and manage execution/inspection
* of debuggees.
*
* @param aParent object
* This |ThreadActor|'s parent actor. It must implement the following
* properties:
* - url: The URL string of the debuggee.
* - window: The global window object.
* - preNest: Function called before entering a nested event loop.
* - postNest: Function called after exiting a nested event loop.
* - dbg: a Debugger instance that manages its globals on its own.
* @param aGlobal object [optional]
* An optional (for content debugging only) reference to the content
* window.
*/
const ThreadActor = ActorClassWithSpec(threadSpec, {
initialize(parent, global) {
Actor.prototype.initialize.call(this, parent.conn);
this._state = STATES.DETACHED;
this._frameActors = [];
this._parent = parent;
this._dbg = null;
this._gripDepth = 0;
this._threadLifetimePool = null;
this._parentClosed = false;
this._xhrBreakpoints = [];
this._observingNetwork = false;
this._activeEventBreakpoints = new Set();
this._activeEventPause = null;
this._pauseOverlay = null;
this._priorPause = null;
this._frameActorMap = new WeakMap();
this._watchpointsMap = new WatchpointMap(this);
this._options = {
skipBreakpoints: false,
};
this.breakpointActorMap = new BreakpointActorMap(this);
this._debuggerSourcesSeen = new WeakSet();
// A Set of URLs string to watch for when new sources are found by
// the debugger instance.
this._onLoadBreakpointURLs = new Set();
// A WeakMap from Debugger.Frame to an exception value which will be ignored
// when deciding to pause if the value is thrown by the frame. When we are
// pausing on exceptions then we only want to pause when the youngest frame
// throws a particular exception, instead of for all older frames as well.
this._handledFrameExceptions = new WeakMap();
this.global = global;
this.onNewSourceEvent = this.onNewSourceEvent.bind(this);
this.createCompletionGrip = this.createCompletionGrip.bind(this);
this.onDebuggerStatement = this.onDebuggerStatement.bind(this);
this.onNewScript = this.onNewScript.bind(this);
this.objectGrip = this.objectGrip.bind(this);
this.pauseObjectGrip = this.pauseObjectGrip.bind(this);
this._onOpeningRequest = this._onOpeningRequest.bind(this);
this._onNewDebuggee = this._onNewDebuggee.bind(this);
this._onExceptionUnwind = this._onExceptionUnwind.bind(this);
this._eventBreakpointListener = this._eventBreakpointListener.bind(this);
this._onWindowReady = this._onWindowReady.bind(this);
this._onWillNavigate = this._onWillNavigate.bind(this);
this._onNavigate = this._onNavigate.bind(this);
this._parent.on("window-ready", this._onWindowReady);
this._parent.on("will-navigate", this._onWillNavigate);
this._parent.on("navigate", this._onNavigate);
this._firstStatementBreakpoint = null;
this._debuggerNotificationObserver = new DebuggerNotificationObserver();
},
// Used by the ObjectActor to keep track of the depth of grip() calls.
_gripDepth: null,
get dbg() {
if (!this._dbg) {
this._dbg = this._parent.dbg;
// Keep the debugger disabled until a client attaches.
if (this._state === STATES.DETACHED) {
this._dbg.disable();
} else {
this._dbg.enable();
}
}
return this._dbg;
},
// Current state of the thread actor:
// - detached: state, before ThreadActor.attach is called,
// - exited: state, after the actor is destroyed,
// States possible in between these two states:
// - running: default state, when the thread isn't paused,
// - paused: state, when paused on any type of breakpoint, or, when the client requested an interrupt.
get state() {
return this._state;
},
// XXX: soon to be equivalent to !isDestroyed once the thread actor is initialized on target creation.
get attached() {
return this.state == STATES.RUNNING || this.state == STATES.PAUSED;
},
get threadLifetimePool() {
if (!this._threadLifetimePool) {
this._threadLifetimePool = new Pool(this.conn, "thread");
this._threadLifetimePool.objectActors = new WeakMap();
}
return this._threadLifetimePool;
},
getThreadLifetimeObject(raw) {
return this.threadLifetimePool.objectActors.get(raw);
},
createValueGrip(value) {
return createValueGrip(value, this.threadLifetimePool, this.objectGrip);
},
get sourcesManager() {
return this._parent.sourcesManager;
},
get breakpoints() {
return this._parent.breakpoints;
},
get youngestFrame() {
if (this.state != STATES.PAUSED) {
return null;
}
return this.dbg.getNewestFrame();
},
get skipBreakpointsOption() {
return (
this._options.skipBreakpoints ||
(this.insideClientEvaluation && this.insideClientEvaluation.eager)
);
},
/**
* Keep track of all of the nested event loops we use to pause the debuggee
* when we hit a breakpoint/debugger statement/etc in one place so we can
* resolve them when we get resume packets. We have more than one (and keep
* them in a stack) because we can pause within client evals.
*/
_threadPauseEventLoops: null,
_pushThreadPause() {
if (!this._threadPauseEventLoops) {
this._threadPauseEventLoops = [];
}
const eventLoop = this._nestedEventLoops.push();
this._threadPauseEventLoops.push(eventLoop);
eventLoop.enter();
},
_popThreadPause() {
const eventLoop = this._threadPauseEventLoops.pop();
assert(eventLoop, "Should have an event loop.");
eventLoop.resolve();
},
isPaused() {
return this._state === STATES.PAUSED;
},
/**
* Remove all debuggees and clear out the thread's sources.
*/
clearDebuggees() {
if (this._dbg) {
this.dbg.removeAllDebuggees();
}
},
/**
* Destroy the debugger and put the actor in the exited state.
*
* As part of destroy, we: clean up listeners, debuggees and
* clear actor pools associated with the lifetime of this actor.
*/
destroy() {
dumpn("in ThreadActor.prototype.destroy");
if (this._state == STATES.PAUSED) {
this.doResume();
}
this.removeAllWatchpoints();
this._xhrBreakpoints = [];
this._updateNetworkObserver();
this._activeEventBreakpoints = new Set();
this._debuggerNotificationObserver.removeListener(
this._eventBreakpointListener
);
for (const global of this.dbg.getDebuggees()) {
try {
this._debuggerNotificationObserver.disconnect(
global.unsafeDereference()
);
} catch (e) {}
}
this._parent.off("window-ready", this._onWindowReady);
this._parent.off("will-navigate", this._onWillNavigate);
this._parent.off("navigate", this._onNavigate);
this.sourcesManager.off("newSource", this.onNewSourceEvent);
this.clearDebuggees();
this._threadLifetimePool.destroy();
this._threadLifetimePool = null;
this._dbg = null;
this._state = STATES.EXITED;
Actor.prototype.destroy.call(this);
},
// Request handlers
attach(options) {
if (this.state === STATES.EXITED) {
throw {
error: "exited",
message: "threadActor has exited",
};
}
if (this.state !== STATES.DETACHED) {
throw {
error: "wrongState",
message: "Current state is " + this.state,
};
}
this.dbg.onDebuggerStatement = this.onDebuggerStatement;
this.dbg.onNewScript = this.onNewScript;
this.dbg.onNewDebuggee = this._onNewDebuggee;
this.sourcesManager.on("newSource", this.onNewSourceEvent);
// Initialize an event loop stack. This can't be done in the constructor,
// because this.conn is not yet initialized by the actor pool at that time.
this._nestedEventLoops = new EventLoopStack({
thread: this,
});
this.dbg.enable();
this.reconfigure(options);
// Set everything up so that breakpoint can work
this._state = STATES.RUNNING;
// Notify the parent that we've finished attaching. If this is a worker
// thread which was paused until attaching, this will allow content to
// begin executing.
if (this._parent.onThreadAttached) {
this._parent.onThreadAttached();
}
if (Services.obs) {
// Set a wrappedJSObject property so |this| can be sent via the observer service
// for the xpcshell harness.
this.wrappedJSObject = this;
Services.obs.notifyObservers(this, "devtools-thread-ready");
}
},
toggleEventLogging(logEventBreakpoints) {
this._options.logEventBreakpoints = logEventBreakpoints;
return this._options.logEventBreakpoints;
},
get pauseOverlay() {
if (this._pauseOverlay) {
return this._pauseOverlay;
}
const env = new HighlighterEnvironment();
env.initFromTargetActor(this._parent);
const highlighter = new PausedDebuggerOverlay(env, {
resume: () => this.resume(null),
stepOver: () => this.resume({ type: "next" }),
});
this._pauseOverlay = highlighter;
return highlighter;
},
_canShowOverlay() {
// The CanvasFrameAnonymousContentHelper class we're using to create the paused overlay
// need to have access to a documentElement.
// Accept only browsing context target which exposes such element, but ignore
// privileged document (top level window, special about:* pages, …).
return (
// We might have access to a non-chrome window getter that is a Sandox (e.g. in the
// case of ContentProcessTargetActor).
this._parent.window?.document?.documentElement &&
!this._parent.window.isChromeWindow
);
},
async showOverlay() {
if (
this._options.shouldShowOverlay &&
this.isPaused() &&
this._canShowOverlay() &&
this._parent.on &&
this.pauseOverlay
) {
const reason = this._priorPause.why.type;
await this.pauseOverlay.isReady;
// we might not be paused anymore.
if (!this.isPaused()) {
return;
}
this.pauseOverlay.show(reason);
}
},
hideOverlay() {
if (this._canShowOverlay() && this._pauseOverlay) {
this.pauseOverlay.hide();
}
},
/**
* Tell the thread to automatically add a breakpoint on the first line of
* a given file, when it is first loaded.
*
* This is currently only used by the xpcshell test harness, and unless
* we decide to expand the scope of this feature, we should keep it that way.
*/
setBreakpointOnLoad(urls) {
this._onLoadBreakpointURLs = new Set(urls);
},
_findXHRBreakpointIndex(p, m) {
return this._xhrBreakpoints.findIndex(
({ path, method }) => path === p && method === m
);
},
// We clear the priorPause field when a breakpoint is added or removed
// at the same location because we are no longer worried about pausing twice
// at that location (e.g. debugger statement, stepping).
_maybeClearPriorPause(location) {
if (!this._priorPause) {
return;
}
const { where } = this._priorPause.frame;
if (where.line === location.line && where.column === location.column) {
this._priorPause = null;
}
},
async setBreakpoint(location, options) {
const actor = this.breakpointActorMap.getOrCreateBreakpointActor(location);
actor.setOptions(options);
this._maybeClearPriorPause(location);
if (location.sourceUrl) {
// There can be multiple source actors for a URL if there are multiple
// inline sources on an HTML page.
const sourceActors = this.sourcesManager.getSourceActorsByURL(
location.sourceUrl
);
for (const sourceActor of sourceActors) {
await sourceActor.applyBreakpoint(actor);
}
} else {
const sourceActor = this.sourcesManager.getSourceActorById(
location.sourceId
);
if (sourceActor) {
await sourceActor.applyBreakpoint(actor);
}
}
},
removeBreakpoint(location) {
const actor = this.breakpointActorMap.getOrCreateBreakpointActor(location);
this._maybeClearPriorPause(location);
actor.delete();
},
removeXHRBreakpoint(path, method) {
const index = this._findXHRBreakpointIndex(path, method);
if (index >= 0) {
this._xhrBreakpoints.splice(index, 1);
}
return this._updateNetworkObserver();
},
setXHRBreakpoint(path, method) {
// request.path is a string,
// If requested url contains the path, then we pause.
const index = this._findXHRBreakpointIndex(path, method);
if (index === -1) {
this._xhrBreakpoints.push({ path, method });
}
return this._updateNetworkObserver();
},
getAvailableEventBreakpoints() {
return getAvailableEventBreakpoints();
},
getActiveEventBreakpoints() {
return Array.from(this._activeEventBreakpoints);
},
setActiveEventBreakpoints(ids) {
this._activeEventBreakpoints = new Set(ids);
if (eventsRequireNotifications(ids)) {
this._debuggerNotificationObserver.addListener(
this._eventBreakpointListener
);
} else {
this._debuggerNotificationObserver.removeListener(
this._eventBreakpointListener
);
}
if (this._activeEventBreakpoints.has(firstStatementBreakpointId())) {
this._ensureFirstStatementBreakpointInitialized();
this._firstStatementBreakpoint.hit = frame =>
this._pauseAndRespondEventBreakpoint(
frame,
firstStatementBreakpointId()
);
} else if (this._firstStatementBreakpoint) {
// Disabling the breakpoint disables the feature as much as we need it
// to. We do not bother removing breakpoints from the scripts themselves
// here because the breakpoints will be a no-op if `hit` is `null`, and
// if we wanted to remove them, we'd need a way to iterate through them
// all, which would require us to hold strong references to them, which
// just isn't needed. Plus, if the user disables and then re-enables the
// feature again later, the breakpoints will still be there to work.
this._firstStatementBreakpoint.hit = null;
}
},
_ensureFirstStatementBreakpointInitialized() {
if (this._firstStatementBreakpoint) {
return;
}
this._firstStatementBreakpoint = { hit: null };
for (const script of this.dbg.findScripts()) {
this._maybeTrackFirstStatementBreakpoint(script);
}
},
_maybeTrackFirstStatementBreakpointForNewGlobal(global) {
if (this._firstStatementBreakpoint) {
for (const script of this.dbg.findScripts({ global })) {
this._maybeTrackFirstStatementBreakpoint(script);
}
}
},
_maybeTrackFirstStatementBreakpoint(script) {
if (
// If the feature is not enabled yet, there is nothing to do.
!this._firstStatementBreakpoint ||
// WASM files don't have a first statement.
script.format !== "js" ||
// All "top-level" scripts are non-functions, whether that's because
// the script is a module, a global script, or an eval or what.
script.isFunction
) {
return;
}
const bps = script.getPossibleBreakpoints();
// Scripts aren't guaranteed to have a step start if for instance the
// file contains only function declarations, so in that case we try to
// fall back to whatever we can find.
let meta = bps.find(bp => bp.isStepStart) || bps[0];
if (!meta) {
// We've tried to avoid using `getAllColumnOffsets()` because the set of
// locations included in this list is very under-defined, but for this
// usecase it's not the end of the world. Maybe one day we could have an
// "onEnterFrame" that was scoped to a specific script to avoid this.
meta = script.getAllColumnOffsets()[0];
}
if (!meta) {
// Not certain that this is actually possible, but including for sanity
// so that we don't throw unexpectedly.
return;
}
script.setBreakpoint(meta.offset, this._firstStatementBreakpoint);
},
_onNewDebuggee(global) {
this._maybeTrackFirstStatementBreakpointForNewGlobal(global);
try {
this._debuggerNotificationObserver.connect(global.unsafeDereference());
} catch (e) {}
},
_updateNetworkObserver() {
// Workers don't have access to `Services` and even if they did, network
// requests are all dispatched to the main thread, so there would be
// nothing here to listen for. We'll need to revisit implementing
// XHR breakpoints for workers.
if (isWorker) {
return false;
}
if (this._xhrBreakpoints.length > 0 && !this._observingNetwork) {
this._observingNetwork = true;
Services.obs.addObserver(
this._onOpeningRequest,
"http-on-opening-request"
);
} else if (this._xhrBreakpoints.length === 0 && this._observingNetwork) {
this._observingNetwork = false;
Services.obs.removeObserver(
this._onOpeningRequest,
"http-on-opening-request"
);
}
return true;
},
_onOpeningRequest(subject) {
if (this.skipBreakpointsOption) {
return;
}
const channel = subject.QueryInterface(Ci.nsIHttpChannel);
const url = channel.URI.asciiSpec;
const requestMethod = channel.requestMethod;
let causeType = Ci.nsIContentPolicy.TYPE_OTHER;
if (channel.loadInfo) {
causeType = channel.loadInfo.externalContentPolicyType;
}
const isXHR =
causeType === Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST ||
causeType === Ci.nsIContentPolicy.TYPE_FETCH;
if (!isXHR) {
// We currently break only if the request is either fetch or xhr
return;
}
let shouldPause = false;
for (const { path, method } of this._xhrBreakpoints) {
if (method !== "ANY" && method !== requestMethod) {
continue;
}
if (url.includes(path)) {
shouldPause = true;
break;
}
}
if (shouldPause) {
const frame = this.dbg.getNewestFrame();
// If there is no frame, this request was dispatched by logic that isn't
// primarily JS, so pausing the event loop wouldn't make sense.
// This covers background requests like loading the initial page document,
// or loading favicons. This also includes requests dispatched indirectly
// from workers. We'll need to handle them separately in the future.
if (frame) {
this._pauseAndRespond(frame, { type: "XHR" });
}
}
},
reconfigure(options = {}) {
if (this.state == STATES.EXITED) {
throw {
error: "wrongState",
};
}
this._options = { ...this._options, ...options };
if ("observeAsmJS" in options) {
this.dbg.allowUnobservedAsmJS = !options.observeAsmJS;
}
if (
"pauseWorkersUntilAttach" in options &&
this._parent.pauseWorkersUntilAttach
) {
this._parent.pauseWorkersUntilAttach(options.pauseWorkersUntilAttach);
}
if (options.breakpoints) {
for (const breakpoint of Object.values(options.breakpoints)) {
this.setBreakpoint(breakpoint.location, breakpoint.options);
}
}
if (options.eventBreakpoints) {
this.setActiveEventBreakpoints(options.eventBreakpoints);
}
this.maybePauseOnExceptions();
},
_eventBreakpointListener(notification) {
if (this._state === STATES.PAUSED || this._state === STATES.DETACHED) {
return;
}
const eventBreakpoint = eventBreakpointForNotification(
this.dbg,
notification
);
if (!this._activeEventBreakpoints.has(eventBreakpoint)) {
return;
}
if (notification.phase === "pre" && !this._activeEventPause) {
this._activeEventPause = this._captureDebuggerHooks();
this.dbg.onEnterFrame = this._makeEventBreakpointEnterFrame(
eventBreakpoint
);
} else if (notification.phase === "post" && this._activeEventPause) {
this._restoreDebuggerHooks(this._activeEventPause);
this._activeEventPause = null;
} else if (!notification.phase && !this._activeEventPause) {
const frame = this.dbg.getNewestFrame();
if (frame) {
if (this.sourcesManager.isFrameBlackBoxed(frame)) {
return;
}
this._pauseAndRespondEventBreakpoint(frame, eventBreakpoint);
}
}
},
_makeEventBreakpointEnterFrame(eventBreakpoint) {
return frame => {
if (this.sourcesManager.isFrameBlackBoxed(frame)) {
return undefined;
}
this._restoreDebuggerHooks(this._activeEventPause);
this._activeEventPause = null;
return this._pauseAndRespondEventBreakpoint(frame, eventBreakpoint);
};
},
_pauseAndRespondEventBreakpoint(frame, eventBreakpoint) {
if (this.skipBreakpointsOption) {
return undefined;
}
if (this._options.logEventBreakpoints) {
return logEvent({
threadActor: this,
frame,
level: "logPoint",
expression: `[_event]`,
bindings: { _event: frame.arguments[0] },
});
}
return this._pauseAndRespond(frame, {
type: "eventBreakpoint",
breakpoint: eventBreakpoint,
message: makeEventBreakpointMessage(eventBreakpoint),
});
},
_captureDebuggerHooks() {
return {
onEnterFrame: this.dbg.onEnterFrame,
onStep: this.dbg.onStep,
onPop: this.dbg.onPop,
};
},
_restoreDebuggerHooks(hooks) {
this.dbg.onEnterFrame = hooks.onEnterFrame;
this.dbg.onStep = hooks.onStep;
this.dbg.onPop = hooks.onPop;
},
/**
* Pause the debuggee, by entering a nested event loop, and return a 'paused'
* packet to the client.
*
* @param Debugger.Frame frame
* The newest debuggee frame in the stack.
* @param object reason
* An object with a 'type' property containing the reason for the pause.
* @param function onPacket
* Hook to modify the packet before it is sent. Feel free to return a
* promise.
*/
_pauseAndRespond(frame, reason, onPacket = k => k) {
try {
const packet = this._paused(frame);
if (!packet) {
return undefined;
}
const {
sourceActor,
line,
column,
} = this.sourcesManager.getFrameLocation(frame);
packet.why = reason;
if (!sourceActor) {
// If the frame location is in a source that not pass the 'allowSource'
// check and thus has no actor, we do not bother pausing.
return undefined;
}
packet.frame.where = {
actor: sourceActor.actorID,
line: line,
column: column,
};
const pkt = onPacket(packet);
this._priorPause = pkt;
this.emit("paused", pkt);
this.showOverlay();
} catch (error) {
reportException("DBG-SERVER", error);
this.conn.send({
error: "unknownError",
message: error.message + "\n" + error.stack,
});
return undefined;
}
try {
this._pushThreadPause();
} catch (e) {
reportException("TA__pauseAndRespond", e);
}
if (this._requestedFrameRestart) {
return null;
}
// If the parent actor has been closed, terminate the debuggee script
// instead of continuing. Executing JS after the content window is gone is
// a bad idea.
return this._parentClosed ? null : undefined;
},
_makeOnEnterFrame({ pauseAndRespond }) {
return frame => {
if (this._requestedFrameRestart) {
return null;
}
// Continue forward until we get to a valid step target.
const { onStep, onPop } = this._makeSteppingHooks({
steppingType: "next",
});
if (this.sourcesManager.isFrameBlackBoxed(frame)) {
return undefined;
}
frame.onStep = onStep;
frame.onPop = onPop;
return undefined;
};
},
_makeOnPop({ pauseAndRespond, steppingType }) {
const thread = this;
return function(completion) {
if (thread._requestedFrameRestart === this) {
return thread.restartFrame(this);
}
// onPop is called when we temporarily leave an async/generator
if (steppingType != "finish" && (completion.await || completion.yield)) {
thread.suspendedFrame = this;
thread.dbg.onEnterFrame = undefined;
return undefined;
}
// Note that we're popping this frame; we need to watch for
// subsequent step events on its caller.
this.reportedPop = true;
// Cache the frame so that the onPop and onStep hooks are cleared
// on the next pause.
thread.suspendedFrame = this;
if (
steppingType != "finish" &&
!thread.sourcesManager.isFrameBlackBoxed(this)
) {
const pauseAndRespValue = pauseAndRespond(this, packet =>
thread.createCompletionGrip(packet, completion)
);
// If the requested frame to restart differs from this frame, we don't
// need to restart it at this point.
if (thread._requestedFrameRestart === this) {
return thread.restartFrame(this);
}
return pauseAndRespValue;
}
thread._attachSteppingHooks(this, "next", completion);
return undefined;
};
},
restartFrame(frame) {
this._requestedFrameRestart = null;
this._priorPause = null;
if (
frame.type !== "call" ||
frame.script.isGeneratorFunction ||
frame.script.isAsyncFunction
) {
return undefined;
}
RESTARTED_FRAMES.add(frame);
const completion = frame.callee.apply(frame.this, frame.arguments);
return completion;
},
hasMoved(frame, newType) {
const newLocation = this.sourcesManager.getFrameLocation(frame);
if (!this._priorPause) {
return true;
}
// Recursion/Loops makes it okay to resume and land at
// the same breakpoint or debugger statement.
// It is not okay to transition from a breakpoint to debugger statement
// or a step to a debugger statement.
const { type } = this._priorPause.why;
if (type == newType) {
return true;
}
const { line, column } = this._priorPause.frame.where;
return line !== newLocation.line || column !== newLocation.column;
},
_makeOnStep({ pauseAndRespond, startFrame, steppingType, completion }) {
const thread = this;
return function() {
if (thread._validFrameStepOffset(this, startFrame, this.offset)) {
return pauseAndRespond(this, packet =>
thread.createCompletionGrip(packet, completion)
);
}
return undefined;
};
},
_validFrameStepOffset(frame, startFrame, offset) {
const meta = frame.script.getOffsetMetadata(offset);
// Continue if:
// 1. the location is not a valid breakpoint position
// 2. the source is blackboxed
// 3. we have not moved since the last pause
if (
!meta.isBreakpoint ||
this.sourcesManager.isFrameBlackBoxed(frame) ||
!this.hasMoved(frame)
) {
return false;
}
// Pause if:
// 1. the frame has changed
// 2. the location is a step position.
return frame !== startFrame || meta.isStepStart;
},
atBreakpointLocation(frame) {
const location = this.sourcesManager.getFrameLocation(frame);
return !!this.breakpointActorMap.get(location);
},
createCompletionGrip(packet, completion) {
if (!completion) {
return packet;
}
const createGrip = value =>
createValueGrip(value, this._pausePool, this.objectGrip);
packet.why.frameFinished = {};
if (completion.hasOwnProperty("return")) {
packet.why.frameFinished.return = createGrip(completion.return);
} else if (completion.hasOwnProperty("yield")) {
packet.why.frameFinished.return = createGrip(completion.yield);
} else if (completion.hasOwnProperty("throw")) {
packet.why.frameFinished.throw = createGrip(completion.throw);
}
return packet;
},
/**
* Define the JS hook functions for stepping.
*/
_makeSteppingHooks({ steppingType, startFrame, completion }) {
// Bind these methods and state because some of the hooks are called
// with 'this' set to the current frame. Rather than repeating the
// binding in each _makeOnX method, just do it once here and pass it
// in to each function.
const steppingHookState = {
pauseAndRespond: (frame, onPacket = k => k) =>
this._pauseAndRespond(frame, { type: "resumeLimit" }, onPacket),
startFrame: startFrame || this.youngestFrame,
steppingType,
completion,
};
return {
onEnterFrame: this._makeOnEnterFrame(steppingHookState),
onPop: this._makeOnPop(steppingHookState),
onStep: this._makeOnStep(steppingHookState),
};
},
/**
* Handle attaching the various stepping hooks we need to attach when we
* receive a resume request with a resumeLimit property.
*
* @param Object { resumeLimit }
* The values received over the RDP.
* @returns A promise that resolves to true once the hooks are attached, or is
* rejected with an error packet.
*/
async _handleResumeLimit({ resumeLimit, frameActorID }) {
const steppingType = resumeLimit.type;
if (
!["break", "step", "next", "finish", "restart"].includes(steppingType)
) {
return Promise.reject({
error: "badParameterType",
message: "Unknown resumeLimit type",
});
}
let frame = this.youngestFrame;
if (frameActorID) {
frame = this._framesPool.getActorByID(frameActorID).frame;
if (!frame) {
throw new Error("Frame should exist in the frames pool.");
}
}
if (steppingType === "restart") {
if (
frame.type !== "call" ||
frame.script.isGeneratorFunction ||
frame.script.isAsyncFunction
) {
return undefined;
}
this._requestedFrameRestart = frame;
}
return this._attachSteppingHooks(frame, steppingType, undefined);
},
_attachSteppingHooks(frame, steppingType, completion) {
// If we are stepping out of the onPop handler, we want to use "next" mode
// so that the parent frame's handlers behave consistently.
if (steppingType === "finish" && frame.reportedPop) {
steppingType = "next";
}
// If there are no more frames on the stack, use "step" mode so that we will
// pause on the next script to execute.
const stepFrame = this._getNextStepFrame(frame);
if (!stepFrame) {
steppingType = "step";
}
const { onEnterFrame, onPop, onStep } = this._makeSteppingHooks({
steppingType,
completion,
startFrame: frame,
});
if (steppingType === "step" || steppingType === "restart") {
this.dbg.onEnterFrame = onEnterFrame;
}
if (stepFrame) {
switch (steppingType) {
case "step":
case "break":
case "next":
if (stepFrame.script) {
if (!this.sourcesManager.isFrameBlackBoxed(stepFrame)) {
stepFrame.onStep = onStep;
}
}
// eslint-disable no-fallthrough
case "finish":
stepFrame.onStep = createStepForReactionTracking(stepFrame.onStep);
// eslint-disable no-fallthrough
case "restart":
stepFrame.onPop = onPop;
break;
}
}
return true;
},
/**
* Clear the onStep and onPop hooks for all frames on the stack.
*/
_clearSteppingHooks() {
if (this.suspendedFrame) {
this.suspendedFrame.onStep = undefined;
this.suspendedFrame.onPop = undefined;
this.suspendedFrame = undefined;
}
let frame = this.youngestFrame;
if (frame?.onStack) {
while (frame) {
frame.onStep = undefined;
frame.onPop = undefined;
frame = frame.older;
}
}
},
/**
* Handle a protocol request to resume execution of the debuggee.
*/
async resume(resumeLimit, frameActorID) {
if (this._state !== STATES.PAUSED) {
return {
error: "wrongState",
message:
"Can't resume when debuggee isn't paused. Current state is '" +
this._state +
"'",
state: this._state,
};
}
// In case of multiple nested event loops (due to multiple debuggers open in
// different tabs or multiple devtools clients connected to the same tab)
// only allow resumption in a LIFO order.
if (
this._nestedEventLoops.size &&
this._nestedEventLoops.lastPausedThreadActor &&
this._nestedEventLoops.lastPausedThreadActor !== this
) {
return {
error: "wrongOrder",
message: "trying to resume in the wrong order.",
};
}
try {
if (resumeLimit) {
await this._handleResumeLimit({ resumeLimit, frameActorID });
} else {
this._clearSteppingHooks();
}
this.doResume({ resumeLimit });
return {};
} catch (error) {
return error instanceof Error
? {
error: "unknownError",
message: DevToolsUtils.safeErrorString(error),
}
: // It is a known error, and the promise was rejected with an error
// packet.
error;
}
},
/**
* Only resume and notify necessary observers. This should be used in cases
* when we do not want to notify the front end of a resume, for example when
* we are shutting down.
*/
doResume({ resumeLimit } = {}) {
this._state = STATES.RUNNING;
// Drop the actors in the pause actor pool.
this._pausePool.destroy();
this._pausePool = null;
this._pauseActor = null;
this._popThreadPause();
// Tell anyone who cares of the resume (as of now, that's the xpcshell harness and
// devtools-startup.js when handling the --wait-for-jsdebugger flag)
this.emit("resumed");
this.hideOverlay();
},
/**
* Spin up a nested event loop so we can synchronously resolve a promise.
*
* DON'T USE THIS UNLESS YOU ABSOLUTELY MUST! Nested event loops suck: the
* world's state can change out from underneath your feet because JS is no
* longer run-to-completion.
*
* @param p
* The promise we want to resolve.
* @returns The promise's resolution.
*/
unsafeSynchronize(p) {
let needNest = true;
let eventLoop;
let returnVal;
p.then(resolvedVal => {
needNest = false;
returnVal = resolvedVal;
})
.catch(e => reportException("unsafeSynchronize", e))
.then(() => {
if (eventLoop) {
eventLoop.resolve();
}
});
if (needNest) {
eventLoop = this._nestedEventLoops.push();
eventLoop.enter();
}
return returnVal;
},
/**
* Set the debugging hook to pause on exceptions if configured to do so.
*/
maybePauseOnExceptions() {
if (this._options.pauseOnExceptions) {
this.dbg.onExceptionUnwind = this._onExceptionUnwind;
} else {
this.dbg.onExceptionUnwind = undefined;
}
},
/**
* Helper method that returns the next frame when stepping.
*/
_getNextStepFrame(frame) {
const endOfFrame = frame.reportedPop;
const stepFrame = endOfFrame
? frame.older || getAsyncParentFrame(frame)
: frame;
if (!stepFrame || !stepFrame.script) {
return null;
}
// Skips a frame that has been restarted.
if (RESTARTED_FRAMES.has(stepFrame)) {
return this._getNextStepFrame(stepFrame.older);
}
return stepFrame;
},
frames(start, count) {
if (this.state !== STATES.PAUSED) {
return {
error: "wrongState",
message:
"Stack frames are only available while the debuggee is paused.",
};
}
// Find the starting frame...
let frame = this.youngestFrame;
const walkToParentFrame = () => {
if (!frame) {
return;
}
const currentFrame = frame;
frame = null;
if (!(currentFrame instanceof Debugger.Frame)) {
frame = getSavedFrameParent(this, currentFrame);
} else if (currentFrame.older) {
frame = currentFrame.older;
} else if (
this._options.shouldIncludeSavedFrames &&
currentFrame.olderSavedFrame
) {
frame = currentFrame.olderSavedFrame;
if (frame && !isValidSavedFrame(this, frame)) {
frame = null;
}
} else if (
this._options.shouldIncludeAsyncLiveFrames &&
currentFrame.asyncPromise
) {
const asyncFrame = getAsyncParentFrame(currentFrame);
if (asyncFrame) {
frame = asyncFrame;
}
}
};
let i = 0;
while (frame && i < start) {
walkToParentFrame();
i++;
}
// Return count frames, or all remaining frames if count is not defined.
const frames = [];
for (; frame && (!count || i < start + count); i++, walkToParentFrame()) {
// SavedFrame instances don't have direct Debugger.Source object. If
// there is an active Debugger.Source that represents the SaveFrame's
// source, it will have already been created in the server.
if (frame instanceof Debugger.Frame) {
const sourceActor = this.sourcesManager.createSourceActor(
frame.script.source
);
if (!sourceActor) {
continue;
}
}
if (RESTARTED_FRAMES.has(frame)) {
continue;
}
const frameActor = this._createFrameActor(frame, i);
frames.push(frameActor);
}
return { frames };
},
addAllSources() {
// Compare the sources we find with the source URLs which have been loaded
// in debuggee realms. Count the number of sources associated with each
// URL so that we can detect if an HTML file has had some inline sources
// collected but not all.
const urlMap = {};
for (const url of this.dbg.findSourceURLs()) {
if (url !== "self-hosted") {
urlMap[url] = 1 + (urlMap[url] || 0);
}
}
const sources = this.dbg.findSources();
for (const source of sources) {
this._addSource(source);
const url = getDebuggerSourceURL(source);
if (url) {
urlMap[url]--;
}
}
// Resurrect any URLs for which not all sources are accounted for.
for (const [url, count] of Object.entries(urlMap)) {
if (count > 0) {
this._resurrectSource(url);
}
}
},
sources(request) {
this.addAllSources();
// No need to flush the new source packets here, as we are sending the
// list of sources out immediately and we don't need to invoke the
// overhead of an RDP packet for every source right now. Let the default
// timeout flush the buffered packets.
return this.sourcesManager.iter().map(s => s.form());
},
/**
* Disassociate all breakpoint actors from their scripts and clear the
* breakpoint handlers. This method can be used when the thread actor intends
* to keep the breakpoint store, but needs to clear any actual breakpoints,
* e.g. due to a page navigation. This way the breakpoint actors' script
* caches won't hold on to the Debugger.Script objects leaking memory.
*/
disableAllBreakpoints() {
for (const bpActor of this.breakpointActorMap.findActors()) {
bpActor.removeScripts();
}
},
removeAllWatchpoints() {
for (const actor of this.threadLifetimePool.poolChildren()) {
if (actor.typeName == "obj") {
actor.removeWatchpoints();
}
}
},
addWatchpoint(objActor, data) {
this._watchpointsMap.add(objActor, data);
},
removeWatchpoint(objActor, property) {
this._watchpointsMap.remove(objActor, property);
},
getWatchpoint(obj, property) {
return this._watchpointsMap.get(obj, property);
},
/**
* Handle a protocol request to pause the debuggee.
*/
interrupt(when) {
if (this.state == STATES.EXITED) {
return { type: "exited" };
} else if (this.state == STATES.PAUSED) {
// TODO: return the actual reason for the existing pause.
this.emit("paused", {
why: { type: "alreadyPaused" },
});
return {};
} else if (this.state != STATES.RUNNING) {
return {
error: "wrongState",
message: "Received interrupt request in " + this.state + " state.",
};
}
try {
// If execution should pause just before the next JavaScript bytecode is
// executed, just set an onEnterFrame handler.
if (when == "onNext") {
const onEnterFrame = frame => {
this._pauseAndRespond(frame, { type: "interrupted", onNext: true });
};
this.dbg.onEnterFrame = onEnterFrame;
this.emit("willInterrupt");
return {};
}
// If execution should pause immediately, just put ourselves in the paused
// state.
const packet = this._paused();
if (!packet) {
return { error: "notInterrupted" };
}
packet.why = { type: "interrupted", onNext: false };
// Send the response to the interrupt request now (rather than
// returning it), because we're going to start a nested event loop
// here.
this.conn.send({ from: this.actorID, type: "interrupt" });
this.emit("paused", packet);
// Start a nested event loop.
this._pushThreadPause();
// We already sent a response to this request, don't send one
// now.
return null;
} catch (e) {
reportException("DBG-SERVER", e);
return { error: "notInterrupted", message: e.toString() };
}
},
_paused(frame) {
// We don't handle nested pauses correctly. Don't try - if we're
// paused, just continue running whatever code triggered the pause.
// We don't want to actually have nested pauses (although we
// have nested event loops). If code runs in the debuggee during
// a pause, it should cause the actor to resume (dropping
// pause-lifetime actors etc) and then repause when complete.
if (this.state === STATES.PAUSED) {
return undefined;
}
this._state = STATES.PAUSED;
// Clear stepping hooks.
this.dbg.onEnterFrame = undefined;
this._requestedFrameRestart = null;
this._clearSteppingHooks();
// Create the actor pool that will hold the pause actor and its
// children.
assert(!this._pausePool, "No pause pool should exist yet");
this._pausePool = new Pool(this.conn, "pause");
// Give children of the pause pool a quick link back to the
// thread...
this._pausePool.threadActor = this;
// Create the pause actor itself...
assert(!this._pauseActor, "No pause actor should exist yet");
this._pauseActor = new PauseActor(this._pausePool);
this._pausePool.manage(this._pauseActor);
// Update the list of frames.
const poppedFrames = this._updateFrames();
// Send off the paused packet and spin an event loop.
const packet = {
actor: this._pauseActor.actorID,
};
if (frame) {
packet.frame = this._createFrameActor(frame);
}
if (poppedFrames) {
packet.poppedFrames = poppedFrames;
}
return packet;
},
/**
* Expire frame actors for frames that have been popped.
*
* @returns A list of actor IDs whose frames have been popped.
*/
_updateFrames() {
const popped = [];
// Create the actor pool that will hold the still-living frames.
const framesPool = new Pool(this.conn, "frames");
const frameList = [];
for (const frameActor of this._frameActors) {
if (frameActor.frame.onStack) {
framesPool.manage(frameActor);
frameList.push(frameActor);
} else {
popped.push(frameActor.actorID);
}
}
// Remove the old frame actor pool, this will expire
// any actors that weren't added to the new pool.
if (this._framesPool) {
this._framesPool.destroy();
}
this._frameActors = frameList;
this._framesPool = framesPool;
return popped;
},
_createFrameActor(frame, depth) {
let actor = this._frameActorMap.get(frame);
if (!actor) {
actor = new FrameActor(frame, this, depth);
this._frameActors.push(actor);
this._framesPool.manage(actor);
this._frameActorMap.set(frame, actor);
}
return actor;
},
/**
* Create and return an environment actor that corresponds to the provided
* Debugger.Environment.
* @param Debugger.Environment environment
* The lexical environment we want to extract.
* @param object pool
* The pool where the newly-created actor will be placed.
* @return The EnvironmentActor for environment or undefined for host
* functions or functions scoped to a non-debuggee global.
*/
createEnvironmentActor(environment, pool) {
if (!environment) {
return undefined;
}
if (environment.actor) {
return environment.actor;
}
const actor = new EnvironmentActor(environment, this);
pool.manage(actor);
environment.actor = actor;
return actor;
},
/**
* Create a grip for the given debuggee object.
*
* @param value Debugger.Object
* The debuggee object value.
* @param pool Pool
* The actor pool where the new object actor will be added.
*/
objectGrip(value, pool) {
if (!pool.objectActors) {
pool.objectActors = new WeakMap();
}
if (pool.objectActors.has(value)) {
return pool.objectActors.get(value).form();
}
if (this.threadLifetimePool.objectActors.has(value)) {
return this.threadLifetimePool.objectActors.get(value).form();
}
const actor = new PauseScopedObjectActor(
value,
{
thread: this,
getGripDepth: () => this._gripDepth,
incrementGripDepth: () => this._gripDepth++,
decrementGripDepth: () => this._gripDepth--,
createValueGrip: v => {
if (this._pausePool) {
return createValueGrip(v, this._pausePool, this.pauseObjectGrip);
}
return createValueGrip(v, this.threadLifetimePool, this.objectGrip);
},
createEnvironmentActor: (e, p) => this.createEnvironmentActor(e, p),
promote: () => this.threadObjectGrip(actor),
isThreadLifetimePool: () =>
actor.getParent() !== this.threadLifetimePool,
},
this.conn
);
pool.manage(actor);
pool.objectActors.set(value, actor);
return actor.form();
},
/**
* Create a grip for the given debuggee object with a pause lifetime.
*
* @param value Debugger.Object
* The debuggee object value.
*/
pauseObjectGrip(value) {
if (!this._pausePool) {
throw new Error("Object grip requested while not paused.");
}
return this.objectGrip(value, this._pausePool);
},
/**
* Extend the lifetime of the provided object actor to thread lifetime.
*
* @param actor object
* The object actor.
*/
threadObjectGrip(actor) {
this.threadLifetimePool.manage(actor);
this.threadLifetimePool.objectActors.set(actor.obj, actor);
},
_onWindowReady({ isTopLevel, isBFCache, window }) {
if (isTopLevel && this.state != STATES.DETACHED) {
this.sourcesManager.reset();
this.clearDebuggees();
this.dbg.enable();
// Update the global no matter if the debugger is on or off,
// otherwise the global will be wrong when enabled later.
this.global = window;
}
// Refresh the debuggee list when a new window object appears (top window or
// iframe).
if (this.attached) {
this.dbg.addDebuggees();
}
// BFCache navigations reuse old sources, so send existing sources to the
// client instead of waiting for onNewScript debugger notifications.
if (isBFCache) {
this.addAllSources();
}
},
_onWillNavigate({ isTopLevel }) {
if (!isTopLevel) {
return;
}
// Proceed normally only if the debuggee is not paused.
if (this.state == STATES.PAUSED) {
this.unsafeSynchronize(Promise.resolve(this.doResume()));
this.dbg.disable();
}
this.removeAllWatchpoints();
this.disableAllBreakpoints();
this.dbg.onEnterFrame = undefined;
},
_onNavigate() {
if (this.state == STATES.RUNNING) {
this.dbg.enable();
}
},
// JS Debugger API hooks.
pauseForMutationBreakpoint(
mutationType,
targetNode,
ancestorNode,
action = "" // "add" or "remove"
) {
if (
!["subtreeModified", "nodeRemoved", "attributeModified"].includes(
mutationType
)
) {
throw new Error("Unexpected mutation breakpoint type");
}
const frame = this.dbg.getNewestFrame();
if (!frame) {
return undefined;
}
if (
this.skipBreakpointsOption ||
this.sourcesManager.isFrameBlackBoxed(frame)
) {
return undefined;
}
const global = (targetNode.ownerDocument || targetNode).defaultView;
assert(global && this.dbg.hasDebuggee(global));
const targetObj = this.dbg
.makeGlobalObjectReference(global)
.makeDebuggeeValue(targetNode);
let ancestorObj = null;
if (ancestorNode) {
ancestorObj = this.dbg
.makeGlobalObjectReference(global)
.makeDebuggeeValue(ancestorNode);
}
return this._pauseAndRespond(
frame,
{
type: "mutationBreakpoint",
mutationType,
message: `DOM Mutation: '${mutationType}'`,
},
pkt => {
// We have to add this here because `_pausePool` is `null` beforehand.
pkt.why.nodeGrip = this.objectGrip(targetObj, this._pausePool);
pkt.why.ancestorGrip = ancestorObj
? this.objectGrip(ancestorObj, this._pausePool)
: null;
pkt.why.action = action;
return pkt;
}
);
},
/**
* A function that the engine calls when a debugger statement has been
* executed in the specified frame.
*
* @param frame Debugger.Frame
* The stack frame that contained the debugger statement.
*/
onDebuggerStatement(frame) {
// Don't pause if
// 1. we have not moved since the last pause
// 2. breakpoints are disabled
// 3. the source is blackboxed
// 4. there is a breakpoint at the same location
if (
!this.hasMoved(frame, "debuggerStatement") ||
this.skipBreakpointsOption ||
this.sourcesManager.isFrameBlackBoxed(frame) ||
this.atBreakpointLocation(frame)
) {
return undefined;
}
return this._pauseAndRespond(frame, { type: "debuggerStatement" });
},
skipBreakpoints(skip) {
this._options.skipBreakpoints = skip;
return { skip };
},
// Bug 1686485 is meant to remove usages of this request
// in favor direct call to `reconfigure`
pauseOnExceptions(pauseOnExceptions, ignoreCaughtExceptions) {
this.reconfigure({
pauseOnExceptions,
ignoreCaughtExceptions,
});
return {};
},
/**
* A function that the engine calls when an exception has been thrown and has
* propagated to the specified frame.
*
* @param youngestFrame Debugger.Frame
* The youngest remaining stack frame.
* @param value object
* The exception that was thrown.
*/
_onExceptionUnwind(youngestFrame, value) {
// Ignore any reported exception if we are already paused
if (this.isPaused()) {
return undefined;
}
let willBeCaught = false;
for (let frame = youngestFrame; frame != null; frame = frame.older) {
if (frame.script.isInCatchScope(frame.offset)) {
willBeCaught = true;
break;
}
}
if (willBeCaught && this._options.ignoreCaughtExceptions) {
return undefined;
}
if (
this._handledFrameExceptions.has(youngestFrame) &&
this._handledFrameExceptions.get(youngestFrame) === value
) {
return undefined;
}
// NS_ERROR_NO_INTERFACE exceptions are a special case in browser code,
// since they're almost always thrown by QueryInterface functions, and
// handled cleanly by native code.
if (!isWorker && value == Cr.NS_ERROR_NO_INTERFACE) {
return undefined;
}
// Don't pause on exceptions thrown while inside an evaluation being done on
// behalf of the client.
if (this.insideClientEvaluation) {
return undefined;
}
if (
this.skipBreakpointsOption ||
this.sourcesManager.isFrameBlackBoxed(youngestFrame)
) {
return undefined;
}
// Now that we've decided to pause, ignore this exception if it's thrown by
// any older frames.
for (let frame = youngestFrame.older; frame != null; frame = frame.older) {
this._handledFrameExceptions.set(frame, value);
}
try {
const packet = this._paused(youngestFrame);
if (!packet) {
return undefined;
}
packet.why = {
type: "exception",
exception: createValueGrip(value, this._pausePool, this.objectGrip),
};
this.emit("paused", packet);
this._pushThreadPause();
} catch (e) {
reportException("TA_onExceptionUnwind", e);
}
return undefined;
},
/**
* A function that the engine calls when a new script has been loaded.
*
* @param script Debugger.Script
* The source script that has been loaded into a debuggee compartment.
*/
onNewScript(script) {
this._addSource(script.source);
this._maybeTrackFirstStatementBreakpoint(script);
},
/**
* A function called when there's a new source from a thread actor's sources.
* Emits `newSource` on the thread actor.
*
* @param {SourceActor} source
*/
onNewSourceEvent(source) {
// When this target is supported by the Watcher Actor,
// and we listen to SOURCE, we avoid emitting the newSource RDP event
// as it would be duplicated with the Resource/watchResources API.
// Could probably be removed once bug 1680280 is fixed.
if (!this._shouldEmitNewSource) {
return;
}
// Bug 1516197: New sources are likely detected due to either user
// interaction on the page, or devtools requests sent to the server.
// We use executeSoon because we don't want to block those operations
// by sending packets in the middle of them.
DevToolsUtils.executeSoon(() => {
if (this.isDestroyed()) {
return;
}
this.emit("newSource", {
source: source.form(),
});
});
},
// API used by the Watcher Actor to disable the newSource events
// Could probably be removed once bug 1680280 is fixed.
_shouldEmitNewSource: true,
disableNewSourceEvents() {
this._shouldEmitNewSource = false;
},
/**
* Add the provided source to the server cache.
*
* @param aSource Debugger.Source
* The source that will be stored.
* @returns true, if the source was added; false otherwise.
*/
_addSource(source) {
if (!this.sourcesManager.allowSource(source)) {
return false;
}
// Preloaded WebExtension content scripts may be cached internally by
// ExtensionContent.jsm and ThreadActor would ignore them on a page reload
// because it finds them in the _debuggerSourcesSeen WeakSet,
// and so we also need to be sure that there is still a source actor for the source.
let sourceActor;
if (
this._debuggerSourcesSeen.has(source) &&
this.sourcesManager.hasSourceActor(source)
) {
sourceActor = this.sourcesManager.getSourceActor(source);
sourceActor.resetDebuggeeScripts();
} else {
sourceActor = this.sourcesManager.createSourceActor(source);
}
const sourceUrl = sourceActor.url;
if (this._onLoadBreakpointURLs.has(sourceUrl)) {
// Immediately set a breakpoint on first line
// (note that this is only used by `./mach xpcshell-test --jsdebugger`)
this.setBreakpoint({ sourceUrl, line: 1 }, {});
// But also query asynchronously the first really breakable line
// as the first may not be valid and won't break.
(async () => {
const [firstLine] = await sourceActor.getBreakableLines();
if (firstLine != 1) {
this.setBreakpoint({ sourceUrl, line: firstLine }, {});
}
})();
}
const bpActors = this.breakpointActorMap
.findActors()
.filter(
actor =>
actor.location.sourceUrl && actor.location.sourceUrl == sourceUrl
);
for (const actor of bpActors) {
sourceActor.applyBreakpoint(actor);
}
this._debuggerSourcesSeen.add(source);
return true;
},
/**
* Create a new source by refetching the specified URL and instantiating all
* sources that were found in the result.
*
* @param url The URL string to fetch.
*/
async _resurrectSource(url) {
let {
content,
contentType,
sourceMapURL,
} = await this.sourcesManager.urlContents(
url,
/* partial */ false,
/* canUseCache */ true
);
// Newlines in all sources should be normalized. Do this with HTML content
// to simplify the comparisons below.
content = content.replace(/\r\n?|\u2028|\u2029/g, "\n");
if (contentType == "text/html") {
// HTML files can contain any number of inline sources. We have to find
// all the inline sources and their start line without running any of the
// scripts on the page. The approach used here is approximate.
if (!this._parent.window) {
return;
}
// Find the offsets in the HTML at which inline scripts might start.
const scriptTagMatches = content.matchAll(/<script[^>]*>/gi);
const scriptStartOffsets = [...scriptTagMatches].map(
rv => rv.index + rv[0].length
);
// Find the script tags in this HTML page by parsing a new document from
// the contentand looking for its script elements.
const document = new DOMParser().parseFromString(content, "text/html");
// For each inline source found, see if there is a start offset for what
// appears to be a script tag, whose contents match the inline source.
const scripts = document.querySelectorAll("script");
for (const script of scripts) {
if (script.src) {
continue;
}
const text = script.innerText;
for (const offset of scriptStartOffsets) {
if (content.substring(offset, offset + text.length) == text) {
const allLineBreaks = content.substring(0, offset).matchAll("\n");
const startLine = 1 + [...allLineBreaks].length;
try {
const global = this.dbg.getDebuggees()[0];
this._addSource(
global.createSource({
text,
url,
startLine,
isScriptElement: true,
})
);
} catch (e) {
// Ignore parse errors.
}
break;
}
}
}
// If no scripts were found, we might have an inaccurate content type and
// the file is actually JavaScript. Fall through and add the entire file
// as the source.
if (scripts.length) {
return;
}
}
// Other files should only contain javascript, so add the file contents as
// the source itself.
try {
const global = this.dbg.getDebuggees()[0];
this._addSource(
global.createSource({
text: content,
url,
startLine: 1,
sourceMapURL,
})
);
} catch (e) {
// Ignore parse errors.
}
},
dumpThread() {
return {
pauseOnExceptions: this._options.pauseOnExceptions,
ignoreCaughtExceptions: this._options.ignoreCaughtExceptions,
logEventBreakpoints: this._options.logEventBreakpoints,
skipBreakpoints: this.skipBreakpointsOption,
breakpoints: this.breakpointActorMap.listKeys(),
};
},
// NOTE: dumpPools is defined in the Thread actor to avoid
// adding it to multiple target specs and actors.
dumpPools() {
return this.conn.dumpPools();
},
logLocation(prefix, frame) {
const loc = this.sourcesManager.getFrameLocation(frame);
dump(`${prefix} (${loc.line}, ${loc.column})\n`);
},
});
exports.ThreadActor = ThreadActor;
/**
* Creates a PauseActor.
*
* PauseActors exist for the lifetime of a given debuggee pause. Used to
* scope pause-lifetime grips.
*
* @param {Pool} pool: The actor pool created for this pause.
*/
function PauseActor(pool) {
this.pool = pool;
}
PauseActor.prototype = {
typeName: "pause",
};
// Utility functions.
/**
* Unwrap a global that is wrapped in a |Debugger.Object|, or if the global has
* become a dead object, return |undefined|.
*
* @param Debugger.Object wrappedGlobal
* The |Debugger.Object| which wraps a global.
*
* @returns {Object|undefined}
* Returns the unwrapped global object or |undefined| if unwrapping
* failed.
*/
exports.unwrapDebuggerObjectGlobal = wrappedGlobal => {
try {
// Because of bug 991399 we sometimes get nuked window references here. We
// just bail out in that case.
//
// Note that addon sandboxes have a DOMWindow as their prototype. So make
// sure that we can touch the prototype too (whatever it is), in case _it_
// is it a nuked window reference. We force stringification to make sure
// that any dead object proxies make themselves known.
const global = wrappedGlobal.unsafeDereference();
Object.getPrototypeOf(global) + "";
return global;
} catch (e) {
return undefined;
}
};
|