File: InspectorDebuggerAgent.cpp

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (1983 lines) | stat: -rw-r--r-- 73,694 bytes parent folder | download | duplicates (7)
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
/*
 * Copyright (C) 2010-2024 Apple Inc. All rights reserved.
 * Copyright (C) 2010, 2011 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1.  Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 * 2.  Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
 *     its contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "InspectorDebuggerAgent.h"

#include "AsyncStackTrace.h"
#include "ContentSearchUtilities.h"
#include "Debugger.h"
#include "DebuggerScope.h"
#include "DeferGC.h"
#include "ExecutableBaseInlines.h"
#include "HeapIterationScope.h"
#include "InjectedScript.h"
#include "InjectedScriptManager.h"
#include "JITCode.h"
#include "JITThunks.h"
#include "JSJavaScriptCallFrame.h"
#include "JavaScriptCallFrame.h"
#include "MarkedSpaceInlines.h"
#include "Microtask.h"
#include "NativeExecutable.h"
#include "RegularExpression.h"
#include "ScriptCallStack.h"
#include "ScriptCallStackFactory.h"
#include "Weak.h"
#include <wtf/Box.h>
#include <wtf/Function.h>
#include <wtf/JSONValues.h>
#include <wtf/Stopwatch.h>
#include <wtf/TZoneMallocInlines.h>
#include <wtf/text/MakeString.h>
#include <wtf/text/StringToIntegerConversion.h>
#include <wtf/text/WTFString.h>

namespace Inspector {

const ASCIILiteral InspectorDebuggerAgent::backtraceObjectGroup = "backtrace"_s;

WTF_MAKE_TZONE_ALLOCATED_IMPL(InspectorDebuggerAgent);
WTF_MAKE_TZONE_ALLOCATED_IMPL(InspectorDebuggerAgent::ProtocolBreakpoint);

// Objects created and retained by evaluating breakpoint actions are put into object groups
// according to the breakpoint action identifier assigned by the frontend. A breakpoint may
// have several object groups, and objects from several backend breakpoint action instances may
// create objects in the same group.
static String objectGroupForBreakpointAction(JSC::BreakpointActionID id)
{
    return makeString("breakpoint-action-"_s, id);
}

static bool isWebKitInjectedScript(const String& sourceURL)
{
    return sourceURL.startsWith("__InjectedScript_"_s) && sourceURL.endsWith(".js"_s);
}

static JSC::Debugger::BlackboxRange blackboxRange(const JSC::Debugger::Script& script)
{
    return {
        { OrdinalNumber::fromZeroBasedInt(script.startLine), OrdinalNumber::fromZeroBasedInt(script.startColumn) },
        { OrdinalNumber::fromZeroBasedInt(script.endLine), OrdinalNumber::fromZeroBasedInt(script.endColumn) },
    };
}

static std::optional<JSC::Breakpoint::Action::Type> breakpointActionTypeForString(Protocol::ErrorString& errorString, const String& typeString)
{
    auto type = Protocol::Helpers::parseEnumValueFromString<Protocol::Debugger::BreakpointAction::Type>(typeString);
    if (!type) {
        errorString = makeString("Unknown breakpoint action type: "_s, typeString);
        return std::nullopt;
    }

    switch (*type) {
    case Protocol::Debugger::BreakpointAction::Type::Log:
        return JSC::Breakpoint::Action::Type::Log;

    case Protocol::Debugger::BreakpointAction::Type::Evaluate:
        return JSC::Breakpoint::Action::Type::Evaluate;

    case Protocol::Debugger::BreakpointAction::Type::Sound:
        return JSC::Breakpoint::Action::Type::Sound;

    case Protocol::Debugger::BreakpointAction::Type::Probe:
        return JSC::Breakpoint::Action::Type::Probe;
    }

    ASSERT_NOT_REACHED();
    return std::nullopt;
}

template <typename T>
static T parseBreakpointOptions(Protocol::ErrorString& errorString, RefPtr<JSON::Object>&& options, Function<T(const String&, JSC::Breakpoint::ActionsVector&&, bool, size_t)> callback)
{
    String condition;
    JSC::Breakpoint::ActionsVector actions;
    bool autoContinue = false;
    size_t ignoreCount = 0;

    if (options) {
        condition = options->getString("condition"_s);

        auto actionsPayload = options->getArray("actions"_s);
        if (auto count = actionsPayload ? actionsPayload->length() : 0) {
            actions.reserveInitialCapacity(count);

            for (unsigned i = 0; i < count; ++i) {
                auto actionObject = actionsPayload->get(i)->asObject();
                if (!actionObject) {
                    errorString = "Unexpected non-object item in given actions"_s;
                    return { };
                }

                auto actionTypeString = actionObject->getString("type"_s);
                if (!actionTypeString) {
                    errorString = "Missing type for item in given actions"_s;
                    return { };
                }

                auto actionType = breakpointActionTypeForString(errorString, actionTypeString);
                if (!actionType)
                    return { };

                JSC::Breakpoint::Action action(*actionType);

                action.data = actionObject->getString("data"_s);

                // Specifying an identifier is optional. They are used to correlate probe samples
                // in the frontend across multiple backend probe actions and segregate object groups.
                action.id = actionObject->getInteger("id"_s).value_or(JSC::noBreakpointActionID);

                action.emulateUserGesture = actionObject->getBoolean("emulateUserGesture"_s).value_or(false);

                actions.append(WTFMove(action));
            }
        }

        autoContinue = options->getBoolean("autoContinue"_s).value_or(false);
        ignoreCount = options->getInteger("ignoreCount"_s).value_or(0);
    }

    return callback(condition, WTFMove(actions), autoContinue, ignoreCount);
}

std::optional<InspectorDebuggerAgent::ProtocolBreakpoint> InspectorDebuggerAgent::ProtocolBreakpoint::fromPayload(Protocol::ErrorString& errorString, JSC::SourceID sourceID, unsigned lineNumber, unsigned columnNumber, RefPtr<JSON::Object>&& options)
{
    return parseBreakpointOptions<std::optional<ProtocolBreakpoint>>(errorString, WTFMove(options), [&] (const String& condition, JSC::Breakpoint::ActionsVector&& actions, bool autoContinue, size_t ignoreCount) -> std::optional<ProtocolBreakpoint> {
        return ProtocolBreakpoint(sourceID, lineNumber, columnNumber, condition, WTFMove(actions), autoContinue, ignoreCount);
    });
}

std::optional<InspectorDebuggerAgent::ProtocolBreakpoint> InspectorDebuggerAgent::ProtocolBreakpoint::fromPayload(Protocol::ErrorString& errorString, const String& url, bool isRegex, unsigned lineNumber, unsigned columnNumber, RefPtr<JSON::Object>&& options)
{
    return parseBreakpointOptions<std::optional<ProtocolBreakpoint>>(errorString, WTFMove(options), [&] (const String& condition, JSC::Breakpoint::ActionsVector&& actions, bool autoContinue, size_t ignoreCount) -> std::optional<ProtocolBreakpoint> {
        return ProtocolBreakpoint(url, isRegex, lineNumber, columnNumber, condition, WTFMove(actions), autoContinue, ignoreCount);
    });
}

InspectorDebuggerAgent::ProtocolBreakpoint::ProtocolBreakpoint() = default;

InspectorDebuggerAgent::ProtocolBreakpoint::ProtocolBreakpoint(JSC::SourceID sourceID, unsigned lineNumber, unsigned columnNumber, const String& condition, JSC::Breakpoint::ActionsVector&& actions, bool autoContinue, size_t ignoreCount)
    : m_id(makeString(sourceID, ':', lineNumber, ':', columnNumber))
#if ASSERT_ENABLED
    , m_sourceID(sourceID)
#endif
    , m_lineNumber(lineNumber)
    , m_columnNumber(columnNumber)
    , m_condition(condition)
    , m_actions(WTFMove(actions))
    , m_autoContinue(autoContinue)
    , m_ignoreCount(ignoreCount)
{
}

InspectorDebuggerAgent::ProtocolBreakpoint::ProtocolBreakpoint(const String& url, bool isRegex, unsigned lineNumber, unsigned columnNumber, const String& condition, JSC::Breakpoint::ActionsVector&& actions, bool autoContinue, size_t ignoreCount)
    : m_id(makeString(isRegex ? "/"_s : ""_s, url, isRegex ? "/"_s : ""_s, ':', lineNumber, ':', columnNumber))
    , m_url(url)
    , m_isRegex(isRegex)
    , m_lineNumber(lineNumber)
    , m_columnNumber(columnNumber)
    , m_condition(condition)
    , m_actions(WTFMove(actions))
    , m_autoContinue(autoContinue)
    , m_ignoreCount(ignoreCount)
{
}

Ref<JSC::Breakpoint> InspectorDebuggerAgent::ProtocolBreakpoint::createDebuggerBreakpoint(JSC::BreakpointID debuggerBreakpointID, JSC::SourceID sourceID) const
{
    ASSERT(debuggerBreakpointID != JSC::noBreakpointID);
    ASSERT(sourceID != JSC::noSourceID);
    ASSERT(sourceID == m_sourceID || m_sourceID == JSC::noSourceID);

    auto debuggerBreakpoint = JSC::Breakpoint::create(debuggerBreakpointID, m_condition, copyToVector(m_actions), m_autoContinue, m_ignoreCount);
    debuggerBreakpoint->link(sourceID, m_lineNumber, m_columnNumber);
    return debuggerBreakpoint;
}

bool InspectorDebuggerAgent::ProtocolBreakpoint::matchesScriptURL(const String& scriptURL) const
{
    ASSERT(m_sourceID == JSC::noSourceID);

    if (m_isRegex) {
        JSC::Yarr::RegularExpression regex(m_url);
        return regex.match(scriptURL) != -1;
    }
    return m_url == scriptURL;
}

RefPtr<JSC::Breakpoint> InspectorDebuggerAgent::debuggerBreakpointFromPayload(Protocol::ErrorString& errorString, RefPtr<JSON::Object>&& options)
{
    return parseBreakpointOptions<RefPtr<JSC::Breakpoint>>(errorString, WTFMove(options), [] (const String& condition, JSC::Breakpoint::ActionsVector&& actions, bool autoContinue, size_t ignoreCount) {
        return JSC::Breakpoint::create(JSC::noBreakpointID, condition, WTFMove(actions), autoContinue, ignoreCount);
    });
}

InspectorDebuggerAgent::InspectorDebuggerAgent(AgentContext& context)
    : InspectorAgentBase("Debugger"_s)
    , m_frontendDispatcher(makeUnique<DebuggerFrontendDispatcher>(context.frontendRouter))
    , m_backendDispatcher(DebuggerBackendDispatcher::create(context.backendDispatcher, this))
    , m_debugger(*context.environment.debugger())
    , m_injectedScriptManager(context.injectedScriptManager)
{
    // FIXME: make pauseReason optional so that there was no need to init it with "other".
    clearPauseDetails();
}

InspectorDebuggerAgent::~InspectorDebuggerAgent() = default;

void InspectorDebuggerAgent::didCreateFrontendAndBackend(FrontendRouter*, BackendDispatcher*)
{
}

void InspectorDebuggerAgent::willDestroyFrontendAndBackend(DisconnectReason reason)
{
    if (enabled())
        internalDisable(reason == DisconnectReason::InspectedTargetDestroyed);
}

void InspectorDebuggerAgent::internalEnable()
{
    m_enabled = true;

    m_debugger.setClient(this);
    m_debugger.addObserver(*this);

    for (auto* listener : copyToVector(m_listeners))
        listener->debuggerWasEnabled();

    for (auto& [sourceID, script] : m_scripts)
        setBlackboxConfiguration(sourceID, script);
}

void InspectorDebuggerAgent::internalDisable(bool isBeingDestroyed)
{
    for (auto* listener : copyToVector(m_listeners))
        listener->debuggerWasDisabled();

    m_debugger.setClient(nullptr);
    m_debugger.removeObserver(*this, isBeingDestroyed);

    clearInspectorBreakpointState();

    if (!isBeingDestroyed)
        m_debugger.deactivateBreakpoints();

    clearAsyncStackTraceData();

    m_enabled = false;
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::enable()
{
    if (enabled())
        return makeUnexpected("Debugger domain already enabled"_s);

    internalEnable();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::disable()
{
    internalDisable(false);

    return { };
}

bool InspectorDebuggerAgent::breakpointsActive() const
{
    return m_debugger.breakpointsActive();
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setAsyncStackTraceDepth(int depth)
{
    if (m_asyncStackTraceDepth == depth)
        return { };

    if (depth < 0)
        return makeUnexpected("Unexpected negative depth"_s);

    m_asyncStackTraceDepth = depth;

    if (!m_asyncStackTraceDepth)
        clearAsyncStackTraceData();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setBreakpointsActive(bool active)
{
    if (active)
        m_debugger.activateBreakpoints();
    else
        m_debugger.deactivateBreakpoints();

    return { };
}

bool InspectorDebuggerAgent::isPaused() const
{
    return m_debugger.isPaused();
}

void InspectorDebuggerAgent::setSuppressAllPauses(bool suppress)
{
    m_debugger.setSuppressAllPauses(suppress);
}

void InspectorDebuggerAgent::updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason reason, RefPtr<JSON::Object>&& data)
{
    if (m_pauseReason != DebuggerFrontendDispatcher::Reason::BlackboxedScript) {
        m_preBlackboxPauseReason = m_pauseReason;
        m_preBlackboxPauseData = WTFMove(m_pauseData);
    }

    m_pauseReason = reason;
    m_pauseData = WTFMove(data);
}

static Ref<JSON::Object> buildAssertPauseReason(const String& message)
{
    auto reason = Protocol::Debugger::AssertPauseReason::create().release();
    if (!message.isNull())
        reason->setMessage(message);
    return *reason->asObject();
}

static Ref<JSON::Object> buildCSPViolationPauseReason(const String& directiveText)
{
    auto reason = Protocol::Debugger::CSPViolationPauseReason::create()
        .setDirective(directiveText)
        .release();
    return *reason->asObject();
}

RefPtr<JSON::Object> InspectorDebuggerAgent::buildBreakpointPauseReason(JSC::BreakpointID debuggerBreakpointID)
{
    ASSERT(debuggerBreakpointID != JSC::noBreakpointID);

    for (auto& [protocolBreakpointID, debuggerBreakpoints] : m_debuggerBreakpointsForProtocolBreakpointID) {
        for (auto& debuggerBreakpoint : debuggerBreakpoints) {
            if (debuggerBreakpoint->id() == debuggerBreakpointID) {
                auto reason = Protocol::Debugger::BreakpointPauseReason::create()
                    .setBreakpointId(protocolBreakpointID)
                    .release();
                return reason->asObject();
            }
        }
    }

    return nullptr;
}

RefPtr<JSON::Object> InspectorDebuggerAgent::buildExceptionPauseReason(JSC::JSValue exception, const InjectedScript& injectedScript)
{
    ASSERT(exception);
    if (!exception)
        return nullptr;

    ASSERT(!injectedScript.hasNoValue());
    if (injectedScript.hasNoValue())
        return nullptr;

    auto exceptionValue = injectedScript.wrapObject(exception, InspectorDebuggerAgent::backtraceObjectGroup);
    if (!exceptionValue)
        return nullptr;

    return exceptionValue->asObject();
}

void InspectorDebuggerAgent::handleConsoleAssert(const String& message)
{
    if (!breakpointsActive())
        return;

    if (!m_pauseOnAssertionsBreakpoint)
        return;

    breakProgram(DebuggerFrontendDispatcher::Reason::Assert, buildAssertPauseReason(message), m_pauseOnAssertionsBreakpoint.copyRef());
}

InspectorDebuggerAgent::AsyncCallIdentifier InspectorDebuggerAgent::asyncCallIdentifier(AsyncCallType asyncCallType, uint64_t callbackId)
{
    return std::make_pair(static_cast<unsigned>(asyncCallType), callbackId);
}

void InspectorDebuggerAgent::didScheduleAsyncCall(JSC::JSGlobalObject* globalObject, AsyncCallType asyncCallType, uint64_t callbackId, bool singleShot)
{
    if (!m_asyncStackTraceDepth)
        return;

    if (!breakpointsActive())
        return;

    Ref<ScriptCallStack> callStack = createScriptCallStack(globalObject, m_asyncStackTraceDepth);
    if (!callStack->size())
        return;

    auto identifier = asyncCallIdentifier(asyncCallType, callbackId);
    auto asyncStackTrace = AsyncStackTrace::create(WTFMove(callStack), singleShot, currentParentStackTrace());

    m_pendingAsyncCalls.set(identifier, WTFMove(asyncStackTrace));
}

void InspectorDebuggerAgent::didCancelAsyncCall(AsyncCallType asyncCallType, uint64_t callbackId)
{
    if (!m_asyncStackTraceDepth)
        return;

    auto identifier = asyncCallIdentifier(asyncCallType, callbackId);
    auto asyncStackTrace = m_pendingAsyncCalls.get(identifier);
    if (!asyncStackTrace)
        return;

    asyncStackTrace->didCancelAsyncCall();

    if (m_currentAsyncCallIdentifierStack.contains(identifier))
        return;

    m_pendingAsyncCalls.remove(identifier);
}

void InspectorDebuggerAgent::willDispatchAsyncCall(AsyncCallType asyncCallType, uint64_t callbackId)
{
    if (!m_asyncStackTraceDepth)
        return;

    // A call can be scheduled before the Inspector is opened, or while async stack
    // traces are disabled. If no call data exists, do nothing.
    auto identifier = asyncCallIdentifier(asyncCallType, callbackId);
    auto asyncStackTrace = m_pendingAsyncCalls.get(identifier);
    if (!asyncStackTrace)
        return;

    asyncStackTrace->willDispatchAsyncCall(m_asyncStackTraceDepth);

    m_currentAsyncCallIdentifierStack.append(WTFMove(identifier));
}

void InspectorDebuggerAgent::didDispatchAsyncCall(AsyncCallType asyncCallType, uint64_t callbackId)
{
    if (!m_asyncStackTraceDepth)
        return;

    auto identifier = asyncCallIdentifier(asyncCallType, callbackId);
    auto asyncStackTrace = m_pendingAsyncCalls.get(identifier);
    if (!asyncStackTrace)
        return;

    asyncStackTrace->didDispatchAsyncCall();

    m_currentAsyncCallIdentifierStack.removeLast(identifier);

    if (asyncStackTrace->isPending() || m_currentAsyncCallIdentifierStack.contains(identifier))
        return;

    m_pendingAsyncCalls.remove(identifier);
}

AsyncStackTrace* InspectorDebuggerAgent::currentParentStackTrace() const
{
    if (m_currentAsyncCallIdentifierStack.isEmpty())
        return nullptr;

    auto identifier = m_currentAsyncCallIdentifierStack.last();
    return m_pendingAsyncCalls.get(identifier);
}

static Ref<Protocol::Debugger::Location> buildDebuggerLocation(const JSC::Breakpoint& debuggerBreakpoint)
{
    ASSERT(debuggerBreakpoint.isResolved());

    auto location = Protocol::Debugger::Location::create()
        .setScriptId(String::number(debuggerBreakpoint.sourceID()))
        .setLineNumber(debuggerBreakpoint.lineNumber())
        .release();
    location->setColumnNumber(debuggerBreakpoint.columnNumber());
    return location;
}

static bool parseLocation(Protocol::ErrorString& errorString, const JSON::Object& location, JSC::SourceID& sourceID, unsigned& lineNumber, unsigned& columnNumber)
{
    auto lineNumberValue = location.getInteger("lineNumber"_s);
    if (!lineNumberValue) {
        errorString = "Unexpected non-integer lineNumber in given location"_s;
        sourceID = JSC::noSourceID;
        return false;
    }

    lineNumber = *lineNumberValue;

    auto scriptIDStr = location.getString("scriptId"_s);
    if (!scriptIDStr) {
        sourceID = JSC::noSourceID;
        errorString = "Unexepcted non-string scriptId in given location"_s;
        return false;
    }

    sourceID = parseIntegerAllowingTrailingJunk<JSC::SourceID>(scriptIDStr).value_or(0);
    columnNumber = location.getInteger("columnNumber"_s).value_or(0);
    return true;
}

Protocol::ErrorStringOr<std::tuple<Protocol::Debugger::BreakpointId, Ref<JSON::ArrayOf<Protocol::Debugger::Location>>>> InspectorDebuggerAgent::setBreakpointByUrl(int lineNumber, const String& url, const String& urlRegex, std::optional<int>&& columnNumber, RefPtr<JSON::Object>&& options)
{
    if (!url == !urlRegex)
        return makeUnexpected("Either url or urlRegex must be specified"_s);

    Protocol::ErrorString errorString;

    auto protocolBreakpoint = ProtocolBreakpoint::fromPayload(errorString, !!url ? url : urlRegex, !!urlRegex, lineNumber, columnNumber.value_or(0), WTFMove(options));
    if (!protocolBreakpoint)
        return makeUnexpected(errorString);

    if (m_protocolBreakpointForProtocolBreakpointID.contains(protocolBreakpoint->id()))
        return makeUnexpected("Breakpoint for given location already exists."_s);

    m_protocolBreakpointForProtocolBreakpointID.set(protocolBreakpoint->id(), *protocolBreakpoint);

    auto locations = JSON::ArrayOf<Protocol::Debugger::Location>::create();

    for (auto& [sourceID, script] : m_scripts) {
        String scriptURLForBreakpoints = !script.sourceURL.isEmpty() ? script.sourceURL : script.url;
        if (!protocolBreakpoint->matchesScriptURL(scriptURLForBreakpoints))
            continue;

        auto debuggerBreakpoint = protocolBreakpoint->createDebuggerBreakpoint(m_nextDebuggerBreakpointID++, sourceID);

        if (!resolveBreakpoint(script, debuggerBreakpoint))
            continue;

        if (!setBreakpoint(debuggerBreakpoint))
            continue;

        didSetBreakpoint(*protocolBreakpoint, debuggerBreakpoint);

        locations->addItem(buildDebuggerLocation(debuggerBreakpoint));
    }

    return { { protocolBreakpoint->id(), WTFMove(locations) } };
}

Protocol::ErrorStringOr<std::tuple<Protocol::Debugger::BreakpointId, Ref<Protocol::Debugger::Location>>> InspectorDebuggerAgent::setBreakpoint(Ref<JSON::Object>&& location, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    JSC::SourceID sourceID;
    unsigned lineNumber;
    unsigned columnNumber;
    if (!parseLocation(errorString, location, sourceID, lineNumber, columnNumber))
        return makeUnexpected(errorString);

    auto scriptIterator = m_scripts.find(sourceID);
    if (scriptIterator == m_scripts.end())
        return makeUnexpected("Missing script for scriptId in given location"_s);

    auto protocolBreakpoint = ProtocolBreakpoint::fromPayload(errorString, sourceID, lineNumber, columnNumber, WTFMove(options));
    if (!protocolBreakpoint)
        return makeUnexpected(errorString);

    // Don't save `protocolBreakpoint` in `m_protocolBreakpointForProtocolBreakpointID` because it
    // was set specifically for the given `sourceID`, which is unique, meaning that it will never
    // be used inside `InspectorDebuggerAgent::didParseSource`.

    auto debuggerBreakpoint = protocolBreakpoint->createDebuggerBreakpoint(m_nextDebuggerBreakpointID++, sourceID);

    if (!resolveBreakpoint(scriptIterator->value, debuggerBreakpoint))
        return makeUnexpected("Could not resolve breakpoint"_s);

    if (!setBreakpoint(debuggerBreakpoint))
        return makeUnexpected("Breakpoint for given location already exists"_s);

    didSetBreakpoint(*protocolBreakpoint, debuggerBreakpoint);

    return { { protocolBreakpoint->id(), buildDebuggerLocation(debuggerBreakpoint) } };
}

void InspectorDebuggerAgent::didSetBreakpoint(ProtocolBreakpoint& protocolBreakpoint, JSC::Breakpoint& debuggerBreakpoint)
{
    auto& debuggerBreakpoints = m_debuggerBreakpointsForProtocolBreakpointID.ensure(protocolBreakpoint.id(), [] {
        return JSC::BreakpointsVector();
    }).iterator->value;

    debuggerBreakpoints.append(debuggerBreakpoint);
}

bool InspectorDebuggerAgent::resolveBreakpoint(const JSC::Debugger::Script& script, JSC::Breakpoint& debuggerBreakpoint)
{
    if (debuggerBreakpoint.lineNumber() < static_cast<unsigned>(script.startLine) || static_cast<unsigned>(script.endLine) < debuggerBreakpoint.lineNumber())
        return false;

    return m_debugger.resolveBreakpoint(debuggerBreakpoint, script.sourceProvider.get());
}

bool InspectorDebuggerAgent::setBreakpoint(JSC::Breakpoint& debuggerBreakpoint)
{
    JSC::JSLockHolder locker(m_debugger.vm());
    return m_debugger.setBreakpoint(debuggerBreakpoint);
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::removeBreakpoint(const Protocol::Debugger::BreakpointId& protocolBreakpointID)
{
    m_protocolBreakpointForProtocolBreakpointID.remove(protocolBreakpointID);

    for (auto& debuggerBreakpoint : m_debuggerBreakpointsForProtocolBreakpointID.take(protocolBreakpointID)) {
        for (const auto& action : debuggerBreakpoint->actions())
            m_injectedScriptManager.releaseObjectGroup(objectGroupForBreakpointAction(action.id));

        JSC::JSLockHolder locker(m_debugger.vm());
        m_debugger.removeBreakpoint(debuggerBreakpoint);
    }

    return { };
}

static String functionName(JSC::NativeExecutable& nativeExecutable)
{
    return nativeExecutable.name();
}

static String functionName(JSC::FunctionExecutable& functionExecutable)
{
    return functionExecutable.ecmaName().string();
}

static String functionName(JSC::CodeBlock& codeBlock)
{
    if (auto* functionExecutable = JSC::jsDynamicCast<JSC::FunctionExecutable*>(codeBlock.ownerExecutable()))
        return functionName(*functionExecutable);

    return nullString();
}

static String functionName(JSC::CallFrame* callFrame)
{
    if (callFrame->isNativeCalleeFrame())
        return nullString();

    if (auto* codeBlock = callFrame->codeBlock())
        return functionName(*codeBlock);

    if (auto* jsFunction = JSC::jsDynamicCast<JSC::JSFunction*>(callFrame->jsCallee())) {
        if (auto* nativeExecutable = JSC::jsDynamicCast<JSC::NativeExecutable*>(jsFunction->executable()))
            return functionName(*nativeExecutable);
    }

    return nullString();
}

#if ENABLE(JIT)

struct ReplacedThunk {
    ~ReplacedThunk()
    {
        if (!nativeExecutable)
            return;

        auto restoreThunks = [&] (JSC::CodeSpecializationKind kind) {
            RELEASE_ASSERT(nativeExecutable->hasJITCodeFor(kind));

            auto jitCode = nativeExecutable->generatedJITCodeFor(kind);
            if (!jitCode->canSwapCodeRefForDebugger())
                return;

            JSC::JITCode::CodeRef<JSC::JSEntryPtrTag> oldJITCodeRef;
            CodePtr<JSC::JSEntryPtrTag> oldArityJITCodeRef;
            switch (kind) {
            case JSC::CodeForCall:
                oldJITCodeRef = WTFMove(callThunk);
                oldArityJITCodeRef = WTFMove(callArityThunk);
                break;

            case JSC::CodeForConstruct:
                oldJITCodeRef = WTFMove(constructThunk);
                oldArityJITCodeRef = WTFMove(constructArityThunk);
                break;
            }

            jitCode->swapCodeRefForDebugger(WTFMove(oldJITCodeRef));
            nativeExecutable->swapGeneratedJITCodeWithArityCheckForDebugger(kind, oldArityJITCodeRef);
        };

        restoreThunks(JSC::CodeForCall);
        restoreThunks(JSC::CodeForConstruct);
    }

    JSC::Weak<JSC::NativeExecutable> nativeExecutable;

    JSC::JITCode::CodeRef<JSC::JSEntryPtrTag> callThunk;
    CodePtr<JSC::JSEntryPtrTag> callArityThunk;

    JSC::JITCode::CodeRef<JSC::JSEntryPtrTag> constructThunk;
    CodePtr<JSC::JSEntryPtrTag> constructArityThunk;

    size_t matchCount { 0 };

    friend inline bool operator==(const Box<ReplacedThunk>& a, const Box<ReplacedThunk>& b)
    {
        return a && b && a->nativeExecutable.get() == b->nativeExecutable.get();
    }

    friend inline bool operator==(const Box<ReplacedThunk>& a, const JSC::NativeExecutable* b)
    {
        return a && a->nativeExecutable.get() == b;
    }
};

static Lock s_replacedThunksLock;
static Vector<Box<ReplacedThunk>>& replacedThunks() WTF_REQUIRES_LOCK(s_replacedThunksLock)
{
    ASSERT(s_replacedThunksLock.isHeld());
    static NeverDestroyed<Vector<Box<ReplacedThunk>>> replacedThunks;
    return replacedThunks;
}

#endif // ENABLE(JIT)

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::addSymbolicBreakpoint(const String& symbol, std::optional<bool>&& caseSensitive, std::optional<bool>&& isRegex, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    auto breakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
    if (!breakpoint)
        return makeUnexpected(errorString);

    {
        SymbolicBreakpoint symbolicBreakpoint;
        symbolicBreakpoint.symbol = symbol;
        if (caseSensitive)
            symbolicBreakpoint.caseSensitive = *caseSensitive;
        if (isRegex)
            symbolicBreakpoint.isRegex = *isRegex;
        symbolicBreakpoint.specialBreakpoint = WTFMove(breakpoint);

        if (!m_symbolicBreakpoints.appendIfNotContains(WTFMove(symbolicBreakpoint)))
            return makeUnexpected("Symbolic breakpoint for given symbol, given caseSensitive, and given isRegex already exists"_s);
    }

    auto& symbolicBreakpoint = m_symbolicBreakpoints.last();

    {
        JSC::JSLockHolder locker(m_debugger.vm());

        m_debugger.forEachRegisteredCodeBlock([&] (JSC::CodeBlock* codeBlock) {
            if (symbolicBreakpoint.matches(functionName(*codeBlock)))
                codeBlock->addBreakpoint(1);
        });
    }

#if ENABLE(JIT)
    {
        JSC::DeferGCForAWhile deferGC(m_debugger.vm());
        m_debugger.vm().notifyDebuggerHookInjected();

        Vector<JSC::NativeExecutable*> newNativeExecutables;
        {
            Locker locker { s_replacedThunksLock };
            auto& existingReplacedThunks = replacedThunks();

            JSC::HeapIterationScope iterationScope(m_debugger.vm().heap);
            m_debugger.vm().heap.objectSpace().forEachLiveCell(iterationScope, [&] (JSC::HeapCell* cell, JSC::HeapCell::Kind kind) {
                if (isJSCellKind(kind)) {
                    if (auto* nativeExecutable = JSC::jsDynamicCast<JSC::NativeExecutable*>(static_cast<JSC::JSCell*>(cell))) {
                        if (auto existingIndex = existingReplacedThunks.find(nativeExecutable); existingIndex != notFound)
                            ++existingReplacedThunks[existingIndex]->matchCount;
                        else
                            newNativeExecutables.append(nativeExecutable);
                    }
                }

                return IterationStatus::Continue;
            });
        }
        for (auto* nativeExecutable : WTFMove(newNativeExecutables))
            didCreateNativeExecutable(*nativeExecutable);
    }
#endif

    // FIXME: <https://webkit.org/b/243994> Web Inspector: Debugger: symbolic breakpoints should work with intrinsic functions
    // FIXME: <https://webkit.org/b/243717> Web Inspector: Debugger: symbolic breakpoints should work when functions change their `name`

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::removeSymbolicBreakpoint(const String& symbol, std::optional<bool>&& caseSensitive, std::optional<bool>&& isRegex)
{
    SymbolicBreakpoint symbolicBreakpoint;
    symbolicBreakpoint.symbol = symbol;
    if (caseSensitive)
        symbolicBreakpoint.caseSensitive = *caseSensitive;
    if (isRegex)
        symbolicBreakpoint.isRegex = *isRegex;

    if (!m_symbolicBreakpoints.removeAll(symbolicBreakpoint))
        return makeUnexpected("Missing symbolic breakpoint for given symbol, given caseSensitive, and given isRegex"_s);

    {
        JSC::JSLockHolder locker(m_debugger.vm());

        m_debugger.forEachRegisteredCodeBlock([&] (JSC::CodeBlock* codeBlock) {
            if (symbolicBreakpoint.matches(functionName(*codeBlock)))
                codeBlock->removeBreakpoint(1);
        });
    }

#if ENABLE(JIT)
    {
        Locker locker { s_replacedThunksLock };

        replacedThunks().removeAllMatching([&] (auto& replacedThunk) {
            if (!replacedThunk->nativeExecutable)
                return true;

            if (&replacedThunk->nativeExecutable->vm() != &m_debugger.vm())
                return false;

            if (symbolicBreakpoint.matches(functionName(*replacedThunk->nativeExecutable))) {
                ASSERT(replacedThunk->matchCount);
                if (!--replacedThunk->matchCount)
                    return true;
            }

            return false;
        });
    }
#endif

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::continueUntilNextRunLoop()
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    auto resumeResult = resume();
    if (!resumeResult)
        return makeUnexpected(resumeResult.error());

    m_enablePauseWhenIdle = true;

    registerIdleHandler();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::continueToLocation(Ref<JSON::Object>&& location)
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    if (m_continueToLocationDebuggerBreakpoint) {
        m_debugger.removeBreakpoint(*m_continueToLocationDebuggerBreakpoint);
        m_continueToLocationDebuggerBreakpoint = nullptr;
    }

    JSC::SourceID sourceID;
    unsigned lineNumber;
    unsigned columnNumber;
    if (!parseLocation(errorString, location, sourceID, lineNumber, columnNumber))
        return makeUnexpected(errorString);

    auto scriptIterator = m_scripts.find(sourceID);
    if (scriptIterator == m_scripts.end()) {
        m_debugger.continueProgram();
        m_frontendDispatcher->resumed();
        return makeUnexpected("Missing script for scriptId in given location"_s);
    }

    auto protocolBreakpoint = ProtocolBreakpoint::fromPayload(errorString, sourceID, lineNumber, columnNumber);
    if (!protocolBreakpoint)
        return makeUnexpected(errorString);

    // Don't save `protocolBreakpoint` in `m_protocolBreakpointForProtocolBreakpointID` because it
    // is a temporary breakpoint that will be removed as soon as `location` is reached.

    auto debuggerBreakpoint = protocolBreakpoint->createDebuggerBreakpoint(m_nextDebuggerBreakpointID++, sourceID);

    if (!resolveBreakpoint(scriptIterator->value, debuggerBreakpoint)) {
        m_debugger.continueProgram();
        m_frontendDispatcher->resumed();
        return makeUnexpected("Could not resolve breakpoint"_s);
    }

    if (!setBreakpoint(debuggerBreakpoint)) {
        // There is an existing breakpoint at this location. Instead of
        // acting like a series of steps, just resume and we will either
        // hit this new breakpoint or not.
        m_debugger.continueProgram();
        m_frontendDispatcher->resumed();
        return { };
    }

    m_continueToLocationDebuggerBreakpoint = WTFMove(debuggerBreakpoint);

    // Treat this as a series of steps until reaching the new breakpoint.
    // So don't issue a resumed event unless we exit the VM without pausing.
    willStepAndMayBecomeIdle();
    m_debugger.continueProgram();

    return { };
}

Protocol::ErrorStringOr<Ref<JSON::ArrayOf<Protocol::GenericTypes::SearchMatch>>> InspectorDebuggerAgent::searchInContent(const Protocol::Debugger::ScriptId& scriptId, const String& query, std::optional<bool>&& caseSensitive, std::optional<bool>&& isRegex)
{
    auto it = m_scripts.find(parseIntegerAllowingTrailingJunk<JSC::SourceID>(scriptId).value_or(0));
    if (it == m_scripts.end())
        return makeUnexpected("Missing script for given scriptId"_s);

    return ContentSearchUtilities::searchInTextByLines(it->value.source, query, caseSensitive.value_or(false), isRegex.value_or(false));
}

Protocol::ErrorStringOr<String> InspectorDebuggerAgent::getScriptSource(const Protocol::Debugger::ScriptId& scriptId)
{
    auto it = m_scripts.find(parseIntegerAllowingTrailingJunk<JSC::SourceID>(scriptId).value_or(0));
    if (it == m_scripts.end())
        return makeUnexpected("Missing script for given scriptId"_s);

    return it->value.source;
}

Protocol::ErrorStringOr<Ref<Protocol::Debugger::FunctionDetails>> InspectorDebuggerAgent::getFunctionDetails(const String& functionId)
{
    Protocol::ErrorString errorString;

    InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(functionId);
    if (injectedScript.hasNoValue())
        return makeUnexpected("Missing injected script for given functionId"_s);

    RefPtr<Protocol::Debugger::FunctionDetails> details;
    injectedScript.getFunctionDetails(errorString, functionId, details);
    if (!details)
        return makeUnexpected(errorString);

    return details.releaseNonNull();
}

Protocol::ErrorStringOr<Ref<JSON::ArrayOf<Protocol::Debugger::Location>>> InspectorDebuggerAgent::getBreakpointLocations(Ref<JSON::Object>&& start, Ref<JSON::Object>&& end)
{
    Protocol::ErrorString errorString;

    JSC::SourceID startSourceID;
    unsigned startLineNumber;
    unsigned startColumnNumber;
    if (!parseLocation(errorString, WTFMove(start), startSourceID, startLineNumber, startColumnNumber))
        return makeUnexpected(errorString);

    JSC::SourceID endSourceID;
    unsigned endLineNumber;
    unsigned endColumnNumber;
    if (!parseLocation(errorString, WTFMove(end), endSourceID, endLineNumber, endColumnNumber))
        return makeUnexpected(errorString);

    if (startSourceID != endSourceID)
        return makeUnexpected("Must have same scriptId for given start and given end"_s);

    if (endLineNumber < startLineNumber)
        return makeUnexpected("Cannot have lineNumber of given end be before lineNumber of given start"_s);

    if (startLineNumber == endLineNumber && endColumnNumber < startColumnNumber)
        return makeUnexpected("Cannot have columnNumber of given end be before columnNumber of given start"_s);

    auto scriptIterator = m_scripts.find(startSourceID);
    if (scriptIterator == m_scripts.end())
        return makeUnexpected("Missing script for scriptId in given start"_s);

    auto protocolLocations = JSON::ArrayOf<Protocol::Debugger::Location>::create();
    m_debugger.forEachBreakpointLocation(startSourceID, scriptIterator->value.sourceProvider.get(), startLineNumber, startColumnNumber, endLineNumber, endColumnNumber, [&] (int lineNumber, int columnNumber) {
        auto protocolLocation = Protocol::Debugger::Location::create()
            .setScriptId(String::number(startSourceID))
            .setLineNumber(lineNumber)
            .release();
        protocolLocation->setColumnNumber(columnNumber);
        protocolLocations->addItem(WTFMove(protocolLocation));
    });
    return protocolLocations;
}

void InspectorDebuggerAgent::schedulePauseAtNextOpportunity(DebuggerFrontendDispatcher::Reason reason, RefPtr<JSON::Object>&& data)
{
    if (m_javaScriptPauseScheduled)
        return;

    m_javaScriptPauseScheduled = true;

    updatePauseReasonAndData(reason, WTFMove(data));

    JSC::JSLockHolder locker(m_debugger.vm());
    m_debugger.schedulePauseAtNextOpportunity();
}

void InspectorDebuggerAgent::cancelPauseAtNextOpportunity()
{
    if (!m_javaScriptPauseScheduled)
        return;

    m_javaScriptPauseScheduled = false;

    clearPauseDetails();
    m_debugger.cancelPauseAtNextOpportunity();
    m_enablePauseWhenIdle = false;
}

bool InspectorDebuggerAgent::schedulePauseForSpecialBreakpoint(JSC::Breakpoint& breakpoint, DebuggerFrontendDispatcher::Reason reason, RefPtr<JSON::Object>&& data)
{
    JSC::JSLockHolder locker(m_debugger.vm());

    if (!m_debugger.schedulePauseForSpecialBreakpoint(breakpoint))
        return false;

    updatePauseReasonAndData(reason, WTFMove(data));
    return true;
}

bool InspectorDebuggerAgent::cancelPauseForSpecialBreakpoint(JSC::Breakpoint& breakpoint)
{
    if (!m_debugger.cancelPauseForSpecialBreakpoint(breakpoint))
        return false;

    clearPauseDetails();
    return true;
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::pause()
{
    schedulePauseAtNextOpportunity(DebuggerFrontendDispatcher::Reason::PauseOnNextStatement);

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::resume()
{
    if (!m_pausedGlobalObject && !m_javaScriptPauseScheduled)
        return makeUnexpected("Must be paused or waiting to pause"_s);

    cancelPauseAtNextOpportunity();
    m_debugger.continueProgram();
    m_conditionToDispatchResumed = ShouldDispatchResumed::WhenContinued;

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::stepNext()
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    willStepAndMayBecomeIdle();
    m_debugger.stepNextExpression();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::stepOver()
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    willStepAndMayBecomeIdle();
    m_debugger.stepOverStatement();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::stepInto()
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    willStepAndMayBecomeIdle();
    m_debugger.stepIntoStatement();

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::stepOut()
{
    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    willStepAndMayBecomeIdle();
    m_debugger.stepOutOfFunction();

    return { };
}

void InspectorDebuggerAgent::registerIdleHandler()
{
    if (!m_registeredIdleCallback) {
        m_registeredIdleCallback = true;
        JSC::VM& vm = m_debugger.vm();
        vm.whenIdle([this]() {
            didBecomeIdle();
        });
    }
}

void InspectorDebuggerAgent::willStepAndMayBecomeIdle()
{
    // When stepping the backend must eventually trigger a "paused" or "resumed" event.
    // If the step causes us to exit the VM, then we should issue "resumed".
    m_conditionToDispatchResumed = ShouldDispatchResumed::WhenIdle;

    registerIdleHandler();
}

void InspectorDebuggerAgent::didBecomeIdle()
{
    m_registeredIdleCallback = false;

    if (m_conditionToDispatchResumed == ShouldDispatchResumed::WhenIdle) {
        cancelPauseAtNextOpportunity();
        m_debugger.continueProgram();
        m_frontendDispatcher->resumed();
    }

    m_conditionToDispatchResumed = ShouldDispatchResumed::No;

    if (m_enablePauseWhenIdle)
        pause();
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setPauseOnDebuggerStatements(bool enabled, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    if (!enabled) {
        m_debugger.setPauseOnDebuggerStatementsBreakpoint(nullptr);
        return { };
    }

    auto breakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
    if (!breakpoint)
        return makeUnexpected(errorString);

    m_debugger.setPauseOnDebuggerStatementsBreakpoint(WTFMove(breakpoint));

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setPauseOnExceptions(const String& stateString, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    RefPtr<JSC::Breakpoint> allExceptionsBreakpoint;
    RefPtr<JSC::Breakpoint> uncaughtExceptionsBreakpoint;

    if (stateString == "all"_s) {
        allExceptionsBreakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
        if (!allExceptionsBreakpoint)
            return makeUnexpected(errorString);
    } else if (stateString == "uncaught"_s) {
        uncaughtExceptionsBreakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
        if (!uncaughtExceptionsBreakpoint)
            return makeUnexpected(errorString);
    } else if (stateString != "none"_s)
        return makeUnexpected(makeString("Unknown state: "_s, stateString));

    m_debugger.setPauseOnAllExceptionsBreakpoint(WTFMove(allExceptionsBreakpoint));
    m_debugger.setPauseOnUncaughtExceptionsBreakpoint(WTFMove(uncaughtExceptionsBreakpoint));

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setPauseOnAssertions(bool enabled, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    if (!enabled) {
        m_pauseOnAssertionsBreakpoint = nullptr;
        return { };
    }

    auto breakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
    if (!breakpoint)
        return makeUnexpected(errorString);

    m_pauseOnAssertionsBreakpoint = WTFMove(breakpoint);

    return { };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setPauseOnMicrotasks(bool enabled, RefPtr<JSON::Object>&& options)
{
    Protocol::ErrorString errorString;

    if (!enabled) {
        m_pauseOnMicrotasksBreakpoint = nullptr;
        return { };
    }

    auto breakpoint = debuggerBreakpointFromPayload(errorString, WTFMove(options));
    if (!breakpoint)
        return makeUnexpected(errorString);

    m_pauseOnMicrotasksBreakpoint = WTFMove(breakpoint);

    return { };
}

Protocol::ErrorStringOr<std::tuple<Ref<Protocol::Runtime::RemoteObject>, std::optional<bool> /* wasThrown */, std::optional<int> /* savedResultIndex */>> InspectorDebuggerAgent::evaluateOnCallFrame(const Protocol::Debugger::CallFrameId& callFrameId, const String& expression, const String& objectGroup, std::optional<bool>&& includeCommandLineAPI, std::optional<bool>&& doNotPauseOnExceptionsAndMuteConsole, std::optional<bool>&& returnByValue, std::optional<bool>&& generatePreview, std::optional<bool>&& saveResult, std::optional<bool>&& emulateUserGesture)
{
    InjectedScript injectedScript = m_injectedScriptManager.injectedScriptForObjectId(callFrameId);
    if (injectedScript.hasNoValue())
        return makeUnexpected("Missing injected script for given callFrameId"_s);

    return evaluateOnCallFrame(injectedScript, callFrameId, expression, objectGroup, WTFMove(includeCommandLineAPI), WTFMove(doNotPauseOnExceptionsAndMuteConsole), WTFMove(returnByValue), WTFMove(generatePreview), WTFMove(saveResult), WTFMove(emulateUserGesture));
}

Protocol::ErrorStringOr<std::tuple<Ref<Protocol::Runtime::RemoteObject>, std::optional<bool> /* wasThrown */, std::optional<int> /* savedResultIndex */>> InspectorDebuggerAgent::evaluateOnCallFrame(InjectedScript& injectedScript, const Protocol::Debugger::CallFrameId& callFrameId, const String& expression, const String& objectGroup, std::optional<bool>&& includeCommandLineAPI, std::optional<bool>&& doNotPauseOnExceptionsAndMuteConsole, std::optional<bool>&& returnByValue, std::optional<bool>&& generatePreview, std::optional<bool>&& saveResult, std::optional<bool>&& /* emulateUserGesture */)
{
    ASSERT(!injectedScript.hasNoValue());

    Protocol::ErrorString errorString;

    if (!assertPaused(errorString))
        return makeUnexpected(errorString);

    JSC::Debugger::TemporarilyDisableExceptionBreakpoints temporarilyDisableExceptionBreakpoints(m_debugger);

    bool pauseAndMute = doNotPauseOnExceptionsAndMuteConsole && *doNotPauseOnExceptionsAndMuteConsole;
    if (pauseAndMute) {
        temporarilyDisableExceptionBreakpoints.replace();
        muteConsole();
    }

    RefPtr<Protocol::Runtime::RemoteObject> result;
    std::optional<bool> wasThrown;
    std::optional<int> savedResultIndex;

    injectedScript.evaluateOnCallFrame(errorString, m_currentCallStack.get(), callFrameId, expression, objectGroup, includeCommandLineAPI.value_or(false), returnByValue.value_or(false), generatePreview.value_or(false), saveResult.value_or(false), result, wasThrown, savedResultIndex);

    if (pauseAndMute)
        unmuteConsole();

    if (!result)
        return makeUnexpected(errorString);

    return { { result.releaseNonNull(), WTFMove(wasThrown), WTFMove(savedResultIndex) } };
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setShouldBlackboxURL(const String& url, bool shouldBlackbox, std::optional<bool>&& optionalCaseSensitive, std::optional<bool>&& optionalIsRegex, RefPtr<JSON::Array>&& protocolSourceRanges)
{
    if (url.isEmpty())
        return makeUnexpected("URL must not be empty"_s);

    bool caseSensitive = optionalCaseSensitive.value_or(false);
    bool isRegex = optionalIsRegex.value_or(false);

    if (!caseSensitive && !isRegex && isWebKitInjectedScript(url))
        return makeUnexpected("Blackboxing of internal scripts is controlled by 'Debugger.setPauseForInternalScripts'"_s);

    if (shouldBlackbox) {
        UncheckedKeyHashSet<JSC::Debugger::BlackboxRange> blackboxRanges;
        if (protocolSourceRanges) {
            if (protocolSourceRanges->length() % 4)
                return makeUnexpected("Unexpected format for given sourceRanges"_s);

            int startLine = -1;
            int startColumn = -1;
            int endLine = -1;
            for (auto&& value : WTFMove(*protocolSourceRanges)) {
                auto integer = value->asInteger();
                if (!integer)
                    return makeUnexpected("Unexpected non-integer item in given sourceRanges"_s);
                if (*integer < 0)
                    return makeUnexpected("Unexpected negative item in given sourceRanges"_s);

                if (startLine == -1) {
                    startLine = *integer;
                    continue;
                }
                if (startColumn == -1) {
                    startColumn = *integer;
                    continue;
                }
                if (endLine == -1) {
                    endLine = *integer;
                    continue;
                }
                int endColumn = *integer;

                if (startLine > endLine)
                    return makeUnexpected("Unexpected endLine before startLine in given sourceRanges"_s);

                if (startLine == endLine && startColumn >= endColumn)
                    return makeUnexpected("Unexpected endColumn before startColumn in given sourceRanges"_s);

                blackboxRanges.add({
                    { OrdinalNumber::fromZeroBasedInt(startLine), OrdinalNumber::fromZeroBasedInt(startColumn) },
                    { OrdinalNumber::fromZeroBasedInt(endLine), OrdinalNumber::fromZeroBasedInt(endColumn) },
                });

                startLine = -1;
                startColumn = -1;
                endLine = -1;
            }
            ASSERT(startLine == -1);
            ASSERT(startColumn == -1);
            ASSERT(endLine == -1);
        }
        m_blackboxedURLs.set({ url, caseSensitive, isRegex }, WTFMove(blackboxRanges));
    } else
        m_blackboxedURLs.remove({ url, caseSensitive, isRegex });

    for (auto& [sourceID, script] : m_scripts) {
        if (isWebKitInjectedScript(script.sourceURL))
            continue;

        setBlackboxConfiguration(sourceID, script);
    }

    return { };
}

void InspectorDebuggerAgent::setBlackboxConfiguration(JSC::SourceID sourceID, const JSC::Debugger::Script& script)
{
    JSC::Debugger::BlackboxConfiguration blackboxConfiguration;

    if (!m_pauseForInternalScripts && isWebKitInjectedScript(script.sourceURL)) {
        auto& blackboxFlags = blackboxConfiguration.ensure(blackboxRange(script), [] {
            return JSC::Debugger::BlackboxFlags();
        }).iterator->value;
        blackboxFlags.add(JSC::Debugger::BlackboxFlag::Ignore);
    }

    for (const auto& [blackboxParameters, blackboxRanges] : m_blackboxedURLs) {
        const auto& [url, caseSensitive, isRegex] = blackboxParameters;

        auto searchStringType = isRegex ? ContentSearchUtilities::SearchStringType::Regex : ContentSearchUtilities::SearchStringType::ExactString;
        auto regex = ContentSearchUtilities::createRegularExpressionForSearchString(url, caseSensitive, searchStringType);
        if ((script.sourceURL.isEmpty() || regex.match(script.sourceURL) == -1) && (script.url.isEmpty() || regex.match(script.url) == -1))
            continue;

        if (blackboxRanges.isEmpty()) {
            auto& blackboxFlags = blackboxConfiguration.ensure(blackboxRange(script), [] {
                return JSC::Debugger::BlackboxFlags();
            }).iterator->value;
            blackboxFlags.add(JSC::Debugger::BlackboxFlag::Defer);
            continue;
        }

        for (const auto& blackboxRange : blackboxRanges) {
            auto& blackboxFlags = blackboxConfiguration.ensure(blackboxRange, [] {
                return JSC::Debugger::BlackboxFlags();
            }).iterator->value;
            blackboxFlags.add(JSC::Debugger::BlackboxFlag::Defer);
        }
    }

    m_debugger.setBlackboxConfiguration(sourceID, WTFMove(blackboxConfiguration));
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setBlackboxBreakpointEvaluations(bool blackboxBreakpointEvaluations)
{
    m_debugger.setBlackboxBreakpointEvaluations(blackboxBreakpointEvaluations);

    return { };
}

void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText)
{
    if (m_debugger.needsExceptionCallbacks())
        breakProgram(DebuggerFrontendDispatcher::Reason::CSPViolation, buildCSPViolationPauseReason(directiveText));
}

Ref<JSON::ArrayOf<Protocol::Debugger::CallFrame>> InspectorDebuggerAgent::currentCallFrames(const InjectedScript& injectedScript)
{
    ASSERT(!injectedScript.hasNoValue());
    if (injectedScript.hasNoValue())
        return JSON::ArrayOf<Protocol::Debugger::CallFrame>::create();

    return injectedScript.wrapCallFrames(m_currentCallStack.get());
}

String InspectorDebuggerAgent::sourceMapURLForScript(const JSC::Debugger::Script& script)
{
    return script.sourceMappingURL;
}

Protocol::ErrorStringOr<void> InspectorDebuggerAgent::setPauseForInternalScripts(bool shouldPause)
{
    if (shouldPause == m_pauseForInternalScripts)
        return { };

    m_pauseForInternalScripts = shouldPause;

    for (auto& [sourceID, script] : m_scripts) {
        if (!isWebKitInjectedScript(script.sourceURL))
            continue;

        setBlackboxConfiguration(sourceID, script);
    }

    return { };
}

void InspectorDebuggerAgent::didCreateNativeExecutable(JSC::NativeExecutable& nativeExecutable)
{
#if ENABLE(JIT)
    auto& vm = m_debugger.vm();
    ASSERT(&nativeExecutable.vm() == &vm);

    if (!JSC::Options::useJIT())
        return;

    if (m_symbolicBreakpoints.isEmpty())
        return;

    JSC::JSLockHolder apiLocker(vm);
    auto symbol = functionName(nativeExecutable);
    if (symbol.isEmpty())
        return;

    size_t matchCount = 0;
    for (auto& symbolicBreakpoint : m_symbolicBreakpoints) {
        if (symbolicBreakpoint.matches(symbol))
            ++matchCount;
    }
    if (!matchCount)
        return;

    Locker locker { s_replacedThunksLock };

    auto existingIndex = replacedThunks().find(&nativeExecutable);
    if (existingIndex != notFound) {
        replacedThunks()[existingIndex]->matchCount += matchCount;
        return;
    }

    auto replacedThunk = Box<ReplacedThunk>::create();
    replacedThunk->nativeExecutable = &nativeExecutable;
    replacedThunk->matchCount = matchCount;

    auto createJITCodeRef = [&] (CodePtr<JSC::JITThunkPtrTag> thunk) {
        return JSC::JITCode::CodeRef<JSC::JSEntryPtrTag>::createSelfManagedCodeRef(thunk.retagged<JSC::JSEntryPtrTag>());
    };

    auto replaceThunks = [&] (JSC::CodeSpecializationKind kind) {
        RELEASE_ASSERT(nativeExecutable.hasJITCodeFor(kind));

        auto jitCode = nativeExecutable.generatedJITCodeFor(kind);
        if (!jitCode->canSwapCodeRefForDebugger())
            return false;

        CodePtr<JSC::JITThunkPtrTag> thunk;
        switch (kind) {
        case JSC::CodeForCall:
            thunk = vm.jitStubs->ctiNativeCallWithDebuggerHook(vm);
            break;

        case JSC::CodeForConstruct:
            thunk = vm.jitStubs->ctiNativeConstructWithDebuggerHook(vm);
            break;
        }

        RELEASE_ASSERT(nativeExecutable.generatedJITCodeWithArityCheckFor(kind) == jitCode->addressForCall(JSC::MustCheckArity));

        auto oldJITCodeRef = jitCode->swapCodeRefForDebugger(createJITCodeRef(thunk));
        auto oldArityJITCodeRef = nativeExecutable.swapGeneratedJITCodeWithArityCheckForDebugger(kind, jitCode->addressForCall(JSC::MustCheckArity));

        switch (kind) {
        case JSC::CodeForCall:
            ASSERT(!replacedThunk->callThunk);
            replacedThunk->callThunk = WTFMove(oldJITCodeRef);

            ASSERT(!replacedThunk->callArityThunk);
            replacedThunk->callArityThunk = WTFMove(oldArityJITCodeRef);

            RELEASE_ASSERT(replacedThunk->callThunk.code() == createJITCodeRef(vm.jitStubs->ctiNativeCall(vm)).code());
            break;

        case JSC::CodeForConstruct:
            ASSERT(!replacedThunk->constructThunk);
            replacedThunk->constructThunk = WTFMove(oldJITCodeRef);

            ASSERT(!replacedThunk->constructArityThunk);
            replacedThunk->constructArityThunk = WTFMove(oldArityJITCodeRef);

            RELEASE_ASSERT(replacedThunk->constructThunk.code() == createJITCodeRef(vm.jitStubs->ctiNativeConstruct(vm)).code());
            break;
        }

        return true;
    };

    bool didReplaceCallThunks = replaceThunks(JSC::CodeForCall);
    bool didReplaceConstructThunks = replaceThunks(JSC::CodeForConstruct);
    if (!didReplaceCallThunks && !didReplaceConstructThunks)
        return;

    replacedThunks().append(WTFMove(replacedThunk));
#else
    UNUSED_PARAM(nativeExecutable);
#endif
}

void InspectorDebuggerAgent::willCallNativeExecutable(JSC::CallFrame* callFrame)
{
    if (!breakpointsActive())
        return;

    if (m_symbolicBreakpoints.isEmpty())
        return;

    auto symbol = functionName(callFrame);
    if (symbol.isEmpty())
        return;

    auto index = m_symbolicBreakpoints.findIf([&] (const auto& symbolicBreakpoint) {
        return symbolicBreakpoint.knownMatchingSymbols.contains(symbol);
    });
    if (index == notFound)
        return;

    ASSERT(m_symbolicBreakpoints[index].specialBreakpoint);

    auto pauseData = JSON::Object::create();
    pauseData->setString("name"_s, symbol);

    breakProgram(DebuggerFrontendDispatcher::Reason::FunctionCall, WTFMove(pauseData), m_symbolicBreakpoints[index].specialBreakpoint.copyRef());
}

bool InspectorDebuggerAgent::isInspectorDebuggerAgent() const
{
    return true;
}

JSC::JSObject* InspectorDebuggerAgent::debuggerScopeExtensionObject(JSC::Debugger& debugger, JSC::JSGlobalObject* globalObject, JSC::DebuggerCallFrame& debuggerCallFrame)
{
    auto injectedScript = m_injectedScriptManager.injectedScriptFor(globalObject);
    ASSERT(!injectedScript.hasNoValue());
    if (injectedScript.hasNoValue())
        return JSC::Debugger::Client::debuggerScopeExtensionObject(debugger, globalObject, debuggerCallFrame);

    auto* debuggerGlobalObject = debuggerCallFrame.scope(globalObject->vm())->globalObject();
    auto callFrame = toJS(debuggerGlobalObject, debuggerGlobalObject, JavaScriptCallFrame::create(debuggerCallFrame).ptr());
    return injectedScript.createCommandLineAPIObject(callFrame);
}

void InspectorDebuggerAgent::didParseSource(JSC::SourceID sourceID, const JSC::Debugger::Script& script)
{
    String scriptIDStr = String::number(sourceID);
    bool hasSourceURL = !script.sourceURL.isEmpty();
    String sourceURL = script.sourceURL;
    String sourceMappingURL = sourceMapURLForScript(script);

    m_frontendDispatcher->scriptParsed(scriptIDStr, script.url, script.startLine, script.startColumn, script.endLine, script.endColumn, script.isContentScript, sourceURL, sourceMappingURL, script.sourceProvider->sourceType() == JSC::SourceProviderSourceType::Module);

    m_scripts.set(sourceID, script);

    String scriptURLForBreakpoints = hasSourceURL ? script.sourceURL : script.url;
    if (scriptURLForBreakpoints.isEmpty())
        return;

    setBlackboxConfiguration(sourceID, script);

    for (auto& protocolBreakpoint : m_protocolBreakpointForProtocolBreakpointID.values()) {
        if (!protocolBreakpoint.matchesScriptURL(scriptURLForBreakpoints))
            continue;

        auto debuggerBreakpoint = protocolBreakpoint.createDebuggerBreakpoint(m_nextDebuggerBreakpointID++, sourceID);

        if (!resolveBreakpoint(script, debuggerBreakpoint))
            continue;

        if (!setBreakpoint(debuggerBreakpoint))
            continue;

        didSetBreakpoint(protocolBreakpoint, debuggerBreakpoint);

        m_frontendDispatcher->breakpointResolved(protocolBreakpoint.id(), buildDebuggerLocation(debuggerBreakpoint));
    }
}

void InspectorDebuggerAgent::failedToParseSource(const String& url, const String& data, int firstLine, int errorLine, const String& errorMessage)
{
    m_frontendDispatcher->scriptFailedToParse(url, data, firstLine, errorLine, errorMessage);
}

void InspectorDebuggerAgent::willEnter(JSC::CallFrame* callFrame)
{
    if (!breakpointsActive())
        return;

    if (m_symbolicBreakpoints.isEmpty())
        return;

    auto symbol = functionName(callFrame);
    if (symbol.isEmpty())
        return;

    auto index = m_symbolicBreakpoints.findIf([&] (const auto& symbolicBreakpoint) {
        return symbolicBreakpoint.knownMatchingSymbols.contains(symbol);
    });
    if (index == notFound)
        return;

    ASSERT(m_symbolicBreakpoints[index].specialBreakpoint);

    auto pauseData = JSON::Object::create();
    pauseData->setString("name"_s, symbol);

    schedulePauseForSpecialBreakpoint(*m_symbolicBreakpoints[index].specialBreakpoint, DebuggerFrontendDispatcher::Reason::FunctionCall, WTFMove(pauseData));
}

void InspectorDebuggerAgent::didQueueMicrotask(JSC::JSGlobalObject* globalObject, JSC::MicrotaskIdentifier identifier)
{
    if (!breakpointsActive())
        return;

    didScheduleAsyncCall(globalObject, InspectorDebuggerAgent::AsyncCallType::Microtask, identifier.toUInt64(), true);
}

void InspectorDebuggerAgent::willRunMicrotask(JSC::JSGlobalObject*, JSC::MicrotaskIdentifier identifier)
{
    willDispatchAsyncCall(AsyncCallType::Microtask, identifier.toUInt64());

    if (breakpointsActive() && m_pauseOnMicrotasksBreakpoint)
        schedulePauseForSpecialBreakpoint(*m_pauseOnMicrotasksBreakpoint, DebuggerFrontendDispatcher::Reason::Microtask);
}

void InspectorDebuggerAgent::didRunMicrotask(JSC::JSGlobalObject*, JSC::MicrotaskIdentifier identifier)
{
    didDispatchAsyncCall(AsyncCallType::Microtask, identifier.toUInt64());

    if (breakpointsActive() && m_pauseOnMicrotasksBreakpoint)
        cancelPauseForSpecialBreakpoint(*m_pauseOnMicrotasksBreakpoint);
}

void InspectorDebuggerAgent::didPause(JSC::JSGlobalObject* globalObject, JSC::DebuggerCallFrame& debuggerCallFrame, JSC::JSValue exceptionOrCaughtValue)
{
    ASSERT(!m_pausedGlobalObject);
    m_pausedGlobalObject = globalObject;

    auto* debuggerGlobalObject = debuggerCallFrame.scope(globalObject->vm())->globalObject();
    m_currentCallStack = { m_pausedGlobalObject->vm(), toJS(debuggerGlobalObject, debuggerGlobalObject, JavaScriptCallFrame::create(debuggerCallFrame).ptr()) };

    InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(m_pausedGlobalObject);

    // If a high level pause pause reason is not already set, try to infer a reason from the debugger.
    if (m_pauseReason == DebuggerFrontendDispatcher::Reason::Other) {
        switch (m_debugger.reasonForPause()) {
        case JSC::Debugger::PausedForBreakpoint: {
            auto debuggerBreakpointId = m_debugger.pausingBreakpointID();
            if (!m_continueToLocationDebuggerBreakpoint || debuggerBreakpointId != m_continueToLocationDebuggerBreakpoint->id())
                updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::Breakpoint, buildBreakpointPauseReason(debuggerBreakpointId));
            break;
        }
        case JSC::Debugger::PausedForDebuggerStatement:
            updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::DebuggerStatement, nullptr);
            break;
        case JSC::Debugger::PausedForException:
            updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::Exception, buildExceptionPauseReason(exceptionOrCaughtValue, injectedScript));
            break;
        case JSC::Debugger::PausedAfterBlackboxedScript: {
            // There should be no break data, as we would've already continued past the breakpoint.
            ASSERT(!m_pauseData);

            // Don't call `updatePauseReasonAndData` so as to not override `m_preBlackboxPauseData`.
            if (m_pauseReason != DebuggerFrontendDispatcher::Reason::BlackboxedScript)
                m_preBlackboxPauseReason = m_pauseReason;
            m_pauseReason = DebuggerFrontendDispatcher::Reason::BlackboxedScript;
            break;
        }
        case JSC::Debugger::PausedAtStatement:
        case JSC::Debugger::PausedAtExpression:
        case JSC::Debugger::PausedBeforeReturn:
        case JSC::Debugger::PausedAtEndOfProgram:
            // Pause was just stepping. Nothing to report.
            break;
        case JSC::Debugger::NotPaused:
            ASSERT_NOT_REACHED();
            break;
        }
    }

    if (m_debugger.reasonForPause() == JSC::Debugger::PausedAfterBlackboxedScript) {
        // Ensure that `m_preBlackboxPauseReason` is populated with the most recent data.
        updatePauseReasonAndData(m_pauseReason, nullptr);

        RefPtr<JSON::Object> data;
        if (auto debuggerBreakpointId = m_debugger.pausingBreakpointID()) {
            ASSERT(!m_continueToLocationDebuggerBreakpoint || debuggerBreakpointId != m_continueToLocationDebuggerBreakpoint->id());
            data = JSON::Object::create();
            data->setString("originalReason"_s, Protocol::Helpers::getEnumConstantValue(DebuggerFrontendDispatcher::Reason::Breakpoint));
            if (auto pauseReason = buildBreakpointPauseReason(debuggerBreakpointId))
                data->setValue("originalData"_s, pauseReason.releaseNonNull());
        } else if (m_preBlackboxPauseData) {
            data = JSON::Object::create();
            data->setString("originalReason"_s, Protocol::Helpers::getEnumConstantValue(m_preBlackboxPauseReason));
            data->setValue("originalData"_s, m_preBlackboxPauseData.releaseNonNull());
        }
        updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::BlackboxedScript, WTFMove(data));
    }

    // Set $exception to the exception or caught value.
    if (exceptionOrCaughtValue && !injectedScript.hasNoValue()) {
        injectedScript.setExceptionValue(exceptionOrCaughtValue);
        m_hasExceptionValue = true;
    }

    m_conditionToDispatchResumed = ShouldDispatchResumed::No;
    m_enablePauseWhenIdle = false;

    RefPtr<Protocol::Console::StackTrace> asyncStackTrace;
    if (auto* parentStackTrace = currentParentStackTrace())
        asyncStackTrace = parentStackTrace->buildInspectorObject();

    m_frontendDispatcher->paused(currentCallFrames(injectedScript), Protocol::Helpers::getEnumConstantValue(m_pauseReason), m_pauseData.copyRef(), WTFMove(asyncStackTrace));

    m_javaScriptPauseScheduled = false;

    if (m_continueToLocationDebuggerBreakpoint) {
        m_debugger.removeBreakpoint(*m_continueToLocationDebuggerBreakpoint);
        m_continueToLocationDebuggerBreakpoint = nullptr;
    }

    auto& stopwatch = m_injectedScriptManager.inspectorEnvironment().executionStopwatch();
    if (stopwatch.isActive()) {
        stopwatch.stop();
        m_didPauseStopwatch = true;
    }
}

void InspectorDebuggerAgent::applyBreakpoints(JSC::CodeBlock* codeBlock)
{
    if (m_symbolicBreakpoints.isEmpty())
        return;

    auto symbol = functionName(*codeBlock);
    if (symbol.isEmpty())
        return;

    for (auto& symbolicBreakpoint : m_symbolicBreakpoints) {
        if (symbolicBreakpoint.matches(symbol))
            codeBlock->addBreakpoint(1);
    }
}

void InspectorDebuggerAgent::breakpointActionSound(JSC::BreakpointActionID id)
{
    m_frontendDispatcher->playBreakpointActionSound(id);
}

void InspectorDebuggerAgent::breakpointActionProbe(JSC::JSGlobalObject* globalObject, JSC::BreakpointActionID actionID, unsigned batchId, unsigned sampleId, JSC::JSValue sample)
{
    InjectedScript injectedScript = m_injectedScriptManager.injectedScriptFor(globalObject);
    auto payload = injectedScript.wrapObject(sample, objectGroupForBreakpointAction(actionID), true);
    if (!payload)
        return;

    auto result = Protocol::Debugger::ProbeSample::create()
        .setProbeId(actionID)
        .setBatchId(batchId)
        .setSampleId(sampleId)
        .setTimestamp(m_injectedScriptManager.inspectorEnvironment().executionStopwatch().elapsedTime().seconds())
        .setPayload(payload.releaseNonNull())
        .release();
    m_frontendDispatcher->didSampleProbe(WTFMove(result));
}

void InspectorDebuggerAgent::didContinue()
{
    if (m_didPauseStopwatch) {
        m_didPauseStopwatch = false;
        m_injectedScriptManager.inspectorEnvironment().executionStopwatch().start();
    }

    m_pausedGlobalObject = nullptr;
    m_currentCallStack = { };
    m_injectedScriptManager.releaseObjectGroup(InspectorDebuggerAgent::backtraceObjectGroup);
    clearPauseDetails();
    clearExceptionValue();

    if (m_conditionToDispatchResumed == ShouldDispatchResumed::WhenContinued)
        m_frontendDispatcher->resumed();
}

void InspectorDebuggerAgent::didDeferBreakpointPause(JSC::BreakpointID breakpointId)
{
    updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::Breakpoint, buildBreakpointPauseReason(breakpointId));
}

void InspectorDebuggerAgent::breakProgram(DebuggerFrontendDispatcher::Reason reason, RefPtr<JSON::Object>&& data, RefPtr<JSC::Breakpoint>&& specialBreakpoint)
{
    updatePauseReasonAndData(reason, WTFMove(data));

    m_debugger.breakProgram(WTFMove(specialBreakpoint));
}

void InspectorDebuggerAgent::clearInspectorBreakpointState()
{
    for (auto& protocolBreakpointID : copyToVector(m_debuggerBreakpointsForProtocolBreakpointID.keys()))
        removeBreakpoint(protocolBreakpointID);

    m_protocolBreakpointForProtocolBreakpointID.clear();

    if (m_continueToLocationDebuggerBreakpoint) {
        m_debugger.removeBreakpoint(*m_continueToLocationDebuggerBreakpoint);
        m_continueToLocationDebuggerBreakpoint = nullptr;
    }

    m_pauseOnAssertionsBreakpoint = nullptr;
    m_pauseOnMicrotasksBreakpoint = nullptr;

#if ENABLE(JIT)
    {
        Locker locker { s_replacedThunksLock };

        replacedThunks().removeAllMatching([&] (auto& replacedThunk) {
            if (!replacedThunk->nativeExecutable)
                return true;

            if (&replacedThunk->nativeExecutable->vm() != &m_debugger.vm())
                return false;

            for (auto& symbolicBreakpoint : m_symbolicBreakpoints) {
                if (symbolicBreakpoint.matches(functionName(*replacedThunk->nativeExecutable))) {
                    ASSERT(replacedThunk->matchCount);
                    if (!--replacedThunk->matchCount)
                        return true;
                }
            }

            return false;
        });
    }
#endif

    m_symbolicBreakpoints.clear();

    clearDebuggerBreakpointState();
}

void InspectorDebuggerAgent::clearDebuggerBreakpointState()
{
    {
        JSC::JSLockHolder holder(m_debugger.vm());
        m_debugger.clearBreakpoints();
        m_debugger.clearBlackbox();
    }

    m_pausedGlobalObject = nullptr;
    m_currentCallStack = { };
    m_scripts.clear();
    m_debuggerBreakpointsForProtocolBreakpointID.clear();
    m_nextDebuggerBreakpointID = JSC::noBreakpointID + 1;
    m_continueToLocationDebuggerBreakpoint = nullptr;
    clearPauseDetails();
    m_javaScriptPauseScheduled = false;
    m_hasExceptionValue = false;

    if (isPaused()) {
        m_debugger.continueProgram();
        m_frontendDispatcher->resumed();
    }
}

void InspectorDebuggerAgent::didClearGlobalObject()
{
    // Clear breakpoints from the debugger, but keep the inspector's model of which
    // pages have what breakpoints, as the mapping is only sent to DebuggerAgent once.
    clearDebuggerBreakpointState();

    clearAsyncStackTraceData();

    m_frontendDispatcher->globalObjectCleared();
}

void InspectorDebuggerAgent::didClearAsyncStackTraceData()
{
}

bool InspectorDebuggerAgent::assertPaused(Protocol::ErrorString& errorString)
{
    if (!m_pausedGlobalObject) {
        errorString = "Must be paused"_s;
        return false;
    }

    return true;
}

void InspectorDebuggerAgent::clearPauseDetails()
{
    updatePauseReasonAndData(DebuggerFrontendDispatcher::Reason::Other, nullptr);
}

void InspectorDebuggerAgent::clearExceptionValue()
{
    if (m_hasExceptionValue) {
        m_injectedScriptManager.clearExceptionValue();
        m_hasExceptionValue = false;
    }
}

void InspectorDebuggerAgent::clearAsyncStackTraceData()
{
    m_pendingAsyncCalls.clear();
    m_currentAsyncCallIdentifierStack.clear();

    didClearAsyncStackTraceData();
}

bool InspectorDebuggerAgent::SymbolicBreakpoint::matches(const String& symbol)
{
    if (symbol.isEmpty())
        return false;

    if (knownMatchingSymbols.contains(symbol))
        return true;

    if (!m_symbolMatchRegex) {
        auto searchStringType = isRegex ? ContentSearchUtilities::SearchStringType::Regex : ContentSearchUtilities::SearchStringType::ExactString;
        m_symbolMatchRegex = ContentSearchUtilities::createRegularExpressionForSearchString(this->symbol, caseSensitive, searchStringType);
    }
    if (m_symbolMatchRegex->match(symbol) == -1)
        return false;

    knownMatchingSymbols.add(symbol);
    return true;
}

} // namespace Inspector