File: duk_debugger.c

package info (click to toggle)
duktape 2.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 21,160 kB
  • sloc: ansic: 215,359; python: 5,961; javascript: 4,555; makefile: 477; cpp: 205
file content (2894 lines) | stat: -rw-r--r-- 85,982 bytes parent folder | download | duplicates (2)
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
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
/*
 *  Duktape debugger
 */

#include "duk_internal.h"

#if defined(DUK_USE_DEBUGGER_SUPPORT)

/*
 *  Assert helpers
 */

#if defined(DUK_USE_ASSERTIONS)
#define DUK__DBG_TPORT_ENTER() \
	do { \
		DUK_ASSERT(heap->dbg_calling_transport == 0); \
		heap->dbg_calling_transport = 1; \
	} while (0)
#define DUK__DBG_TPORT_EXIT() \
	do { \
		DUK_ASSERT(heap->dbg_calling_transport == 1); \
		heap->dbg_calling_transport = 0; \
	} while (0)
#else
#define DUK__DBG_TPORT_ENTER() \
	do { \
	} while (0)
#define DUK__DBG_TPORT_EXIT() \
	do { \
	} while (0)
#endif

/*
 *  Helper structs
 */

typedef union {
	void *p;
	duk_uint_t b[1];
	/* Use b[] to access the size of the union, which is strictly not
	 * correct.  Can't use fixed size unless there's feature detection
	 * for pointer byte size.
	 */
} duk__ptr_union;

/*
 *  Detach handling
 */

#define DUK__SET_CONN_BROKEN(thr, reason) \
	do { \
		/* For now shared handler is fine. */ \
		duk__debug_do_detach1((thr)->heap, (reason)); \
	} while (0)

DUK_LOCAL void duk__debug_do_detach1(duk_heap *heap, duk_int_t reason) {
	/* Can be called multiple times with no harm.  Mark the transport
	 * bad (dbg_read_cb == NULL) and clear state except for the detached
	 * callback and the udata field.  The detached callback is delayed
	 * to the message loop so that it can be called between messages;
	 * this avoids corner cases related to immediate debugger reattach
	 * inside the detached callback.
	 */

	if (heap->dbg_detaching) {
		DUK_D(DUK_DPRINT("debugger already detaching, ignore detach1"));
		return;
	}

	DUK_D(DUK_DPRINT("debugger transport detaching, marking transport broken"));

	heap->dbg_detaching = 1; /* prevent multiple in-progress detaches */

	if (heap->dbg_write_cb != NULL) {
		duk_hthread *thr;

		thr = heap->heap_thread;
		DUK_ASSERT(thr != NULL);

		duk_debug_write_notify(thr, DUK_DBG_CMD_DETACHING);
		duk_debug_write_int(thr, reason);
		duk_debug_write_eom(thr);
	}

	heap->dbg_read_cb = NULL;
	heap->dbg_write_cb = NULL;
	heap->dbg_peek_cb = NULL;
	heap->dbg_read_flush_cb = NULL;
	heap->dbg_write_flush_cb = NULL;
	heap->dbg_request_cb = NULL;
	/* heap->dbg_detached_cb: keep */
	/* heap->dbg_udata: keep */
	/* heap->dbg_processing: keep on purpose to avoid debugger re-entry in detaching state */
	heap->dbg_state_dirty = 0;
	heap->dbg_force_restart = 0;
	heap->dbg_pause_flags = 0;
	heap->dbg_pause_act = NULL;
	heap->dbg_pause_startline = 0;
	heap->dbg_have_next_byte = 0;
	duk_debug_clear_paused(heap); /* XXX: some overlap with field inits above */
	heap->dbg_state_dirty = 0; /* XXX: clear_paused sets dirty; rework? */

	/* Ensure there are no stale active breakpoint pointers.
	 * Breakpoint list is currently kept - we could empty it
	 * here but we'd need to handle refcounts correctly, and
	 * we'd need a 'thr' reference for that.
	 *
	 * XXX: clear breakpoint on either attach or detach?
	 */
	heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;
}

DUK_LOCAL void duk__debug_do_detach2(duk_heap *heap) {
	duk_debug_detached_function detached_cb;
	void *detached_udata;
	duk_hthread *thr;

	thr = heap->heap_thread;
	if (thr == NULL) {
		DUK_ASSERT(heap->dbg_detached_cb == NULL);
		return;
	}

	/* Safe to call multiple times. */

	detached_cb = heap->dbg_detached_cb;
	detached_udata = heap->dbg_udata;
	heap->dbg_detached_cb = NULL;
	heap->dbg_udata = NULL;

	if (detached_cb) {
		/* Careful here: state must be wiped before the call
		 * so that we can cleanly handle a re-attach from
		 * inside the callback.
		 */
		DUK_D(DUK_DPRINT("detached during message loop, delayed call to detached_cb"));
		detached_cb(thr, detached_udata);
	}

	heap->dbg_detaching = 0;
}

DUK_INTERNAL void duk_debug_do_detach(duk_heap *heap) {
	duk__debug_do_detach1(heap, 0);
	duk__debug_do_detach2(heap);
}

/* Called on a read/write error: NULL all callbacks except the detached
 * callback so that we never accidentally call them after a read/write
 * error has been indicated.  This is especially important for the transport
 * I/O callbacks to fulfill guaranteed callback semantics.
 */
DUK_LOCAL void duk__debug_null_most_callbacks(duk_hthread *thr) {
	duk_heap *heap;

	DUK_ASSERT(thr != NULL);

	heap = thr->heap;
	DUK_D(DUK_DPRINT("transport read/write error, NULL all callbacks expected detached"));
	heap->dbg_read_cb = NULL;
	heap->dbg_write_cb = NULL; /* this is especially critical to avoid another write call in detach1() */
	heap->dbg_peek_cb = NULL;
	heap->dbg_read_flush_cb = NULL;
	heap->dbg_write_flush_cb = NULL;
	heap->dbg_request_cb = NULL;
	/* keep heap->dbg_detached_cb */
}

/*
 *  Pause handling
 */

DUK_LOCAL void duk__debug_set_pause_state(duk_hthread *thr, duk_heap *heap, duk_small_uint_t pause_flags) {
	duk_uint_fast32_t line;

	line = duk_debug_curr_line(thr);
	if (line == 0) {
		/* No line info for current function. */
		duk_small_uint_t updated_flags;

		updated_flags = pause_flags & ~(DUK_PAUSE_FLAG_LINE_CHANGE);
		DUK_D(DUK_DPRINT("no line info for current activation, disable line-based pause flags: 0x%08lx -> 0x%08lx",
		                 (long) pause_flags,
		                 (long) updated_flags));
		pause_flags = updated_flags;
	}

	heap->dbg_pause_flags = pause_flags;
	heap->dbg_pause_act = thr->callstack_curr;
	heap->dbg_pause_startline = (duk_uint32_t) line;
	heap->dbg_state_dirty = 1;

	DUK_D(DUK_DPRINT("set state for automatic pause triggers, flags=0x%08lx, act=%p, startline=%ld",
	                 (long) heap->dbg_pause_flags,
	                 (void *) heap->dbg_pause_act,
	                 (long) heap->dbg_pause_startline));
}

/*
 *  Debug connection peek and flush primitives
 */

DUK_INTERNAL duk_bool_t duk_debug_read_peek(duk_hthread *thr) {
	duk_heap *heap;
	duk_bool_t ret;

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	if (heap->dbg_read_cb == NULL) {
		DUK_D(DUK_DPRINT("attempt to peek in detached state, return zero (= no data)"));
		return 0;
	}
	if (heap->dbg_peek_cb == NULL) {
		DUK_DD(DUK_DDPRINT("no peek callback, return zero (= no data)"));
		return 0;
	}

	DUK__DBG_TPORT_ENTER();
	ret = (duk_bool_t) (heap->dbg_peek_cb(heap->dbg_udata) > 0);
	DUK__DBG_TPORT_EXIT();
	return ret;
}

DUK_INTERNAL void duk_debug_read_flush(duk_hthread *thr) {
	duk_heap *heap;

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	if (heap->dbg_read_cb == NULL) {
		DUK_D(DUK_DPRINT("attempt to read flush in detached state, ignore"));
		return;
	}
	if (heap->dbg_read_flush_cb == NULL) {
		DUK_DD(DUK_DDPRINT("no read flush callback, ignore"));
		return;
	}

	DUK__DBG_TPORT_ENTER();
	heap->dbg_read_flush_cb(heap->dbg_udata);
	DUK__DBG_TPORT_EXIT();
}

DUK_INTERNAL void duk_debug_write_flush(duk_hthread *thr) {
	duk_heap *heap;

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	if (heap->dbg_read_cb == NULL) {
		DUK_D(DUK_DPRINT("attempt to write flush in detached state, ignore"));
		return;
	}
	if (heap->dbg_write_flush_cb == NULL) {
		DUK_DD(DUK_DDPRINT("no write flush callback, ignore"));
		return;
	}

	DUK__DBG_TPORT_ENTER();
	heap->dbg_write_flush_cb(heap->dbg_udata);
	DUK__DBG_TPORT_EXIT();
}

/*
 *  Debug connection skip primitives
 */

/* Skip fully. */
DUK_INTERNAL void duk_debug_skip_bytes(duk_hthread *thr, duk_size_t length) {
	duk_uint8_t dummy[64];
	duk_size_t now;

	DUK_ASSERT(thr != NULL);

	while (length > 0) {
		now = (length > sizeof(dummy) ? sizeof(dummy) : length);
		duk_debug_read_bytes(thr, dummy, now);
		length -= now;
	}
}

DUK_INTERNAL void duk_debug_skip_byte(duk_hthread *thr) {
	DUK_ASSERT(thr != NULL);

	(void) duk_debug_read_byte(thr);
}

/*
 *  Debug connection read primitives
 */

/* Peek ahead in the stream one byte. */
DUK_INTERNAL uint8_t duk_debug_peek_byte(duk_hthread *thr) {
	/* It is important not to call this if the last byte read was an EOM.
	 * Reading ahead in this scenario would cause unnecessary blocking if
	 * another message is not available.
	 */

	duk_uint8_t x;

	x = duk_debug_read_byte(thr);
	thr->heap->dbg_have_next_byte = 1;
	thr->heap->dbg_next_byte = x;
	return x;
}

/* Read fully. */
DUK_INTERNAL void duk_debug_read_bytes(duk_hthread *thr, duk_uint8_t *data, duk_size_t length) {
	duk_heap *heap;
	duk_uint8_t *p;
	duk_size_t left;
	duk_size_t got;

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);
	DUK_ASSERT(data != NULL);

	if (heap->dbg_read_cb == NULL) {
		DUK_D(DUK_DPRINT("attempt to read %ld bytes in detached state, return zero data", (long) length));
		goto fail;
	}

	/* NOTE: length may be zero */
	p = data;
	if (length >= 1 && heap->dbg_have_next_byte) {
		heap->dbg_have_next_byte = 0;
		*p++ = heap->dbg_next_byte;
	}
	for (;;) {
		left = (duk_size_t) ((data + length) - p);
		if (left == 0) {
			break;
		}
		DUK_ASSERT(heap->dbg_read_cb != NULL);
		DUK_ASSERT(left >= 1);
#if defined(DUK_USE_DEBUGGER_TRANSPORT_TORTURE)
		left = 1;
#endif
		DUK__DBG_TPORT_ENTER();
		got = heap->dbg_read_cb(heap->dbg_udata, (char *) p, left);
		DUK__DBG_TPORT_EXIT();

		if (got == 0 || got > left) {
			DUK_D(DUK_DPRINT("connection error during read, return zero data"));
			duk__debug_null_most_callbacks(thr); /* avoid calling write callback in detach1() */
			DUK__SET_CONN_BROKEN(thr, 1);
			goto fail;
		}
		p += got;
	}
	return;

fail:
	duk_memzero((void *) data, (size_t) length);
}

DUK_INTERNAL duk_uint8_t duk_debug_read_byte(duk_hthread *thr) {
	duk_uint8_t x;

	x = 0; /* just in case callback is broken and won't write 'x' */
	duk_debug_read_bytes(thr, &x, 1);
	return x;
}

DUK_LOCAL duk_uint32_t duk__debug_read_uint32_raw(duk_hthread *thr) {
	duk_uint8_t buf[4];

	DUK_ASSERT(thr != NULL);

	duk_debug_read_bytes(thr, buf, 4);
	return ((duk_uint32_t) buf[0] << 24) | ((duk_uint32_t) buf[1] << 16) | ((duk_uint32_t) buf[2] << 8) | (duk_uint32_t) buf[3];
}

DUK_LOCAL duk_int32_t duk__debug_read_int32_raw(duk_hthread *thr) {
	return (duk_int32_t) duk__debug_read_uint32_raw(thr);
}

DUK_LOCAL duk_uint16_t duk__debug_read_uint16_raw(duk_hthread *thr) {
	duk_uint8_t buf[2];

	DUK_ASSERT(thr != NULL);

	duk_debug_read_bytes(thr, buf, 2);
	return ((duk_uint16_t) buf[0] << 8) | (duk_uint16_t) buf[1];
}

DUK_INTERNAL duk_int32_t duk_debug_read_int(duk_hthread *thr) {
	duk_small_uint_t x;
	duk_small_uint_t t;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);
	if (x >= 0xc0) {
		t = duk_debug_read_byte(thr);
		return (duk_int32_t) (((x - 0xc0) << 8) + t);
	} else if (x >= 0x80) {
		return (duk_int32_t) (x - 0x80);
	} else if (x == DUK_DBG_IB_INT4) {
		return (duk_int32_t) duk__debug_read_uint32_raw(thr);
	}

	DUK_D(DUK_DPRINT("debug connection error: failed to decode int"));
	DUK__SET_CONN_BROKEN(thr, 1);
	return 0;
}

DUK_LOCAL duk_hstring *duk__debug_read_hstring_raw(duk_hthread *thr, duk_uint32_t len) {
	duk_uint8_t buf[31];
	duk_uint8_t *p;

	if (len <= sizeof(buf)) {
		duk_debug_read_bytes(thr, buf, (duk_size_t) len);
		duk_push_lstring(thr, (const char *) buf, (duk_size_t) len);
	} else {
		p = (duk_uint8_t *) duk_push_fixed_buffer(thr, (duk_size_t) len); /* zero for paranoia */
		DUK_ASSERT(p != NULL);
		duk_debug_read_bytes(thr, p, (duk_size_t) len);
		(void) duk_buffer_to_string(thr, -1); /* Safety relies on debug client, which is OK. */
	}

	return duk_require_hstring(thr, -1);
}

DUK_INTERNAL duk_hstring *duk_debug_read_hstring(duk_hthread *thr) {
	duk_small_uint_t x;
	duk_uint32_t len;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);
	if (x >= 0x60 && x <= 0x7f) {
		/* For short strings, use a fixed temp buffer. */
		len = (duk_uint32_t) (x - 0x60);
	} else if (x == DUK_DBG_IB_STR2) {
		len = (duk_uint32_t) duk__debug_read_uint16_raw(thr);
	} else if (x == DUK_DBG_IB_STR4) {
		len = (duk_uint32_t) duk__debug_read_uint32_raw(thr);
	} else {
		goto fail;
	}

	return duk__debug_read_hstring_raw(thr, len);

fail:
	DUK_D(DUK_DPRINT("debug connection error: failed to decode int"));
	DUK__SET_CONN_BROKEN(thr, 1);
	duk_push_hstring_empty(thr); /* always push some string */
	return duk_require_hstring(thr, -1);
}

DUK_LOCAL duk_hbuffer *duk__debug_read_hbuffer_raw(duk_hthread *thr, duk_uint32_t len) {
	duk_uint8_t *p;

	p = (duk_uint8_t *) duk_push_fixed_buffer(thr, (duk_size_t) len); /* zero for paranoia */
	DUK_ASSERT(p != NULL);
	duk_debug_read_bytes(thr, p, (duk_size_t) len);

	return duk_require_hbuffer(thr, -1);
}

DUK_LOCAL void *duk__debug_read_pointer_raw(duk_hthread *thr) {
	duk_small_uint_t x;
	duk__ptr_union pu;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);
	if (x != sizeof(pu)) {
		goto fail;
	}
	duk_debug_read_bytes(thr, (duk_uint8_t *) &pu.p, sizeof(pu));
#if defined(DUK_USE_INTEGER_LE)
	duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
#endif
	return (void *) pu.p;

fail:
	DUK_D(DUK_DPRINT("debug connection error: failed to decode pointer"));
	DUK__SET_CONN_BROKEN(thr, 1);
	return (void *) NULL;
}

DUK_LOCAL duk_double_t duk__debug_read_double_raw(duk_hthread *thr) {
	duk_double_union du;

	DUK_ASSERT(sizeof(du.uc) == 8);
	duk_debug_read_bytes(thr, (duk_uint8_t *) du.uc, sizeof(du.uc));
	DUK_DBLUNION_DOUBLE_NTOH(&du);
	return du.d;
}

#if 0
DUK_INTERNAL duk_heaphdr *duk_debug_read_heapptr(duk_hthread *thr) {
	duk_small_uint_t x;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);
	if (x != DUK_DBG_IB_HEAPPTR) {
		goto fail;
	}

	return (duk_heaphdr *) duk__debug_read_pointer_raw(thr);

 fail:
	DUK_D(DUK_DPRINT("debug connection error: failed to decode heapptr"));
	DUK__SET_CONN_BROKEN(thr, 1);
	return NULL;
}
#endif

DUK_INTERNAL duk_heaphdr *duk_debug_read_any_ptr(duk_hthread *thr) {
	duk_small_uint_t x;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);
	switch (x) {
	case DUK_DBG_IB_OBJECT:
	case DUK_DBG_IB_POINTER:
	case DUK_DBG_IB_HEAPPTR:
		/* Accept any pointer-like value; for 'object' dvalue, read
		 * and ignore the class number.
		 */
		if (x == DUK_DBG_IB_OBJECT) {
			duk_debug_skip_byte(thr);
		}
		break;
	default:
		goto fail;
	}

	return (duk_heaphdr *) duk__debug_read_pointer_raw(thr);

fail:
	DUK_D(DUK_DPRINT("debug connection error: failed to decode any pointer (object, pointer, heapptr)"));
	DUK__SET_CONN_BROKEN(thr, 1);
	return NULL;
}

DUK_INTERNAL duk_tval *duk_debug_read_tval(duk_hthread *thr) {
	duk_uint8_t x;
	duk_uint_t t;
	duk_uint32_t len;

	DUK_ASSERT(thr != NULL);

	x = duk_debug_read_byte(thr);

	if (x >= 0xc0) {
		t = (duk_uint_t) (x - 0xc0);
		t = (t << 8) + duk_debug_read_byte(thr);
		duk_push_uint(thr, (duk_uint_t) t);
		goto return_ptr;
	}
	if (x >= 0x80) {
		duk_push_uint(thr, (duk_uint_t) (x - 0x80));
		goto return_ptr;
	}
	if (x >= 0x60) {
		len = (duk_uint32_t) (x - 0x60);
		duk__debug_read_hstring_raw(thr, len);
		goto return_ptr;
	}

	switch (x) {
	case DUK_DBG_IB_INT4: {
		duk_int32_t i = duk__debug_read_int32_raw(thr);
		duk_push_i32(thr, i);
		break;
	}
	case DUK_DBG_IB_STR4: {
		len = duk__debug_read_uint32_raw(thr);
		duk__debug_read_hstring_raw(thr, len);
		break;
	}
	case DUK_DBG_IB_STR2: {
		len = duk__debug_read_uint16_raw(thr);
		duk__debug_read_hstring_raw(thr, len);
		break;
	}
	case DUK_DBG_IB_BUF4: {
		len = duk__debug_read_uint32_raw(thr);
		duk__debug_read_hbuffer_raw(thr, len);
		break;
	}
	case DUK_DBG_IB_BUF2: {
		len = duk__debug_read_uint16_raw(thr);
		duk__debug_read_hbuffer_raw(thr, len);
		break;
	}
	case DUK_DBG_IB_UNDEFINED: {
		duk_push_undefined(thr);
		break;
	}
	case DUK_DBG_IB_NULL: {
		duk_push_null(thr);
		break;
	}
	case DUK_DBG_IB_TRUE: {
		duk_push_true(thr);
		break;
	}
	case DUK_DBG_IB_FALSE: {
		duk_push_false(thr);
		break;
	}
	case DUK_DBG_IB_NUMBER: {
		duk_double_t d;
		d = duk__debug_read_double_raw(thr);
		duk_push_number(thr, d);
		break;
	}
	case DUK_DBG_IB_OBJECT: {
		duk_heaphdr *h;
		duk_debug_skip_byte(thr);
		h = (duk_heaphdr *) duk__debug_read_pointer_raw(thr);
		duk_push_heapptr(thr, (void *) h);
		break;
	}
	case DUK_DBG_IB_POINTER: {
		void *ptr;
		ptr = duk__debug_read_pointer_raw(thr);
		duk_push_pointer(thr, ptr);
		break;
	}
	case DUK_DBG_IB_LIGHTFUNC: {
		/* XXX: Not needed for now, so not implemented.  Note that
		 * function pointers may have different size/layout than
		 * a void pointer.
		 */
		DUK_D(DUK_DPRINT("reading lightfunc values unimplemented"));
		goto fail;
	}
	case DUK_DBG_IB_HEAPPTR: {
		duk_heaphdr *h;
		h = (duk_heaphdr *) duk__debug_read_pointer_raw(thr);
		duk_push_heapptr(thr, (void *) h);
		break;
	}
	case DUK_DBG_IB_UNUSED: /* unused: not accepted in inbound messages */
	default:
		goto fail;
	}

return_ptr:
	return DUK_GET_TVAL_NEGIDX(thr, -1);

fail:
	DUK_D(DUK_DPRINT("debug connection error: failed to decode tval"));
	DUK__SET_CONN_BROKEN(thr, 1);
	return NULL;
}

/*
 *  Debug connection write primitives
 */

/* Write fully. */
DUK_INTERNAL void duk_debug_write_bytes(duk_hthread *thr, const duk_uint8_t *data, duk_size_t length) {
	duk_heap *heap;
	const duk_uint8_t *p;
	duk_size_t left;
	duk_size_t got;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(length == 0 || data != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	if (heap->dbg_write_cb == NULL) {
		DUK_D(DUK_DPRINT("attempt to write %ld bytes in detached state, ignore", (long) length));
		return;
	}
	if (length == 0) {
		/* Avoid doing an actual write callback with length == 0,
		 * because that's reserved for a write flush.
		 */
		return;
	}
	DUK_ASSERT(data != NULL);

	p = data;
	for (;;) {
		left = (duk_size_t) ((data + length) - p);
		if (left == 0) {
			break;
		}
		DUK_ASSERT(heap->dbg_write_cb != NULL);
		DUK_ASSERT(left >= 1);
#if defined(DUK_USE_DEBUGGER_TRANSPORT_TORTURE)
		left = 1;
#endif
		DUK__DBG_TPORT_ENTER();
		got = heap->dbg_write_cb(heap->dbg_udata, (const char *) p, left);
		DUK__DBG_TPORT_EXIT();

		if (got == 0 || got > left) {
			duk__debug_null_most_callbacks(thr); /* avoid calling write callback in detach1() */
			DUK_D(DUK_DPRINT("connection error during write"));
			DUK__SET_CONN_BROKEN(thr, 1);
			return;
		}
		p += got;
	}
}

DUK_INTERNAL void duk_debug_write_byte(duk_hthread *thr, duk_uint8_t x) {
	duk_debug_write_bytes(thr, (const duk_uint8_t *) &x, 1);
}

DUK_INTERNAL void duk_debug_write_unused(duk_hthread *thr) {
	duk_debug_write_byte(thr, DUK_DBG_IB_UNUSED);
}

DUK_INTERNAL void duk_debug_write_undefined(duk_hthread *thr) {
	duk_debug_write_byte(thr, DUK_DBG_IB_UNDEFINED);
}

#if defined(DUK_USE_DEBUGGER_INSPECT)
DUK_INTERNAL void duk_debug_write_null(duk_hthread *thr) {
	duk_debug_write_byte(thr, DUK_DBG_IB_NULL);
}
#endif

DUK_INTERNAL void duk_debug_write_boolean(duk_hthread *thr, duk_uint_t val) {
	duk_debug_write_byte(thr, val ? DUK_DBG_IB_TRUE : DUK_DBG_IB_FALSE);
}

/* Write signed 32-bit integer. */
DUK_INTERNAL void duk_debug_write_int(duk_hthread *thr, duk_int32_t x) {
	duk_uint8_t buf[5];
	duk_size_t len;

	DUK_ASSERT(thr != NULL);

	if (x >= 0 && x <= 0x3fL) {
		buf[0] = (duk_uint8_t) (0x80 + x);
		len = 1;
	} else if (x >= 0 && x <= 0x3fffL) {
		buf[0] = (duk_uint8_t) (0xc0 + (x >> 8));
		buf[1] = (duk_uint8_t) (x & 0xff);
		len = 2;
	} else {
		/* Signed integers always map to 4 bytes now. */
		buf[0] = (duk_uint8_t) DUK_DBG_IB_INT4;
		buf[1] = (duk_uint8_t) ((x >> 24) & 0xff);
		buf[2] = (duk_uint8_t) ((x >> 16) & 0xff);
		buf[3] = (duk_uint8_t) ((x >> 8) & 0xff);
		buf[4] = (duk_uint8_t) (x & 0xff);
		len = 5;
	}
	duk_debug_write_bytes(thr, buf, len);
}

/* Write unsigned 32-bit integer. */
DUK_INTERNAL void duk_debug_write_uint(duk_hthread *thr, duk_uint32_t x) {
	/* The debugger protocol doesn't support a plain integer encoding for
	 * the full 32-bit unsigned range (only 32-bit signed).  For now,
	 * unsigned 32-bit values simply written as signed ones.  This is not
	 * a concrete issue except for 32-bit heaphdr fields.  Proper solutions
	 * would be to (a) write such integers as IEEE doubles or (b) add an
	 * unsigned 32-bit dvalue.
	 */
	if (x >= 0x80000000UL) {
		DUK_D(DUK_DPRINT("writing unsigned integer 0x%08lx as signed integer", (long) x));
	}
	duk_debug_write_int(thr, (duk_int32_t) x);
}

DUK_INTERNAL void duk_debug_write_strbuf(duk_hthread *thr, const char *data, duk_size_t length, duk_uint8_t marker_base) {
	duk_uint8_t buf[5];
	duk_size_t buflen;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(length == 0 || data != NULL);

	if (length <= 0x1fUL && marker_base == DUK_DBG_IB_STR4) {
		/* For strings, special form for short lengths. */
		buf[0] = (duk_uint8_t) (0x60 + length);
		buflen = 1;
	} else if (length <= 0xffffUL) {
		buf[0] = (duk_uint8_t) (marker_base + 1);
		buf[1] = (duk_uint8_t) (length >> 8);
		buf[2] = (duk_uint8_t) (length & 0xff);
		buflen = 3;
	} else {
		buf[0] = (duk_uint8_t) marker_base;
		buf[1] = (duk_uint8_t) (length >> 24);
		buf[2] = (duk_uint8_t) ((length >> 16) & 0xff);
		buf[3] = (duk_uint8_t) ((length >> 8) & 0xff);
		buf[4] = (duk_uint8_t) (length & 0xff);
		buflen = 5;
	}

	duk_debug_write_bytes(thr, (const duk_uint8_t *) buf, buflen);
	duk_debug_write_bytes(thr, (const duk_uint8_t *) data, length);
}

DUK_INTERNAL void duk_debug_write_string(duk_hthread *thr, const char *data, duk_size_t length) {
	duk_debug_write_strbuf(thr, data, length, DUK_DBG_IB_STR4);
}

DUK_INTERNAL void duk_debug_write_cstring(duk_hthread *thr, const char *data) {
	DUK_ASSERT(thr != NULL);

	duk_debug_write_string(thr, data, data ? DUK_STRLEN(data) : 0);
}

DUK_INTERNAL void duk_debug_write_hstring(duk_hthread *thr, duk_hstring *h) {
	DUK_ASSERT(thr != NULL);

	/* XXX: differentiate null pointer from empty string? */
	duk_debug_write_string(thr,
	                       (h != NULL ? (const char *) DUK_HSTRING_GET_DATA(h) : NULL),
	                       (h != NULL ? (duk_size_t) DUK_HSTRING_GET_BYTELEN(h) : 0));
}

DUK_LOCAL void duk__debug_write_hstring_safe_top(duk_hthread *thr) {
	duk_debug_write_hstring(thr, duk_safe_to_hstring(thr, -1));
}

DUK_INTERNAL void duk_debug_write_buffer(duk_hthread *thr, const char *data, duk_size_t length) {
	duk_debug_write_strbuf(thr, data, length, DUK_DBG_IB_BUF4);
}

DUK_INTERNAL void duk_debug_write_hbuffer(duk_hthread *thr, duk_hbuffer *h) {
	DUK_ASSERT(thr != NULL);

	duk_debug_write_buffer(thr,
	                       (h != NULL ? (const char *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h) : NULL),
	                       (h != NULL ? (duk_size_t) DUK_HBUFFER_GET_SIZE(h) : 0));
}

DUK_LOCAL void duk__debug_write_pointer_raw(duk_hthread *thr, void *ptr, duk_uint8_t ibyte) {
	duk_uint8_t buf[2];
	duk__ptr_union pu;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(sizeof(ptr) >= 1 && sizeof(ptr) <= 16);
	/* ptr may be NULL */

	buf[0] = ibyte;
	buf[1] = sizeof(pu);
	duk_debug_write_bytes(thr, buf, 2);
	pu.p = (void *) ptr;
#if defined(DUK_USE_INTEGER_LE)
	duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
#endif
	duk_debug_write_bytes(thr, (const duk_uint8_t *) &pu.p, (duk_size_t) sizeof(pu));
}

DUK_INTERNAL void duk_debug_write_pointer(duk_hthread *thr, void *ptr) {
	duk__debug_write_pointer_raw(thr, ptr, DUK_DBG_IB_POINTER);
}

#if defined(DUK_USE_DEBUGGER_DUMPHEAP) || defined(DUK_USE_DEBUGGER_INSPECT)
DUK_INTERNAL void duk_debug_write_heapptr(duk_hthread *thr, duk_heaphdr *h) {
	duk__debug_write_pointer_raw(thr, (void *) h, DUK_DBG_IB_HEAPPTR);
}
#endif /* DUK_USE_DEBUGGER_DUMPHEAP || DUK_USE_DEBUGGER_INSPECT */

DUK_INTERNAL void duk_debug_write_hobject(duk_hthread *thr, duk_hobject *obj) {
	duk_uint8_t buf[3];
	duk__ptr_union pu;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(sizeof(obj) >= 1 && sizeof(obj) <= 16);
	DUK_ASSERT(obj != NULL);

	buf[0] = DUK_DBG_IB_OBJECT;
	buf[1] = (duk_uint8_t) DUK_HOBJECT_GET_CLASS_NUMBER(obj);
	buf[2] = sizeof(pu);
	duk_debug_write_bytes(thr, buf, 3);
	pu.p = (void *) obj;
#if defined(DUK_USE_INTEGER_LE)
	duk_byteswap_bytes((duk_uint8_t *) pu.b, sizeof(pu));
#endif
	duk_debug_write_bytes(thr, (const duk_uint8_t *) &pu.p, (duk_size_t) sizeof(pu));
}

DUK_INTERNAL void duk_debug_write_tval(duk_hthread *thr, duk_tval *tv) {
	duk_c_function lf_func;
	duk_small_uint_t lf_flags;
	duk_uint8_t buf[4];
	duk_double_union du1;
	duk_double_union du2;
	duk_int32_t i32;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(tv != NULL);

	switch (DUK_TVAL_GET_TAG(tv)) {
	case DUK_TAG_UNDEFINED:
		duk_debug_write_byte(thr, DUK_DBG_IB_UNDEFINED);
		break;
	case DUK_TAG_UNUSED:
		duk_debug_write_byte(thr, DUK_DBG_IB_UNUSED);
		break;
	case DUK_TAG_NULL:
		duk_debug_write_byte(thr, DUK_DBG_IB_NULL);
		break;
	case DUK_TAG_BOOLEAN:
		DUK_ASSERT(DUK_TVAL_GET_BOOLEAN(tv) == 0 || DUK_TVAL_GET_BOOLEAN(tv) == 1);
		duk_debug_write_boolean(thr, DUK_TVAL_GET_BOOLEAN(tv));
		break;
	case DUK_TAG_POINTER:
		duk_debug_write_pointer(thr, (void *) DUK_TVAL_GET_POINTER(tv));
		break;
	case DUK_TAG_LIGHTFUNC:
		DUK_TVAL_GET_LIGHTFUNC(tv, lf_func, lf_flags);
		buf[0] = DUK_DBG_IB_LIGHTFUNC;
		buf[1] = (duk_uint8_t) (lf_flags >> 8);
		buf[2] = (duk_uint8_t) (lf_flags & 0xff);
		buf[3] = sizeof(lf_func);
		duk_debug_write_bytes(thr, buf, 4);
		duk_debug_write_bytes(thr, (const duk_uint8_t *) &lf_func, sizeof(lf_func));
		break;
	case DUK_TAG_STRING:
		duk_debug_write_hstring(thr, DUK_TVAL_GET_STRING(tv));
		break;
	case DUK_TAG_OBJECT:
		duk_debug_write_hobject(thr, DUK_TVAL_GET_OBJECT(tv));
		break;
	case DUK_TAG_BUFFER:
		duk_debug_write_hbuffer(thr, DUK_TVAL_GET_BUFFER(tv));
		break;
#if defined(DUK_USE_FASTINT)
	case DUK_TAG_FASTINT:
#endif
	default:
		/* Numbers are normalized to big (network) endian.  We can
		 * (but are not required) to use integer dvalues when there's
		 * no loss of precision.
		 *
		 * XXX: share check with other code; this check is slow but
		 * reliable and doesn't require careful exponent/mantissa
		 * mask tricks as in the fastint downgrade code.
		 */
		DUK_ASSERT(!DUK_TVAL_IS_UNUSED(tv));
		DUK_ASSERT(DUK_TVAL_IS_NUMBER(tv));
		du1.d = DUK_TVAL_GET_NUMBER(tv);
		i32 = (duk_int32_t) du1.d;
		du2.d = (duk_double_t) i32;

		DUK_DD(DUK_DDPRINT("i32=%ld du1=%02x%02x%02x%02x%02x%02x%02x%02x "
		                   "du2=%02x%02x%02x%02x%02x%02x%02x%02x",
		                   (long) i32,
		                   (unsigned int) du1.uc[0],
		                   (unsigned int) du1.uc[1],
		                   (unsigned int) du1.uc[2],
		                   (unsigned int) du1.uc[3],
		                   (unsigned int) du1.uc[4],
		                   (unsigned int) du1.uc[5],
		                   (unsigned int) du1.uc[6],
		                   (unsigned int) du1.uc[7],
		                   (unsigned int) du2.uc[0],
		                   (unsigned int) du2.uc[1],
		                   (unsigned int) du2.uc[2],
		                   (unsigned int) du2.uc[3],
		                   (unsigned int) du2.uc[4],
		                   (unsigned int) du2.uc[5],
		                   (unsigned int) du2.uc[6],
		                   (unsigned int) du2.uc[7]));

		if (duk_memcmp((const void *) du1.uc, (const void *) du2.uc, sizeof(du1.uc)) == 0) {
			duk_debug_write_int(thr, i32);
		} else {
			DUK_DBLUNION_DOUBLE_HTON(&du1);
			duk_debug_write_byte(thr, DUK_DBG_IB_NUMBER);
			duk_debug_write_bytes(thr, (const duk_uint8_t *) du1.uc, sizeof(du1.uc));
		}
	}
}

#if defined(DUK_USE_DEBUGGER_DUMPHEAP)
/* Variant for writing duk_tvals so that any heap allocated values are
 * written out as tagged heap pointers.
 */
DUK_LOCAL void duk__debug_write_tval_heapptr(duk_hthread *thr, duk_tval *tv) {
	if (DUK_TVAL_IS_HEAP_ALLOCATED(tv)) {
		duk_heaphdr *h = DUK_TVAL_GET_HEAPHDR(tv);
		duk_debug_write_heapptr(thr, h);
	} else {
		duk_debug_write_tval(thr, tv);
	}
}
#endif /* DUK_USE_DEBUGGER_DUMPHEAP */

/*
 *  Debug connection message write helpers
 */

#if 0 /* unused */
DUK_INTERNAL void duk_debug_write_request(duk_hthread *thr, duk_small_uint_t command) {
	duk_debug_write_byte(thr, DUK_DBG_IB_REQUEST);
	duk_debug_write_int(thr, command);
}
#endif

DUK_INTERNAL void duk_debug_write_reply(duk_hthread *thr) {
	duk_debug_write_byte(thr, DUK_DBG_IB_REPLY);
}

DUK_INTERNAL void duk_debug_write_error_eom(duk_hthread *thr, duk_small_uint_t err_code, const char *msg) {
	/* Allow NULL 'msg' */
	duk_debug_write_byte(thr, DUK_DBG_IB_ERROR);
	duk_debug_write_int(thr, (duk_int32_t) err_code);
	duk_debug_write_cstring(thr, msg);
	duk_debug_write_eom(thr);
}

DUK_INTERNAL void duk_debug_write_notify(duk_hthread *thr, duk_small_uint_t command) {
	duk_debug_write_byte(thr, DUK_DBG_IB_NOTIFY);
	duk_debug_write_int(thr, (duk_int32_t) command);
}

DUK_INTERNAL void duk_debug_write_eom(duk_hthread *thr) {
	duk_debug_write_byte(thr, DUK_DBG_IB_EOM);

	/* As an initial implementation, write flush after every EOM (and the
	 * version identifier).  A better implementation would flush only when
	 * Duktape is finished processing messages so that a flush only happens
	 * after all outbound messages are finished on that occasion.
	 */
	duk_debug_write_flush(thr);
}

/*
 *  Status message and helpers
 */

DUK_INTERNAL duk_uint_fast32_t duk_debug_curr_line(duk_hthread *thr) {
	duk_activation *act;
	duk_uint_fast32_t line;
	duk_uint_fast32_t pc;

	act = thr->callstack_curr;
	if (act == NULL) {
		return 0;
	}

	/* We're conceptually between two opcodes; act->pc indicates the next
	 * instruction to be executed.  This is usually the correct pc/line to
	 * indicate in Status.  (For the 'debugger' statement this now reports
	 * the pc/line after the debugger statement because the debugger opcode
	 * has already been executed.)
	 */

	pc = duk_hthread_get_act_curr_pc(thr, act);

	/* XXX: this should be optimized to be a raw query and avoid valstack
	 * operations if possible.
	 */
	duk_push_tval(thr, &act->tv_func);
	line = duk_hobject_pc2line_query(thr, -1, pc);
	duk_pop(thr);
	return line;
}

DUK_INTERNAL void duk_debug_send_status(duk_hthread *thr) {
	duk_activation *act;

	duk_debug_write_notify(thr, DUK_DBG_CMD_STATUS);
	duk_debug_write_int(thr, (DUK_HEAP_HAS_DEBUGGER_PAUSED(thr->heap) ? 1 : 0));

	act = thr->callstack_curr;
	if (act == NULL) {
		duk_debug_write_undefined(thr);
		duk_debug_write_undefined(thr);
		duk_debug_write_int(thr, 0);
		duk_debug_write_int(thr, 0);
	} else {
		duk_push_tval(thr, &act->tv_func);
		duk_get_prop_literal(thr, -1, "fileName");
		duk__debug_write_hstring_safe_top(thr);
		duk_get_prop_literal(thr, -2, "name");
		duk__debug_write_hstring_safe_top(thr);
		duk_pop_3(thr);
		/* Report next pc/line to be executed. */
		duk_debug_write_uint(thr, (duk_uint32_t) duk_debug_curr_line(thr));
		duk_debug_write_uint(thr, (duk_uint32_t) duk_hthread_get_act_curr_pc(thr, act));
	}

	duk_debug_write_eom(thr);
}

#if defined(DUK_USE_DEBUGGER_THROW_NOTIFY)
DUK_INTERNAL void duk_debug_send_throw(duk_hthread *thr, duk_bool_t fatal) {
	/*
	 *  NFY <int: 5> <int: fatal> <str: msg> <str: filename> <int: linenumber> EOM
	 */

	duk_activation *act;
	duk_uint32_t pc;

	DUK_ASSERT(thr->valstack_top > thr->valstack); /* At least: ... [err] */

	duk_debug_write_notify(thr, DUK_DBG_CMD_THROW);
	duk_debug_write_int(thr, (duk_int32_t) fatal);

	/* Report thrown value to client coerced to string */
	duk_dup_top(thr);
	duk__debug_write_hstring_safe_top(thr);
	duk_pop(thr);

	if (duk_is_error(thr, -1)) {
		/* Error instance, use augmented error data directly */
		duk_get_prop_stridx_short(thr, -1, DUK_STRIDX_FILE_NAME);
		duk__debug_write_hstring_safe_top(thr);
		duk_get_prop_stridx_short(thr, -2, DUK_STRIDX_LINE_NUMBER);
		duk_debug_write_uint(thr, duk_get_uint(thr, -1));
		duk_pop_2(thr);
	} else {
		/* For anything other than an Error instance, we calculate the
		 * error location directly from the current activation if one
		 * exists.
		 */
		act = thr->callstack_curr;
		if (act != NULL) {
			duk_push_tval(thr, &act->tv_func);
			duk_get_prop_literal(thr, -1, "fileName");
			duk__debug_write_hstring_safe_top(thr);
			pc = (duk_uint32_t) duk_hthread_get_act_prev_pc(thr, act);
			duk_debug_write_uint(thr, (duk_uint32_t) duk_hobject_pc2line_query(thr, -2, pc));
			duk_pop_2(thr);
		} else {
			/* Can happen if duk_throw() is called on an empty
			 * callstack.
			 */
			duk_debug_write_cstring(thr, "");
			duk_debug_write_uint(thr, 0);
		}
	}

	duk_debug_write_eom(thr);
}
#endif /* DUK_USE_DEBUGGER_THROW_NOTIFY */

/*
 *  Debug message processing
 */

/* Skip dvalue. */
DUK_LOCAL duk_bool_t duk__debug_skip_dvalue(duk_hthread *thr) {
	duk_uint8_t x;
	duk_uint32_t len;

	x = duk_debug_read_byte(thr);

	if (x >= 0xc0) {
		duk_debug_skip_byte(thr);
		return 0;
	}
	if (x >= 0x80) {
		return 0;
	}
	if (x >= 0x60) {
		duk_debug_skip_bytes(thr, (duk_size_t) (x - 0x60));
		return 0;
	}
	switch (x) {
	case DUK_DBG_IB_EOM:
		return 1; /* Return 1: got EOM */
	case DUK_DBG_IB_REQUEST:
	case DUK_DBG_IB_REPLY:
	case DUK_DBG_IB_ERROR:
	case DUK_DBG_IB_NOTIFY:
		break;
	case DUK_DBG_IB_INT4:
		(void) duk__debug_read_uint32_raw(thr);
		break;
	case DUK_DBG_IB_STR4:
	case DUK_DBG_IB_BUF4:
		len = duk__debug_read_uint32_raw(thr);
		duk_debug_skip_bytes(thr, len);
		break;
	case DUK_DBG_IB_STR2:
	case DUK_DBG_IB_BUF2:
		len = duk__debug_read_uint16_raw(thr);
		duk_debug_skip_bytes(thr, len);
		break;
	case DUK_DBG_IB_UNUSED:
	case DUK_DBG_IB_UNDEFINED:
	case DUK_DBG_IB_NULL:
	case DUK_DBG_IB_TRUE:
	case DUK_DBG_IB_FALSE:
		break;
	case DUK_DBG_IB_NUMBER:
		duk_debug_skip_bytes(thr, 8);
		break;
	case DUK_DBG_IB_OBJECT:
		duk_debug_skip_byte(thr);
		len = duk_debug_read_byte(thr);
		duk_debug_skip_bytes(thr, len);
		break;
	case DUK_DBG_IB_POINTER:
	case DUK_DBG_IB_HEAPPTR:
		len = duk_debug_read_byte(thr);
		duk_debug_skip_bytes(thr, len);
		break;
	case DUK_DBG_IB_LIGHTFUNC:
		duk_debug_skip_bytes(thr, 2);
		len = duk_debug_read_byte(thr);
		duk_debug_skip_bytes(thr, len);
		break;
	default:
		goto fail;
	}

	return 0;

fail:
	DUK__SET_CONN_BROKEN(thr, 1);
	return 1; /* Pretend like we got EOM */
}

/* Skip dvalues to EOM. */
DUK_LOCAL void duk__debug_skip_to_eom(duk_hthread *thr) {
	for (;;) {
		if (duk__debug_skip_dvalue(thr)) {
			break;
		}
	}
}

/* Read and validate a call stack index.  If index is invalid, write out an
 * error message and return zero.
 */
DUK_LOCAL duk_int32_t duk__debug_read_validate_csindex(duk_hthread *thr) {
	duk_int32_t level;
	level = duk_debug_read_int(thr);
	if (level >= 0 || -level > (duk_int32_t) thr->callstack_top) {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "invalid callstack index");
		return 0; /* zero indicates failure */
	}
	return level;
}

/* Read a call stack index and lookup the corresponding duk_activation.
 * If index is invalid, write out an error message and return NULL.
 */
DUK_LOCAL duk_activation *duk__debug_read_level_get_activation(duk_hthread *thr) {
	duk_activation *act;
	duk_int32_t level;

	level = duk_debug_read_int(thr);
	act = duk_hthread_get_activation_for_level(thr, level);
	if (act == NULL) {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "invalid callstack index");
	}
	return act;
}

/*
 *  Simple commands
 */

DUK_LOCAL void duk__debug_handle_basic_info(duk_hthread *thr, duk_heap *heap) {
	DUK_UNREF(heap);
	DUK_D(DUK_DPRINT("debug command Version"));

	duk_debug_write_reply(thr);
	duk_debug_write_int(thr, DUK_VERSION);
	duk_debug_write_cstring(thr, DUK_GIT_DESCRIBE);
	duk_debug_write_cstring(thr, DUK_USE_TARGET_INFO);
#if defined(DUK_USE_DOUBLE_LE)
	duk_debug_write_int(thr, 1);
#elif defined(DUK_USE_DOUBLE_ME)
	duk_debug_write_int(thr, 2);
#elif defined(DUK_USE_DOUBLE_BE)
	duk_debug_write_int(thr, 3);
#else
	duk_debug_write_int(thr, 0);
#endif
	duk_debug_write_int(thr, (duk_int_t) sizeof(void *));
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_trigger_status(duk_hthread *thr, duk_heap *heap) {
	DUK_UNREF(heap);
	DUK_D(DUK_DPRINT("debug command TriggerStatus"));

	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);
	heap->dbg_state_dirty = 1;
}

DUK_LOCAL void duk__debug_handle_pause(duk_hthread *thr, duk_heap *heap) {
	DUK_D(DUK_DPRINT("debug command Pause"));
	duk_debug_set_paused(heap);
	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_resume(duk_hthread *thr, duk_heap *heap) {
	duk_small_uint_t pause_flags;

	DUK_D(DUK_DPRINT("debug command Resume"));

	duk_debug_clear_paused(heap);

	pause_flags = 0;
#if 0 /* manual testing */
	pause_flags |= DUK_PAUSE_FLAG_ONE_OPCODE;
	pause_flags |= DUK_PAUSE_FLAG_CAUGHT_ERROR;
	pause_flags |= DUK_PAUSE_FLAG_UNCAUGHT_ERROR;
#endif
#if defined(DUK_USE_DEBUGGER_PAUSE_UNCAUGHT)
	pause_flags |= DUK_PAUSE_FLAG_UNCAUGHT_ERROR;
#endif

	duk__debug_set_pause_state(thr, heap, pause_flags);

	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_step(duk_hthread *thr, duk_heap *heap, duk_int32_t cmd) {
	duk_small_uint_t pause_flags;

	DUK_D(DUK_DPRINT("debug command StepInto/StepOver/StepOut: %d", (int) cmd));

	if (cmd == DUK_DBG_CMD_STEPINTO) {
		pause_flags = DUK_PAUSE_FLAG_LINE_CHANGE | DUK_PAUSE_FLAG_FUNC_ENTRY | DUK_PAUSE_FLAG_FUNC_EXIT;
	} else if (cmd == DUK_DBG_CMD_STEPOVER) {
		pause_flags = DUK_PAUSE_FLAG_LINE_CHANGE | DUK_PAUSE_FLAG_FUNC_EXIT;
	} else {
		DUK_ASSERT(cmd == DUK_DBG_CMD_STEPOUT);
		pause_flags = DUK_PAUSE_FLAG_FUNC_EXIT;
	}
#if defined(DUK_USE_DEBUGGER_PAUSE_UNCAUGHT)
	pause_flags |= DUK_PAUSE_FLAG_UNCAUGHT_ERROR;
#endif

	/* If current activation doesn't have line information, line-based
	 * pause flags are automatically disabled.  As a result, e.g.
	 * StepInto will then pause on (native) function entry or exit.
	 */
	duk_debug_clear_paused(heap);
	duk__debug_set_pause_state(thr, heap, pause_flags);

	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_list_break(duk_hthread *thr, duk_heap *heap) {
	duk_small_int_t i;

	DUK_D(DUK_DPRINT("debug command ListBreak"));
	duk_debug_write_reply(thr);
	for (i = 0; i < (duk_small_int_t) heap->dbg_breakpoint_count; i++) {
		duk_debug_write_hstring(thr, heap->dbg_breakpoints[i].filename);
		duk_debug_write_uint(thr, (duk_uint32_t) heap->dbg_breakpoints[i].line);
	}
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_add_break(duk_hthread *thr, duk_heap *heap) {
	duk_hstring *filename;
	duk_uint32_t linenumber;
	duk_small_int_t idx;

	DUK_UNREF(heap);

	filename = duk_debug_read_hstring(thr);
	linenumber = (duk_uint32_t) duk_debug_read_int(thr);
	DUK_D(DUK_DPRINT("debug command AddBreak: %!O:%ld", (duk_hobject *) filename, (long) linenumber));
	idx = duk_debug_add_breakpoint(thr, filename, linenumber);
	if (idx >= 0) {
		duk_debug_write_reply(thr);
		duk_debug_write_int(thr, (duk_int32_t) idx);
		duk_debug_write_eom(thr);
	} else {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_TOOMANY, "no space for breakpoint");
	}
}

DUK_LOCAL void duk__debug_handle_del_break(duk_hthread *thr, duk_heap *heap) {
	duk_small_uint_t idx;

	DUK_UNREF(heap);

	DUK_D(DUK_DPRINT("debug command DelBreak"));
	idx = (duk_small_uint_t) duk_debug_read_int(thr);
	if (duk_debug_remove_breakpoint(thr, idx)) {
		duk_debug_write_reply(thr);
		duk_debug_write_eom(thr);
	} else {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "invalid breakpoint index");
	}
}

DUK_LOCAL void duk__debug_handle_get_var(duk_hthread *thr, duk_heap *heap) {
	duk_activation *act;
	duk_hstring *str;
	duk_bool_t rc;

	DUK_UNREF(heap);
	DUK_D(DUK_DPRINT("debug command GetVar"));

	act = duk__debug_read_level_get_activation(thr);
	if (act == NULL) {
		return;
	}
	str = duk_debug_read_hstring(thr); /* push to stack */
	DUK_ASSERT(str != NULL);

	rc = duk_js_getvar_activation(thr, act, str, 0);

	duk_debug_write_reply(thr);
	if (rc) {
		duk_debug_write_int(thr, 1);
		DUK_ASSERT(duk_get_tval(thr, -2) != NULL);
		duk_debug_write_tval(thr, duk_get_tval(thr, -2));
	} else {
		duk_debug_write_int(thr, 0);
		duk_debug_write_unused(thr);
	}
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_put_var(duk_hthread *thr, duk_heap *heap) {
	duk_activation *act;
	duk_hstring *str;
	duk_tval *tv;

	DUK_UNREF(heap);
	DUK_D(DUK_DPRINT("debug command PutVar"));

	act = duk__debug_read_level_get_activation(thr);
	if (act == NULL) {
		return;
	}
	str = duk_debug_read_hstring(thr); /* push to stack */
	DUK_ASSERT(str != NULL);
	tv = duk_debug_read_tval(thr);
	if (tv == NULL) {
		/* detached */
		return;
	}

	duk_js_putvar_activation(thr, act, str, tv, 0);

	/* XXX: Current putvar implementation doesn't have a success flag,
	 * add one and send to debug client?
	 */
	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_get_call_stack(duk_hthread *thr, duk_heap *heap) {
	duk_hthread *curr_thr = thr;
	duk_activation *curr_act;
	duk_uint_fast32_t pc;
	duk_uint_fast32_t line;

	DUK_ASSERT(thr != NULL);
	DUK_UNREF(heap);

	duk_debug_write_reply(thr);
	while (curr_thr != NULL) {
		for (curr_act = curr_thr->callstack_curr; curr_act != NULL; curr_act = curr_act->parent) {
			/* PC/line semantics here are:
			 *   - For callstack top we're conceptually between two
			 *     opcodes and current PC indicates next line to
			 *     execute, so report that (matches Status).
			 *   - For other activations we're conceptually still
			 *     executing the instruction at PC-1, so report that
			 *     (matches error stacktrace behavior).
			 *   - See: https://github.com/svaarala/duktape/issues/281
			 */

			/* XXX: optimize to use direct reads, i.e. avoid
			 * value stack operations.
			 */
			duk_push_tval(thr, &curr_act->tv_func);
			duk_get_prop_stridx_short(thr, -1, DUK_STRIDX_FILE_NAME);
			duk__debug_write_hstring_safe_top(thr);
			duk_get_prop_stridx_short(thr, -2, DUK_STRIDX_NAME);
			duk__debug_write_hstring_safe_top(thr);
			pc = duk_hthread_get_act_curr_pc(thr, curr_act);
			if (curr_act != curr_thr->callstack_curr && pc > 0) {
				pc--;
			}
			line = duk_hobject_pc2line_query(thr, -3, pc);
			duk_debug_write_uint(thr, (duk_uint32_t) line);
			duk_debug_write_uint(thr, (duk_uint32_t) pc);
			duk_pop_3(thr);
		}
		curr_thr = curr_thr->resumer;
	}
	/* SCANBUILD: warning about 'thr' potentially being NULL here,
	 * warning is incorrect because thr != NULL always here.
	 */
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_get_locals(duk_hthread *thr, duk_heap *heap) {
	duk_activation *act;
	duk_hstring *varname;

	DUK_UNREF(heap);

	act = duk__debug_read_level_get_activation(thr);
	if (act == NULL) {
		return;
	}

	duk_debug_write_reply(thr);

	/* XXX: several nice-to-have improvements here:
	 *   - Use direct reads avoiding value stack operations
	 *   - Avoid triggering getters, indicate getter values to debug client
	 *   - If side effects are possible, add error catching
	 */

	if (DUK_TVAL_IS_OBJECT(&act->tv_func)) {
		duk_hobject *h_func = DUK_TVAL_GET_OBJECT(&act->tv_func);
		duk_hobject *h_varmap;

		h_varmap = duk_hobject_get_varmap(thr, h_func);
		if (h_varmap != NULL) {
			duk_push_hobject(thr, h_varmap);
			duk_enum(thr, -1, 0 /*enum_flags*/);
			while (duk_next(thr, -1 /*enum_index*/, 0 /*get_value*/)) {
				varname = duk_known_hstring(thr, -1);

				duk_js_getvar_activation(thr, act, varname, 0 /*throw_flag*/);
				/* [ ... func varmap enum key value this ] */
				duk_debug_write_hstring(thr, duk_get_hstring(thr, -3));
				duk_debug_write_tval(thr, duk_get_tval(thr, -2));
				duk_pop_3(thr); /* -> [ ... func varmap enum ] */
			}
		} else {
			DUK_D(DUK_DPRINT("varmap missing in GetLocals, ignore"));
		}
	} else {
		DUK_D(DUK_DPRINT("varmap is not an object in GetLocals, ignore"));
	}

	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_eval(duk_hthread *thr, duk_heap *heap) {
	duk_small_uint_t call_flags;
	duk_int_t call_ret;
	duk_small_int_t eval_err;
	duk_bool_t direct_eval;
	duk_int32_t level;
	duk_idx_t idx_func;

	DUK_UNREF(heap);

	DUK_D(DUK_DPRINT("debug command Eval"));

	/* The eval code is executed within the lexical environment of a specified
	 * activation.  For now, use global object eval() function, with the eval
	 * considered a 'direct call to eval'.
	 *
	 * Callstack index for debug commands only affects scope -- the callstack
	 * as seen by, e.g. Duktape.act() will be the same regardless.
	 */

	/* nargs == 2 so we can pass a callstack index to eval(). */
	idx_func = duk_get_top(thr);
	duk_push_c_function(thr, duk_bi_global_object_eval, 2 /*nargs*/);
	duk_push_undefined(thr); /* 'this' binding shouldn't matter here */

	/* Read callstack index, if non-null. */
	if (duk_debug_peek_byte(thr) == DUK_DBG_IB_NULL) {
		direct_eval = 0;
		level = -1; /* Not needed, but silences warning. */
		(void) duk_debug_read_byte(thr);
	} else {
		direct_eval = 1;
		level = duk__debug_read_validate_csindex(thr);
		if (level == 0) {
			return;
		}
	}

	DUK_ASSERT(!direct_eval || (level < 0 && -level <= (duk_int32_t) thr->callstack_top));

	(void) duk_debug_read_hstring(thr);
	if (direct_eval) {
		duk_push_int(thr, level - 1); /* compensate for eval() call */
	}

	/* [ ... eval "eval" eval_input level? ] */

	call_flags = 0;
	if (direct_eval) {
		duk_activation *act;
		duk_hobject *fun;

		act = duk_hthread_get_activation_for_level(thr, level);
		if (act != NULL) {
			fun = DUK_ACT_GET_FUNC(act);
			if (fun != NULL && DUK_HOBJECT_IS_COMPFUNC(fun)) {
				/* Direct eval requires that there's a current
				 * activation and it is an ECMAScript function.
				 * When Eval is executed from e.g. cooperate API
				 * call we'll need to do an indirect eval instead.
				 */
				call_flags |= DUK_CALL_FLAG_DIRECT_EVAL;
			}
		}
	}

	call_ret = duk_pcall_method_flags(thr, duk_get_top(thr) - (idx_func + 2), call_flags);

	if (call_ret == DUK_EXEC_SUCCESS) {
		eval_err = 0;
		/* Use result value as is. */
	} else {
		/* For errors a string coerced result is most informative
		 * right now, as the debug client doesn't have the capability
		 * to traverse the error object.
		 */
		eval_err = 1;
		duk_safe_to_string(thr, -1);
	}

	/* [ ... result ] */

	duk_debug_write_reply(thr);
	duk_debug_write_int(thr, (duk_int32_t) eval_err);
	DUK_ASSERT(duk_get_tval(thr, -1) != NULL);
	duk_debug_write_tval(thr, duk_get_tval(thr, -1));
	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_detach(duk_hthread *thr, duk_heap *heap) {
	DUK_UNREF(heap);
	DUK_D(DUK_DPRINT("debug command Detach"));

	duk_debug_write_reply(thr);
	duk_debug_write_eom(thr);

	DUK_D(DUK_DPRINT("debug connection detached, mark broken"));
	DUK__SET_CONN_BROKEN(thr, 0); /* not an error */
}

DUK_LOCAL void duk__debug_handle_apprequest(duk_hthread *thr, duk_heap *heap) {
	duk_idx_t old_top;

	DUK_D(DUK_DPRINT("debug command AppRequest"));

	old_top = duk_get_top(thr); /* save stack top */

	if (heap->dbg_request_cb != NULL) {
		duk_idx_t nrets;
		duk_idx_t nvalues = 0;
		duk_idx_t top, idx;

		/* Read tvals from the message and push them onto the valstack,
		 * then call the request callback to process the request.
		 */
		while (duk_debug_peek_byte(thr) != DUK_DBG_IB_EOM) {
			duk_tval *tv;
			if (!duk_check_stack(thr, 1)) {
				DUK_D(DUK_DPRINT("failed to allocate space for request dvalue(s)"));
				goto fail;
			}
			tv = duk_debug_read_tval(thr); /* push to stack */
			if (tv == NULL) {
				/* detached */
				return;
			}
			nvalues++;
		}
		DUK_ASSERT(duk_get_top(thr) == old_top + nvalues);

		/* Request callback should push values for reply to client onto valstack */
		DUK_D(DUK_DPRINT("calling into AppRequest request_cb with nvalues=%ld, old_top=%ld, top=%ld",
		                 (long) nvalues,
		                 (long) old_top,
		                 (long) duk_get_top(thr)));
		nrets = heap->dbg_request_cb(thr, heap->dbg_udata, nvalues);
		DUK_D(DUK_DPRINT("returned from AppRequest request_cb; nvalues=%ld -> nrets=%ld, old_top=%ld, top=%ld",
		                 (long) nvalues,
		                 (long) nrets,
		                 (long) old_top,
		                 (long) duk_get_top(thr)));
		if (nrets >= 0) {
			DUK_ASSERT(duk_get_top(thr) >= old_top + nrets);
			if (duk_get_top(thr) < old_top + nrets) {
				DUK_D(DUK_DPRINT("AppRequest callback doesn't match value stack configuration, "
				                 "top=%ld < old_top=%ld + nrets=%ld; "
				                 "this might mean it's unsafe to continue!",
				                 (long) duk_get_top(thr),
				                 (long) old_top,
				                 (long) nrets));
				goto fail;
			}

			/* Reply with tvals pushed by request callback */
			duk_debug_write_byte(thr, DUK_DBG_IB_REPLY);
			top = duk_get_top(thr);
			for (idx = top - nrets; idx < top; idx++) {
				duk_debug_write_tval(thr, DUK_GET_TVAL_POSIDX(thr, idx));
			}
			duk_debug_write_eom(thr);
		} else {
			DUK_ASSERT(duk_get_top(thr) >= old_top + 1);
			if (duk_get_top(thr) < old_top + 1) {
				DUK_D(DUK_DPRINT("request callback return value doesn't match value stack configuration"));
				goto fail;
			}
			duk_debug_write_error_eom(thr, DUK_DBG_ERR_APPLICATION, duk_get_string(thr, -1));
		}

		duk_set_top(thr, old_top); /* restore stack top */
	} else {
		DUK_D(DUK_DPRINT("no request callback, treat AppRequest as unsupported"));
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNSUPPORTED, "AppRequest unsupported by target");
	}

	return;

fail:
	duk_set_top(thr, old_top); /* restore stack top */
	DUK__SET_CONN_BROKEN(thr, 1);
}

/*
 *  DumpHeap command
 */

#if defined(DUK_USE_DEBUGGER_DUMPHEAP)
/* XXX: this has some overlap with object inspection; remove this and make
 * DumpHeap return lists of heapptrs instead?
 */
DUK_LOCAL void duk__debug_dump_heaphdr(duk_hthread *thr, duk_heap *heap, duk_heaphdr *hdr) {
	DUK_UNREF(heap);

	duk_debug_write_heapptr(thr, hdr);
	duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_TYPE(hdr));
	duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_FLAGS_RAW(hdr));
#if defined(DUK_USE_REFERENCE_COUNTING)
	duk_debug_write_uint(thr, (duk_uint32_t) DUK_HEAPHDR_GET_REFCOUNT(hdr));
#else
	duk_debug_write_int(thr, (duk_int32_t) -1);
#endif

	switch (DUK_HEAPHDR_GET_TYPE(hdr)) {
	case DUK_HTYPE_STRING: {
		duk_hstring *h = (duk_hstring *) hdr;

		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HSTRING_GET_BYTELEN(h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HSTRING_GET_CHARLEN(h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HSTRING_GET_HASH(h));
		duk_debug_write_hstring(thr, h);
		break;
	}
	case DUK_HTYPE_OBJECT: {
		duk_hobject *h = (duk_hobject *) hdr;
		duk_hstring *k;
		duk_uint_fast32_t i;

		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_CLASS_NUMBER(h));
		duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_GET_PROTOTYPE(heap, h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ESIZE(h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ENEXT(h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_ASIZE(h));
		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_GET_HSIZE(h));

		for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ENEXT(h); i++) {
			duk_debug_write_uint(thr, (duk_uint32_t) DUK_HOBJECT_E_GET_FLAGS(heap, h, i));
			k = DUK_HOBJECT_E_GET_KEY(heap, h, i);
			duk_debug_write_heapptr(thr, (duk_heaphdr *) k);
			if (k == NULL) {
				duk_debug_write_int(thr, 0); /* isAccessor */
				duk_debug_write_unused(thr);
				continue;
			}
			if (DUK_HOBJECT_E_SLOT_IS_ACCESSOR(heap, h, i)) {
				duk_debug_write_int(thr, 1); /* isAccessor */
				duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.get);
				duk_debug_write_heapptr(thr, (duk_heaphdr *) DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->a.set);
			} else {
				duk_debug_write_int(thr, 0); /* isAccessor */

				duk__debug_write_tval_heapptr(thr, &DUK_HOBJECT_E_GET_VALUE_PTR(heap, h, i)->v);
			}
		}

		for (i = 0; i < (duk_uint_fast32_t) DUK_HOBJECT_GET_ASIZE(h); i++) {
			/* Note: array dump will include elements beyond
			 * 'length'.
			 */
			duk__debug_write_tval_heapptr(thr, DUK_HOBJECT_A_GET_VALUE_PTR(heap, h, i));
		}
		break;
	}
	case DUK_HTYPE_BUFFER: {
		duk_hbuffer *h = (duk_hbuffer *) hdr;

		duk_debug_write_uint(thr, (duk_uint32_t) DUK_HBUFFER_GET_SIZE(h));
		duk_debug_write_buffer(thr, (const char *) DUK_HBUFFER_GET_DATA_PTR(heap, h), (duk_size_t) DUK_HBUFFER_GET_SIZE(h));
		break;
	}
	default: {
		DUK_D(DUK_DPRINT("invalid htype: %d", (int) DUK_HEAPHDR_GET_TYPE(hdr)));
	}
	}
}

DUK_LOCAL void duk__debug_dump_heap_allocated(duk_hthread *thr, duk_heap *heap) {
	duk_heaphdr *hdr;

	hdr = heap->heap_allocated;
	while (hdr != NULL) {
		duk__debug_dump_heaphdr(thr, heap, hdr);
		hdr = DUK_HEAPHDR_GET_NEXT(heap, hdr);
	}
}

DUK_LOCAL void duk__debug_dump_strtab(duk_hthread *thr, duk_heap *heap) {
	duk_uint32_t i;
	duk_hstring *h;

	for (i = 0; i < heap->st_size; i++) {
#if defined(DUK_USE_STRTAB_PTRCOMP)
		h = DUK_USE_HEAPPTR_DEC16((heap)->heap_udata, heap->strtable16[i]);
#else
		h = heap->strtable[i];
#endif
		while (h != NULL) {
			duk__debug_dump_heaphdr(thr, heap, (duk_heaphdr *) h);
			h = h->hdr.h_next;
		}
	}
}

DUK_LOCAL void duk__debug_handle_dump_heap(duk_hthread *thr, duk_heap *heap) {
	DUK_D(DUK_DPRINT("debug command DumpHeap"));

	duk_debug_write_reply(thr);
	duk__debug_dump_heap_allocated(thr, heap);
	duk__debug_dump_strtab(thr, heap);
	duk_debug_write_eom(thr);
}
#endif /* DUK_USE_DEBUGGER_DUMPHEAP */

DUK_LOCAL void duk__debug_handle_get_bytecode(duk_hthread *thr, duk_heap *heap) {
	duk_activation *act;
	duk_hcompfunc *fun = NULL;
	duk_size_t i, n;
	duk_tval *tv;
	duk_hobject **fn;
	duk_int32_t level = -1;
	duk_uint8_t ibyte;

	DUK_UNREF(heap);

	DUK_D(DUK_DPRINT("debug command GetBytecode"));

	ibyte = duk_debug_peek_byte(thr);
	if (ibyte != DUK_DBG_IB_EOM) {
		tv = duk_debug_read_tval(thr);
		if (tv == NULL) {
			/* detached */
			return;
		}
		if (DUK_TVAL_IS_OBJECT(tv)) {
			/* tentative, checked later */
			fun = (duk_hcompfunc *) DUK_TVAL_GET_OBJECT(tv);
			DUK_ASSERT(fun != NULL);
		} else if (DUK_TVAL_IS_NUMBER(tv)) {
			level = (duk_int32_t) DUK_TVAL_GET_NUMBER(tv);
		} else {
			DUK_D(DUK_DPRINT("invalid argument to GetBytecode: %!T", tv));
			goto fail_args;
		}
	}

	if (fun == NULL) {
		act = duk_hthread_get_activation_for_level(thr, level);
		if (act == NULL) {
			goto fail_index;
		}
		fun = (duk_hcompfunc *) DUK_ACT_GET_FUNC(act);
	}

	if (fun == NULL || !DUK_HOBJECT_IS_COMPFUNC((duk_hobject *) fun)) {
		DUK_D(DUK_DPRINT("invalid argument to GetBytecode: %!O", fun));
		goto fail_args;
	}
	DUK_ASSERT(fun != NULL && DUK_HOBJECT_IS_COMPFUNC((duk_hobject *) fun));

	duk_debug_write_reply(thr);
	n = DUK_HCOMPFUNC_GET_CONSTS_COUNT(heap, fun);
	duk_debug_write_int(thr, (duk_int32_t) n);
	tv = DUK_HCOMPFUNC_GET_CONSTS_BASE(heap, fun);
	for (i = 0; i < n; i++) {
		duk_debug_write_tval(thr, tv);
		tv++;
	}
	n = DUK_HCOMPFUNC_GET_FUNCS_COUNT(heap, fun);
	duk_debug_write_int(thr, (duk_int32_t) n);
	fn = DUK_HCOMPFUNC_GET_FUNCS_BASE(heap, fun);
	for (i = 0; i < n; i++) {
		duk_debug_write_hobject(thr, *fn);
		fn++;
	}
	duk_debug_write_string(thr,
	                       (const char *) DUK_HCOMPFUNC_GET_CODE_BASE(heap, fun),
	                       (duk_size_t) DUK_HCOMPFUNC_GET_CODE_SIZE(heap, fun));
	duk_debug_write_eom(thr);
	return;

fail_args:
	duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNKNOWN, "invalid argument");
	return;

fail_index:
	duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "invalid callstack index");
	return;
}

/*
 *  Object inspection commands: GetHeapObjInfo, GetObjPropDesc,
 *  GetObjPropDescRange
 */

#if defined(DUK_USE_DEBUGGER_INSPECT)

#if 0 /* pruned */
DUK_LOCAL const char * const duk__debug_getinfo_heaphdr_keys[] = {
	"reachable",
	"temproot",
	"finalizable",
	"finalized",
	"readonly"
	/* NULL not needed here */
};
DUK_LOCAL duk_uint_t duk__debug_getinfo_heaphdr_masks[] = {
	DUK_HEAPHDR_FLAG_REACHABLE,
	DUK_HEAPHDR_FLAG_TEMPROOT,
	DUK_HEAPHDR_FLAG_FINALIZABLE,
	DUK_HEAPHDR_FLAG_FINALIZED,
	DUK_HEAPHDR_FLAG_READONLY,
	0  /* terminator */
};
#endif
DUK_LOCAL const char * const duk__debug_getinfo_hstring_keys[] = {
#if 0
	"arridx",
	"symbol",
	"hidden",
	"reserved_word",
	"strict_reserved_word",
	"eval_or_arguments",
#endif
	"extdata"
	/* NULL not needed here */
};
DUK_LOCAL duk_uint_t duk__debug_getinfo_hstring_masks[] = {
#if 0
	DUK_HSTRING_FLAG_ARRIDX,
	DUK_HSTRING_FLAG_SYMBOL,
	DUK_HSTRING_FLAG_HIDDEN,
	DUK_HSTRING_FLAG_RESERVED_WORD,
	DUK_HSTRING_FLAG_STRICT_RESERVED_WORD,
	DUK_HSTRING_FLAG_EVAL_OR_ARGUMENTS,
#endif
	DUK_HSTRING_FLAG_EXTDATA,
	0 /* terminator */
};
DUK_LOCAL const char * const duk__debug_getinfo_hobject_keys[] = {
	"extensible",     "constructable", "callable",         "boundfunc",        "compfunc",        "natfunc",     "bufobj",
	"fastrefs",       "array_part",    "strict",           "notail",           "newenv",          "namebinding", "createargs",
	"have_finalizer", "exotic_array",  "exotic_stringobj", "exotic_arguments", "exotic_proxyobj", "special_call"
	/* NULL not needed here */
};
DUK_LOCAL duk_uint_t duk__debug_getinfo_hobject_masks[] = {
	DUK_HOBJECT_FLAG_EXTENSIBLE,      DUK_HOBJECT_FLAG_CONSTRUCTABLE,    DUK_HOBJECT_FLAG_CALLABLE,
	DUK_HOBJECT_FLAG_BOUNDFUNC,       DUK_HOBJECT_FLAG_COMPFUNC,         DUK_HOBJECT_FLAG_NATFUNC,
	DUK_HOBJECT_FLAG_BUFOBJ,          DUK_HOBJECT_FLAG_FASTREFS,         DUK_HOBJECT_FLAG_ARRAY_PART,
	DUK_HOBJECT_FLAG_STRICT,          DUK_HOBJECT_FLAG_NOTAIL,           DUK_HOBJECT_FLAG_NEWENV,
	DUK_HOBJECT_FLAG_NAMEBINDING,     DUK_HOBJECT_FLAG_CREATEARGS,       DUK_HOBJECT_FLAG_HAVE_FINALIZER,
	DUK_HOBJECT_FLAG_EXOTIC_ARRAY,    DUK_HOBJECT_FLAG_EXOTIC_STRINGOBJ, DUK_HOBJECT_FLAG_EXOTIC_ARGUMENTS,
	DUK_HOBJECT_FLAG_EXOTIC_PROXYOBJ, DUK_HOBJECT_FLAG_SPECIAL_CALL,     0 /* terminator */
};
DUK_LOCAL const char * const duk__debug_getinfo_hbuffer_keys[] = {
	"dynamic",
	"external"
	/* NULL not needed here */
};
DUK_LOCAL duk_uint_t duk__debug_getinfo_hbuffer_masks[] = {
	DUK_HBUFFER_FLAG_DYNAMIC,
	DUK_HBUFFER_FLAG_EXTERNAL,
	0 /* terminator */
};

DUK_LOCAL void duk__debug_getinfo_flags_key(duk_hthread *thr, const char *key) {
	duk_debug_write_uint(thr, 0);
	duk_debug_write_cstring(thr, key);
}

DUK_LOCAL void duk__debug_getinfo_prop_uint(duk_hthread *thr, const char *key, duk_uint_t val) {
	duk_debug_write_uint(thr, 0);
	duk_debug_write_cstring(thr, key);
	duk_debug_write_uint(thr, val);
}

DUK_LOCAL void duk__debug_getinfo_prop_int(duk_hthread *thr, const char *key, duk_int_t val) {
	duk_debug_write_uint(thr, 0);
	duk_debug_write_cstring(thr, key);
	duk_debug_write_int(thr, val);
}

DUK_LOCAL void duk__debug_getinfo_prop_bool(duk_hthread *thr, const char *key, duk_bool_t val) {
	duk_debug_write_uint(thr, 0);
	duk_debug_write_cstring(thr, key);
	duk_debug_write_boolean(thr, val);
}

DUK_LOCAL void duk__debug_getinfo_bitmask(duk_hthread *thr, const char * const *keys, duk_uint_t *masks, duk_uint_t flags) {
	const char *key;
	duk_uint_t mask;

	for (;;) {
		mask = *masks++;
		if (mask == 0) {
			break;
		}
		key = *keys++;
		DUK_ASSERT(key != NULL);

		DUK_DD(DUK_DDPRINT("inspect bitmask: key=%s, mask=0x%08lx, flags=0x%08lx",
		                   key,
		                   (unsigned long) mask,
		                   (unsigned long) flags));
		duk__debug_getinfo_prop_bool(thr, key, flags & mask);
	}
}

/* Inspect a property using a virtual index into a conceptual property list
 * consisting of (1) all array part items from [0,a_size[ (even when above
 * .length) and (2) all entry part items from [0,e_next[.  Unused slots are
 * indicated using dvalue 'unused'.
 */
DUK_LOCAL duk_bool_t duk__debug_getprop_index(duk_hthread *thr, duk_heap *heap, duk_hobject *h_obj, duk_uint_t idx) {
	duk_uint_t a_size;
	duk_tval *tv;
	duk_hstring *h_key;
	duk_hobject *h_getset;
	duk_uint_t flags;

	DUK_UNREF(heap);

	a_size = DUK_HOBJECT_GET_ASIZE(h_obj);
	if (idx < a_size) {
		duk_debug_write_uint(thr, DUK_PROPDESC_FLAGS_WEC);
		duk_debug_write_uint(thr, idx);
		tv = DUK_HOBJECT_A_GET_VALUE_PTR(heap, h_obj, idx);
		duk_debug_write_tval(thr, tv);
		return 1;
	}

	idx -= a_size;
	if (idx >= DUK_HOBJECT_GET_ENEXT(h_obj)) {
		return 0;
	}

	h_key = DUK_HOBJECT_E_GET_KEY(heap, h_obj, idx);
	if (h_key == NULL) {
		duk_debug_write_uint(thr, 0);
		duk_debug_write_null(thr);
		duk_debug_write_unused(thr);
		return 1;
	}

	flags = DUK_HOBJECT_E_GET_FLAGS(heap, h_obj, idx);
	if (DUK_HSTRING_HAS_SYMBOL(h_key)) {
		flags |= DUK_DBG_PROPFLAG_SYMBOL;
	}
	if (DUK_HSTRING_HAS_HIDDEN(h_key)) {
		flags |= DUK_DBG_PROPFLAG_HIDDEN;
	}
	duk_debug_write_uint(thr, flags);
	duk_debug_write_hstring(thr, h_key);
	if (flags & DUK_PROPDESC_FLAG_ACCESSOR) {
		h_getset = DUK_HOBJECT_E_GET_VALUE_GETTER(heap, h_obj, idx);
		if (h_getset) {
			duk_debug_write_hobject(thr, h_getset);
		} else {
			duk_debug_write_null(thr);
		}
		h_getset = DUK_HOBJECT_E_GET_VALUE_SETTER(heap, h_obj, idx);
		if (h_getset) {
			duk_debug_write_hobject(thr, h_getset);
		} else {
			duk_debug_write_null(thr);
		}
	} else {
		tv = DUK_HOBJECT_E_GET_VALUE_TVAL_PTR(heap, h_obj, idx);
		duk_debug_write_tval(thr, tv);
	}
	return 1;
}

DUK_LOCAL void duk__debug_handle_get_heap_obj_info(duk_hthread *thr, duk_heap *heap) {
	duk_heaphdr *h;

	DUK_D(DUK_DPRINT("debug command GetHeapObjInfo"));
	DUK_UNREF(heap);

	DUK_ASSERT(sizeof(duk__debug_getinfo_hstring_keys) / sizeof(const char *) ==
	           sizeof(duk__debug_getinfo_hstring_masks) / sizeof(duk_uint_t) - 1);
	DUK_ASSERT(sizeof(duk__debug_getinfo_hobject_keys) / sizeof(const char *) ==
	           sizeof(duk__debug_getinfo_hobject_masks) / sizeof(duk_uint_t) - 1);
	DUK_ASSERT(sizeof(duk__debug_getinfo_hbuffer_keys) / sizeof(const char *) ==
	           sizeof(duk__debug_getinfo_hbuffer_masks) / sizeof(duk_uint_t) - 1);

	h = duk_debug_read_any_ptr(thr);
	if (!h) {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNKNOWN, "invalid target");
		return;
	}

	duk_debug_write_reply(thr);

	/* As with all inspection code, we rely on the debug client providing
	 * a valid, non-stale pointer: there's no portable way to safely
	 * validate the pointer here.
	 */

	duk__debug_getinfo_flags_key(thr, "heapptr");
	duk_debug_write_heapptr(thr, h);

	/* XXX: comes out as signed now */
	duk__debug_getinfo_prop_uint(thr, "heaphdr_flags", (duk_uint_t) DUK_HEAPHDR_GET_FLAGS(h));
	duk__debug_getinfo_prop_uint(thr, "heaphdr_type", (duk_uint_t) DUK_HEAPHDR_GET_TYPE(h));
#if defined(DUK_USE_REFERENCE_COUNTING)
	duk__debug_getinfo_prop_uint(thr, "refcount", (duk_uint_t) DUK_HEAPHDR_GET_REFCOUNT(h));
#endif
#if 0 /* pruned */
	duk__debug_getinfo_bitmask(thr,
	                           duk__debug_getinfo_heaphdr_keys,
	                           duk__debug_getinfo_heaphdr_masks,
	                           DUK_HEAPHDR_GET_FLAGS_RAW(h));
#endif

	switch (DUK_HEAPHDR_GET_TYPE(h)) {
	case DUK_HTYPE_STRING: {
		duk_hstring *h_str;

		h_str = (duk_hstring *) h;
		duk__debug_getinfo_bitmask(thr,
		                           duk__debug_getinfo_hstring_keys,
		                           duk__debug_getinfo_hstring_masks,
		                           DUK_HEAPHDR_GET_FLAGS_RAW(h));
		duk__debug_getinfo_prop_uint(thr, "bytelen", (duk_uint_t) DUK_HSTRING_GET_BYTELEN(h_str));
		duk__debug_getinfo_prop_uint(thr, "charlen", (duk_uint_t) DUK_HSTRING_GET_CHARLEN(h_str));
		duk__debug_getinfo_prop_uint(thr, "hash", (duk_uint_t) DUK_HSTRING_GET_HASH(h_str));
		duk__debug_getinfo_flags_key(thr, "data");
		duk_debug_write_hstring(thr, h_str);
		break;
	}
	case DUK_HTYPE_OBJECT: {
		duk_hobject *h_obj;
		duk_hobject *h_proto;

		h_obj = (duk_hobject *) h;
		h_proto = DUK_HOBJECT_GET_PROTOTYPE(heap, h_obj);

		/* duk_hobject specific fields. */
		duk__debug_getinfo_bitmask(thr,
		                           duk__debug_getinfo_hobject_keys,
		                           duk__debug_getinfo_hobject_masks,
		                           DUK_HEAPHDR_GET_FLAGS_RAW(h));
		duk__debug_getinfo_prop_uint(thr, "class_number", DUK_HOBJECT_GET_CLASS_NUMBER(h_obj));
		duk__debug_getinfo_flags_key(thr, "class_name");
		duk_debug_write_hstring(thr, DUK_HOBJECT_GET_CLASS_STRING(heap, h_obj));
		duk__debug_getinfo_flags_key(thr, "prototype");
		if (h_proto != NULL) {
			duk_debug_write_hobject(thr, h_proto);
		} else {
			duk_debug_write_null(thr);
		}
		duk__debug_getinfo_flags_key(thr, "props");
		duk_debug_write_pointer(thr, (void *) DUK_HOBJECT_GET_PROPS(heap, h_obj));
		duk__debug_getinfo_prop_uint(thr, "e_size", (duk_uint_t) DUK_HOBJECT_GET_ESIZE(h_obj));
		duk__debug_getinfo_prop_uint(thr, "e_next", (duk_uint_t) DUK_HOBJECT_GET_ENEXT(h_obj));
		duk__debug_getinfo_prop_uint(thr, "a_size", (duk_uint_t) DUK_HOBJECT_GET_ASIZE(h_obj));
		duk__debug_getinfo_prop_uint(thr, "h_size", (duk_uint_t) DUK_HOBJECT_GET_HSIZE(h_obj));

		if (DUK_HOBJECT_IS_ARRAY(h_obj)) {
			duk_harray *h_arr;
			h_arr = (duk_harray *) h_obj;

			duk__debug_getinfo_prop_uint(thr, "length", (duk_uint_t) h_arr->length);
			duk__debug_getinfo_prop_bool(thr, "length_nonwritable", h_arr->length_nonwritable);
		}

		if (DUK_HOBJECT_IS_NATFUNC(h_obj)) {
			duk_hnatfunc *h_fun;
			h_fun = (duk_hnatfunc *) h_obj;

			duk__debug_getinfo_prop_int(thr, "nargs", h_fun->nargs);
			duk__debug_getinfo_prop_int(thr, "magic", h_fun->magic);
			duk__debug_getinfo_prop_bool(thr, "varargs", h_fun->magic == DUK_HNATFUNC_NARGS_VARARGS);
			/* Native function pointer may be different from a void pointer,
			 * and we serialize it from memory directly now (no byte swapping etc).
			 */
			duk__debug_getinfo_flags_key(thr, "funcptr");
			duk_debug_write_buffer(thr, (const char *) &h_fun->func, sizeof(h_fun->func));
		}

		if (DUK_HOBJECT_IS_COMPFUNC(h_obj)) {
			duk_hcompfunc *h_fun;
			duk_hbuffer *h_buf;
			duk_hobject *h_lexenv;
			duk_hobject *h_varenv;
			h_fun = (duk_hcompfunc *) h_obj;

			duk__debug_getinfo_prop_int(thr, "nregs", h_fun->nregs);
			duk__debug_getinfo_prop_int(thr, "nargs", h_fun->nargs);

			duk__debug_getinfo_flags_key(thr, "lex_env");
			h_lexenv = DUK_HCOMPFUNC_GET_LEXENV(thr->heap, h_fun);
			if (h_lexenv != NULL) {
				duk_debug_write_hobject(thr, h_lexenv);
			} else {
				duk_debug_write_null(thr);
			}
			duk__debug_getinfo_flags_key(thr, "var_env");
			h_varenv = DUK_HCOMPFUNC_GET_VARENV(thr->heap, h_fun);
			if (h_varenv != NULL) {
				duk_debug_write_hobject(thr, h_varenv);
			} else {
				duk_debug_write_null(thr);
			}

			duk__debug_getinfo_prop_uint(thr, "start_line", h_fun->start_line);
			duk__debug_getinfo_prop_uint(thr, "end_line", h_fun->end_line);
			h_buf = (duk_hbuffer *) DUK_HCOMPFUNC_GET_DATA(thr->heap, h_fun);
			if (h_buf != NULL) {
				duk__debug_getinfo_flags_key(thr, "data");
				duk_debug_write_heapptr(thr, (duk_heaphdr *) h_buf);
			}
		}

		if (DUK_HOBJECT_IS_BOUNDFUNC(h_obj)) {
			duk_hboundfunc *h_bfun;
			h_bfun = (duk_hboundfunc *) (void *) h_obj;

			duk__debug_getinfo_flags_key(thr, "target");
			duk_debug_write_tval(thr, &h_bfun->target);
			duk__debug_getinfo_flags_key(thr, "this_binding");
			duk_debug_write_tval(thr, &h_bfun->this_binding);
			duk__debug_getinfo_flags_key(thr, "nargs");
			duk_debug_write_int(thr, h_bfun->nargs);
			/* h_bfun->args not exposed now */
		}

		if (DUK_HOBJECT_IS_THREAD(h_obj)) {
			/* XXX: Currently no inspection of threads, e.g. value stack, call
			 * stack, catch stack, etc.
			 */
			duk_hthread *h_thr;
			h_thr = (duk_hthread *) h_obj;
			DUK_UNREF(h_thr);
		}

		if (DUK_HOBJECT_IS_DECENV(h_obj)) {
			duk_hdecenv *h_env;
			h_env = (duk_hdecenv *) h_obj;

			duk__debug_getinfo_flags_key(thr, "thread");
			duk_debug_write_heapptr(thr, (duk_heaphdr *) (h_env->thread));
			duk__debug_getinfo_flags_key(thr, "varmap");
			duk_debug_write_heapptr(thr, (duk_heaphdr *) (h_env->varmap));
			duk__debug_getinfo_prop_uint(thr, "regbase", (duk_uint_t) h_env->regbase_byteoff);
		}

		if (DUK_HOBJECT_IS_OBJENV(h_obj)) {
			duk_hobjenv *h_env;
			h_env = (duk_hobjenv *) h_obj;

			duk__debug_getinfo_flags_key(thr, "target");
			duk_debug_write_heapptr(thr, (duk_heaphdr *) (h_env->target));
			duk__debug_getinfo_prop_bool(thr, "has_this", h_env->has_this);
		}

#if defined(DUK_USE_BUFFEROBJECT_SUPPORT)
		if (DUK_HOBJECT_IS_BUFOBJ(h_obj)) {
			duk_hbufobj *h_bufobj;
			h_bufobj = (duk_hbufobj *) h_obj;

			duk__debug_getinfo_prop_uint(thr, "slice_offset", h_bufobj->offset);
			duk__debug_getinfo_prop_uint(thr, "slice_length", h_bufobj->length);
			duk__debug_getinfo_prop_uint(thr, "elem_shift", (duk_uint_t) h_bufobj->shift);
			duk__debug_getinfo_prop_uint(thr, "elem_type", (duk_uint_t) h_bufobj->elem_type);
			duk__debug_getinfo_prop_bool(thr, "is_typedarray", (duk_uint_t) h_bufobj->is_typedarray);
			if (h_bufobj->buf != NULL) {
				duk__debug_getinfo_flags_key(thr, "buffer");
				duk_debug_write_heapptr(thr, (duk_heaphdr *) h_bufobj->buf);
			}
		}
#endif /* DUK_USE_BUFFEROBJECT_SUPPORT */
		break;
	}
	case DUK_HTYPE_BUFFER: {
		duk_hbuffer *h_buf;

		h_buf = (duk_hbuffer *) h;
		duk__debug_getinfo_bitmask(thr,
		                           duk__debug_getinfo_hbuffer_keys,
		                           duk__debug_getinfo_hbuffer_masks,
		                           DUK_HEAPHDR_GET_FLAGS_RAW(h));
		duk__debug_getinfo_prop_uint(thr, "size", (duk_uint_t) DUK_HBUFFER_GET_SIZE(h_buf));
		duk__debug_getinfo_flags_key(thr, "dataptr");
		duk_debug_write_pointer(thr, (void *) DUK_HBUFFER_GET_DATA_PTR(thr->heap, h_buf));
		duk__debug_getinfo_flags_key(thr, "data");
		duk_debug_write_hbuffer(thr, h_buf); /* tolerates NULL h_buf */
		break;
	}
	default: {
		/* Since we already started writing the reply, just emit nothing. */
		DUK_D(DUK_DPRINT("inspect target pointer has invalid heaphdr type"));
	}
	}

	duk_debug_write_eom(thr);
}

DUK_LOCAL void duk__debug_handle_get_obj_prop_desc(duk_hthread *thr, duk_heap *heap) {
	duk_heaphdr *h;
	duk_hobject *h_obj;
	duk_hstring *h_key;
	duk_propdesc desc;

	DUK_D(DUK_DPRINT("debug command GetObjPropDesc"));
	DUK_UNREF(heap);

	h = duk_debug_read_any_ptr(thr);
	if (!h) {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNKNOWN, "invalid target");
		return;
	}
	h_key = duk_debug_read_hstring(thr);
	if (h == NULL || DUK_HEAPHDR_GET_TYPE(h) != DUK_HTYPE_OBJECT || h_key == NULL) {
		goto fail_args;
	}
	h_obj = (duk_hobject *) h;

	if (duk_hobject_get_own_propdesc(thr, h_obj, h_key, &desc, 0 /*flags*/)) {
		duk_int_t virtual_idx;
		duk_bool_t rc;

		/* To use the shared helper need the virtual index. */
		DUK_ASSERT(desc.e_idx >= 0 || desc.a_idx >= 0);
		virtual_idx = (desc.a_idx >= 0 ? desc.a_idx : (duk_int_t) DUK_HOBJECT_GET_ASIZE(h_obj) + desc.e_idx);

		duk_debug_write_reply(thr);
		rc = duk__debug_getprop_index(thr, heap, h_obj, (duk_uint_t) virtual_idx);
		DUK_ASSERT(rc == 1);
		DUK_UNREF(rc);
		duk_debug_write_eom(thr);
	} else {
		duk_debug_write_error_eom(thr, DUK_DBG_ERR_NOTFOUND, "not found");
	}
	return;

fail_args:
	duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNKNOWN, "invalid args");
}

DUK_LOCAL void duk__debug_handle_get_obj_prop_desc_range(duk_hthread *thr, duk_heap *heap) {
	duk_heaphdr *h;
	duk_hobject *h_obj;
	duk_uint_t idx, idx_start, idx_end;

	DUK_D(DUK_DPRINT("debug command GetObjPropDescRange"));
	DUK_UNREF(heap);

	h = duk_debug_read_any_ptr(thr);
	idx_start = (duk_uint_t) duk_debug_read_int(thr);
	idx_end = (duk_uint_t) duk_debug_read_int(thr);
	if (h == NULL || DUK_HEAPHDR_GET_TYPE(h) != DUK_HTYPE_OBJECT) {
		goto fail_args;
	}
	h_obj = (duk_hobject *) h;

	/* The index range space is conceptually the array part followed by the
	 * entry part.  Unlike normal enumeration all slots are exposed here as
	 * is and return 'unused' if the slots are not in active use.  In particular
	 * the array part is included for the full a_size regardless of what the
	 * array .length is.
	 */

	duk_debug_write_reply(thr);
	for (idx = idx_start; idx < idx_end; idx++) {
		if (!duk__debug_getprop_index(thr, heap, h_obj, idx)) {
			break;
		}
	}
	duk_debug_write_eom(thr);
	return;

fail_args:
	duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNKNOWN, "invalid args");
}

#endif /* DUK_USE_DEBUGGER_INSPECT */

/*
 *  Process incoming debug requests
 *
 *  Individual request handlers can push temporaries on the value stack and
 *  rely on duk__debug_process_message() to restore the value stack top
 *  automatically.
 */

/* Process one debug message.  Automatically restore value stack top to its
 * entry value, so that individual message handlers don't need exact value
 * stack handling which is convenient.
 */
DUK_LOCAL void duk__debug_process_message(duk_hthread *thr) {
	duk_heap *heap;
	duk_uint8_t x;
	duk_int32_t cmd;
	duk_idx_t entry_top;

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	entry_top = duk_get_top(thr);

	x = duk_debug_read_byte(thr);
	switch (x) {
	case DUK_DBG_IB_REQUEST: {
		cmd = duk_debug_read_int(thr);
		switch (cmd) {
		case DUK_DBG_CMD_BASICINFO: {
			duk__debug_handle_basic_info(thr, heap);
			break;
		}
		case DUK_DBG_CMD_TRIGGERSTATUS: {
			duk__debug_handle_trigger_status(thr, heap);
			break;
		}
		case DUK_DBG_CMD_PAUSE: {
			duk__debug_handle_pause(thr, heap);
			break;
		}
		case DUK_DBG_CMD_RESUME: {
			duk__debug_handle_resume(thr, heap);
			break;
		}
		case DUK_DBG_CMD_STEPINTO:
		case DUK_DBG_CMD_STEPOVER:
		case DUK_DBG_CMD_STEPOUT: {
			duk__debug_handle_step(thr, heap, cmd);
			break;
		}
		case DUK_DBG_CMD_LISTBREAK: {
			duk__debug_handle_list_break(thr, heap);
			break;
		}
		case DUK_DBG_CMD_ADDBREAK: {
			duk__debug_handle_add_break(thr, heap);
			break;
		}
		case DUK_DBG_CMD_DELBREAK: {
			duk__debug_handle_del_break(thr, heap);
			break;
		}
		case DUK_DBG_CMD_GETVAR: {
			duk__debug_handle_get_var(thr, heap);
			break;
		}
		case DUK_DBG_CMD_PUTVAR: {
			duk__debug_handle_put_var(thr, heap);
			break;
		}
		case DUK_DBG_CMD_GETCALLSTACK: {
			duk__debug_handle_get_call_stack(thr, heap);
			break;
		}
		case DUK_DBG_CMD_GETLOCALS: {
			duk__debug_handle_get_locals(thr, heap);
			break;
		}
		case DUK_DBG_CMD_EVAL: {
			duk__debug_handle_eval(thr, heap);
			break;
		}
		case DUK_DBG_CMD_DETACH: {
			/* The actual detached_cb call is postponed to message loop so
			 * we don't need any special precautions here (just skip to EOM
			 * on the already closed connection).
			 */
			duk__debug_handle_detach(thr, heap);
			break;
		}
#if defined(DUK_USE_DEBUGGER_DUMPHEAP)
		case DUK_DBG_CMD_DUMPHEAP: {
			duk__debug_handle_dump_heap(thr, heap);
			break;
		}
#endif /* DUK_USE_DEBUGGER_DUMPHEAP */
		case DUK_DBG_CMD_GETBYTECODE: {
			duk__debug_handle_get_bytecode(thr, heap);
			break;
		}
		case DUK_DBG_CMD_APPREQUEST: {
			duk__debug_handle_apprequest(thr, heap);
			break;
		}
#if defined(DUK_USE_DEBUGGER_INSPECT)
		case DUK_DBG_CMD_GETHEAPOBJINFO: {
			duk__debug_handle_get_heap_obj_info(thr, heap);
			break;
		}
		case DUK_DBG_CMD_GETOBJPROPDESC: {
			duk__debug_handle_get_obj_prop_desc(thr, heap);
			break;
		}
		case DUK_DBG_CMD_GETOBJPROPDESCRANGE: {
			duk__debug_handle_get_obj_prop_desc_range(thr, heap);
			break;
		}
#endif /* DUK_USE_DEBUGGER_INSPECT */
		default: {
			DUK_D(DUK_DPRINT("debug command unsupported: %d", (int) cmd));
			duk_debug_write_error_eom(thr, DUK_DBG_ERR_UNSUPPORTED, "unsupported command");
		}
		} /* switch cmd */
		break;
	}
	case DUK_DBG_IB_REPLY: {
		DUK_D(DUK_DPRINT("debug reply, skipping"));
		break;
	}
	case DUK_DBG_IB_ERROR: {
		DUK_D(DUK_DPRINT("debug error, skipping"));
		break;
	}
	case DUK_DBG_IB_NOTIFY: {
		DUK_D(DUK_DPRINT("debug notify, skipping"));
		break;
	}
	default: {
		DUK_D(DUK_DPRINT("invalid initial byte, drop connection: %d", (int) x));
		goto fail;
	}
	} /* switch initial byte */

	DUK_ASSERT(duk_get_top(thr) >= entry_top);
	duk_set_top(thr, entry_top);
	duk__debug_skip_to_eom(thr);
	return;

fail:
	DUK_ASSERT(duk_get_top(thr) >= entry_top);
	duk_set_top(thr, entry_top);
	DUK__SET_CONN_BROKEN(thr, 1);
	return;
}

DUK_LOCAL void duk__check_resend_status(duk_hthread *thr) {
	if (thr->heap->dbg_read_cb != NULL && thr->heap->dbg_state_dirty) {
		duk_debug_send_status(thr);
		thr->heap->dbg_state_dirty = 0;
	}
}

DUK_INTERNAL duk_bool_t duk_debug_process_messages(duk_hthread *thr, duk_bool_t no_block) {
#if defined(DUK_USE_ASSERTIONS)
	duk_idx_t entry_top;
#endif
	duk_bool_t retval = 0;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);
#if defined(DUK_USE_ASSERTIONS)
	entry_top = duk_get_top(thr);
#endif

	DUK_D(DUK_DPRINT("process debug messages: read_cb=%s, no_block=%ld, detaching=%ld, processing=%ld",
	                 thr->heap->dbg_read_cb ? "not NULL" : "NULL",
	                 (long) no_block,
	                 (long) thr->heap->dbg_detaching,
	                 (long) thr->heap->dbg_processing));
	DUK_DD(DUK_DDPRINT("top at entry: %ld", (long) duk_get_top(thr)));

	/* thr->heap->dbg_detaching may be != 0 if a debugger write outside
	 * the message loop caused a transport error and detach1() to run.
	 */
	DUK_ASSERT(thr->heap->dbg_detaching == 0 || thr->heap->dbg_detaching == 1);
	DUK_ASSERT(thr->heap->dbg_processing == 0);
	thr->heap->dbg_processing = 1;

	/* Ensure dirty state causes a Status even if never process any
	 * messages.  This is expected by the bytecode executor when in
	 * the running state.
	 */
	duk__check_resend_status(thr);

	for (;;) {
		/* Process messages until we're no longer paused or we peek
		 * and see there's nothing to read right now.
		 */
		DUK_DD(DUK_DDPRINT("top at loop top: %ld", (long) duk_get_top(thr)));
		DUK_ASSERT(thr->heap->dbg_processing == 1);

		while (thr->heap->dbg_read_cb == NULL && thr->heap->dbg_detaching) {
			/* Detach is pending; can be triggered from outside the
			 * debugger loop (e.g. Status notify write error) or by
			 * previous message handling.  Call detached callback
			 * here, in a controlled state, to ensure a possible
			 * reattach inside the detached_cb is handled correctly.
			 *
			 * Recheck for detach in a while loop: an immediate
			 * reattach involves a call to duk_debugger_attach()
			 * which writes a debugger handshake line immediately
			 * inside the API call.  If the transport write fails
			 * for that handshake, we can immediately end up in a
			 * "transport broken, detaching" case several times here.
			 * Loop back until we're either cleanly attached or
			 * fully detached.
			 *
			 * NOTE: Reset dbg_processing = 1 forcibly, in case we
			 * re-attached; duk_debugger_attach() sets dbg_processing
			 * to 0 at the moment.
			 */

			DUK_D(DUK_DPRINT("detach pending (dbg_read_cb == NULL, dbg_detaching != 0), call detach2"));

			duk__debug_do_detach2(thr->heap);
			thr->heap->dbg_processing = 1; /* may be set to 0 by duk_debugger_attach() inside callback */

			DUK_D(DUK_DPRINT("after detach2 (and possible reattach): dbg_read_cb=%s, dbg_detaching=%ld",
			                 thr->heap->dbg_read_cb ? "not NULL" : "NULL",
			                 (long) thr->heap->dbg_detaching));
		}
		DUK_ASSERT(thr->heap->dbg_detaching == 0); /* true even with reattach */
		DUK_ASSERT(thr->heap->dbg_processing == 1); /* even after a detach and possible reattach */

		if (thr->heap->dbg_read_cb == NULL) {
			DUK_D(DUK_DPRINT("debug connection broken (and not detaching), stop processing messages"));
			break;
		}

		if (!DUK_HEAP_HAS_DEBUGGER_PAUSED(thr->heap) || no_block) {
			if (!duk_debug_read_peek(thr)) {
				/* Note: peek cannot currently trigger a detach
				 * so the dbg_detaching == 0 assert outside the
				 * loop is correct.
				 */
				DUK_D(DUK_DPRINT("processing debug message, peek indicated no data, stop processing messages"));
				break;
			}
			DUK_D(DUK_DPRINT("processing debug message, peek indicated there is data, handle it"));
		} else {
			DUK_D(DUK_DPRINT("paused, process debug message, blocking if necessary"));
		}

		duk__check_resend_status(thr);
		duk__debug_process_message(thr);
		duk__check_resend_status(thr);

		retval = 1; /* processed one or more messages */
	}

	DUK_ASSERT(thr->heap->dbg_detaching == 0);
	DUK_ASSERT(thr->heap->dbg_processing == 1);
	thr->heap->dbg_processing = 0;

	/* As an initial implementation, read flush after exiting the message
	 * loop.  If transport is broken, this is a no-op (with debug logs).
	 */
	duk_debug_read_flush(thr); /* this cannot initiate a detach */
	DUK_ASSERT(thr->heap->dbg_detaching == 0);

	DUK_DD(DUK_DDPRINT("top at exit: %ld", (long) duk_get_top(thr)));

#if defined(DUK_USE_ASSERTIONS)
	/* Easy to get wrong, so assert for it. */
	DUK_ASSERT(entry_top == duk_get_top(thr));
#endif

	return retval;
}

/*
 *  Halt execution helper
 */

/* Halt execution and enter a debugger message loop until execution is resumed
 * by the client.  PC for the current activation may be temporarily decremented
 * so that the "current" instruction will be shown by the client.  This helper
 * is callable from anywhere, also outside bytecode executor.
 */

DUK_INTERNAL void duk_debug_halt_execution(duk_hthread *thr, duk_bool_t use_prev_pc) {
	duk_activation *act;
	duk_hcompfunc *fun;
	duk_instr_t *old_pc = NULL;

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(thr->heap != NULL);
	DUK_ASSERT(duk_debug_is_attached(thr->heap));
	DUK_ASSERT(thr->heap->dbg_processing == 0);
	DUK_ASSERT(!duk_debug_is_paused(thr->heap));

	duk_debug_set_paused(thr->heap);

	act = thr->callstack_curr;

	/* NOTE: act may be NULL if an error is thrown outside of any activation,
	 * which may happen in the case of, e.g. syntax errors.
	 */

	/* Decrement PC if that was requested, this requires a PC sync. */
	if (act != NULL) {
		duk_hthread_sync_currpc(thr);
		old_pc = act->curr_pc;
		fun = (duk_hcompfunc *) DUK_ACT_GET_FUNC(act);

		/* Short circuit if is safe: if act->curr_pc != NULL, 'fun' is
		 * guaranteed to be a non-NULL ECMAScript function.
		 */
		DUK_ASSERT(act->curr_pc == NULL || (fun != NULL && DUK_HOBJECT_IS_COMPFUNC((duk_hobject *) fun)));
		if (use_prev_pc && act->curr_pc != NULL && act->curr_pc > DUK_HCOMPFUNC_GET_CODE_BASE(thr->heap, fun)) {
			act->curr_pc--;
		}
	}

	/* Process debug messages until we are no longer paused. */

	/* NOTE: This is a bit fragile.  It's important to ensure that
	 * duk_debug_process_messages() never throws an error or
	 * act->curr_pc will never be reset.
	 */

	thr->heap->dbg_state_dirty = 1;
	while (DUK_HEAP_HAS_DEBUGGER_PAUSED(thr->heap)) {
		DUK_ASSERT(duk_debug_is_attached(thr->heap));
		DUK_ASSERT(thr->heap->dbg_processing == 0);
		duk_debug_process_messages(thr, 0 /*no_block*/);
	}

	/* XXX: Decrementing and restoring act->curr_pc works now, but if the
	 * debugger message loop gains the ability to adjust the current PC
	 * (e.g. a forced jump) restoring the PC here will break.  Another
	 * approach would be to use a state flag for the "decrement 1 from
	 * topmost activation's PC" and take it into account whenever dealing
	 * with PC values.
	 */
	if (act != NULL) {
		act->curr_pc = old_pc; /* restore PC */
	}
}

/*
 *  Breakpoint management
 */

DUK_INTERNAL duk_small_int_t duk_debug_add_breakpoint(duk_hthread *thr, duk_hstring *filename, duk_uint32_t line) {
	duk_heap *heap;
	duk_breakpoint *b;

	/* Caller must trigger recomputation of active breakpoint list.  To
	 * ensure stale values are not used if that doesn't happen, clear the
	 * active breakpoint list here.
	 */

	DUK_ASSERT(thr != NULL);
	DUK_ASSERT(filename != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);

	if (heap->dbg_breakpoint_count >= DUK_HEAP_MAX_BREAKPOINTS) {
		DUK_D(DUK_DPRINT("failed to add breakpoint for %O:%ld, all breakpoint slots used",
		                 (duk_heaphdr *) filename,
		                 (long) line));
		return -1;
	}
	heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;
	b = heap->dbg_breakpoints + (heap->dbg_breakpoint_count++);
	b->filename = filename;
	b->line = line;
	DUK_HSTRING_INCREF(thr, filename);

	return (duk_small_int_t) (heap->dbg_breakpoint_count - 1); /* index */
}

DUK_INTERNAL duk_bool_t duk_debug_remove_breakpoint(duk_hthread *thr, duk_small_uint_t breakpoint_index) {
	duk_heap *heap;
	duk_hstring *h;
	duk_breakpoint *b;
	duk_size_t move_size;

	/* Caller must trigger recomputation of active breakpoint list.  To
	 * ensure stale values are not used if that doesn't happen, clear the
	 * active breakpoint list here.
	 */

	DUK_ASSERT(thr != NULL);
	heap = thr->heap;
	DUK_ASSERT(heap != NULL);
	DUK_ASSERT(duk_debug_is_attached(thr->heap));
	DUK_ASSERT_DISABLE(breakpoint_index >= 0); /* unsigned */

	if (breakpoint_index >= heap->dbg_breakpoint_count) {
		DUK_D(DUK_DPRINT("invalid breakpoint index: %ld", (long) breakpoint_index));
		return 0;
	}
	b = heap->dbg_breakpoints + breakpoint_index;

	h = b->filename;
	DUK_ASSERT(h != NULL);

	move_size = sizeof(duk_breakpoint) * (heap->dbg_breakpoint_count - breakpoint_index - 1);
	duk_memmove((void *) b, (const void *) (b + 1), (size_t) move_size);

	heap->dbg_breakpoint_count--;
	heap->dbg_breakpoints_active[0] = (duk_breakpoint *) NULL;

	DUK_HSTRING_DECREF(thr, h); /* side effects */
	DUK_UNREF(h); /* w/o refcounting */

	/* Breakpoint entries above the used area are left as garbage. */

	return 1;
}

/*
 *  Misc state management
 */

DUK_INTERNAL duk_bool_t duk_debug_is_attached(duk_heap *heap) {
	return (heap->dbg_read_cb != NULL);
}

DUK_INTERNAL duk_bool_t duk_debug_is_paused(duk_heap *heap) {
	return (DUK_HEAP_HAS_DEBUGGER_PAUSED(heap) != 0);
}

DUK_INTERNAL void duk_debug_set_paused(duk_heap *heap) {
	if (duk_debug_is_paused(heap)) {
		DUK_D(DUK_DPRINT("trying to set paused state when already paused, ignoring"));
	} else {
		DUK_HEAP_SET_DEBUGGER_PAUSED(heap);
		heap->dbg_state_dirty = 1;
		duk_debug_clear_pause_state(heap);
		DUK_ASSERT(heap->ms_running == 0); /* debugger can't be triggered within mark-and-sweep */
		heap->ms_running = 2; /* prevent mark-and-sweep, prevent refzero queueing */
		heap->ms_prevent_count++;
		DUK_ASSERT(heap->ms_prevent_count != 0); /* Wrap. */
		DUK_ASSERT(heap->heap_thread != NULL);
	}
}

DUK_INTERNAL void duk_debug_clear_paused(duk_heap *heap) {
	if (duk_debug_is_paused(heap)) {
		DUK_HEAP_CLEAR_DEBUGGER_PAUSED(heap);
		heap->dbg_state_dirty = 1;
		duk_debug_clear_pause_state(heap);
		DUK_ASSERT(heap->ms_running == 2);
		DUK_ASSERT(heap->ms_prevent_count > 0);
		heap->ms_prevent_count--;
		heap->ms_running = 0;
		DUK_ASSERT(heap->heap_thread != NULL);
	} else {
		DUK_D(DUK_DPRINT("trying to clear paused state when not paused, ignoring"));
	}
}

DUK_INTERNAL void duk_debug_clear_pause_state(duk_heap *heap) {
	heap->dbg_pause_flags = 0;
	heap->dbg_pause_act = NULL;
	heap->dbg_pause_startline = 0;
}

#else /* DUK_USE_DEBUGGER_SUPPORT */

/* No debugger support. */

#endif /* DUK_USE_DEBUGGER_SUPPORT */