File: fpdbgclasses.pp

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (4848 lines) | stat: -rw-r--r-- 153,671 bytes parent folder | download
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
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
{ $Id$ }
{
 ---------------------------------------------------------------------------
 fpdbgclasses.pp  -  Native freepascal debugger
 ---------------------------------------------------------------------------

 This unit contains debugger classes for a native freepascal debugger

 ---------------------------------------------------------------------------

 @created(Mon Apr 10th WET 2006)
 @lastmod($Date$)
 @author(Marc Weustink <marc@@dommelstein.nl>)

 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************
}
unit FpDbgClasses;
{$mode objfpc}{$H+}
{$ModeSwitch typehelpers }
{$TYPEDADDRESS on}
{$IFDEF INLINE_OFF}{$INLINE OFF}{$ENDIF}
{$IF FPC_Fullversion=30202}{$Optimization NOPEEPHOLE}{$ENDIF}

interface

uses
  Classes, SysUtils, Maps, FpDbgUtil, FpDbgLoader, FpDbgInfo,
  FpdMemoryTools, {$ifdef FORCE_LAZLOGGER_DUMMY} LazLoggerDummy {$else} LazLoggerBase {$endif}, LazClasses, LazFileUtils, DbgIntfBaseTypes,
  fgl, DbgIntfDebuggerBase, fpDbgSymTableContext,
  FpDbgCommon, FpErrorMessages, FpDbgDwarfCFI, LazDebuggerIntf;

type
  TFPDEvent = (
    deNone,
    deExitProcess, deCreateProcess,
    deLoadLibrary, deUnloadLibrary,
    deFinishedStep, deBreakpoint, deHardCodedBreakpoint,
    deException,
    deInternalContinue,
    deDetachFromProcess,
    deFailed);
  TFPDCompareStepInfo = (dcsiNewLine, dcsiSameLine, dcsiNoLineInfo, dcsiZeroLine);

  TGDbgRegisterValueList = specialize TFPGObjectList<TDbgRegisterValue>;

  { TDbgRegisterValueList }

  TDbgRegisterValueList = class(TGDbgRegisterValueList)
  private
    FPreviousRegisterValueList: TDbgRegisterValueList;

    function GetDbgRegister(AName: string): TDbgRegisterValue;
    function GetDbgRegisterAutoCreate(const AName: string): TDbgRegisterValue;
    function GetDbgRegisterCreate(AName: string): TDbgRegisterValue;
    function GetIsModified(AReg: TDbgRegisterValue): boolean;
  public
    procedure Assign(ASource: TDbgRegisterValueList);
    property DbgRegisterAutoCreate[AName: string]: TDbgRegisterValue read GetDbgRegisterAutoCreate;
    property DbgRegisterCreate[AName: string]: TDbgRegisterValue read GetDbgRegisterCreate;
    function FindRegisterByDwarfIndex(AnIdx: cardinal): TDbgRegisterValue;
    function FindRegisterByName(AnName: String): TDbgRegisterValue;
    property IsModified[AReg: TDbgRegisterValue]: boolean read GetIsModified;
  end;

  { TDbgCallstackEntry }
  TDbgThread = class;
  TFPDThreadArray = array of TDbgThread;
  TDbgInstance = class;
  TDbgLibrary = class;
  TOSDbgClasses = class;
  TDbgAsmInstruction = class;

  TDbgCallstackEntry = class
  private
    FAnAddress: TDBGPtr;
    FAutoFillRegisters: boolean;
    FContext: TFpDbgSimpleLocationContext;
    FFrameAdress: TDBGPtr;
    FThread: TDbgThread;
    FIsSymbolResolved: boolean;
    FSymbol: TFpSymbol;
    FRegisterValueList: TDbgRegisterValueList;
    FIndex: integer;
    function GetContext: TFpDbgSimpleLocationContext;
    function GetFunctionName: string;
    function GetProcSymbol: TFpSymbol;
    function GetLine: integer;
    function GetRegisterValueList: TDbgRegisterValueList;
    function GetSourceFile: string;
    function GetSrcClassName: string;
    procedure SetContext(AValue: TFpDbgSimpleLocationContext);
  public
    constructor create(AThread: TDbgThread; AnIndex: integer; AFrameAddress, AnAddress: TDBGPtr);
    destructor Destroy; override;
    property AnAddress: TDBGPtr read FAnAddress;
    property FrameAdress: TDBGPtr read FFrameAdress;
    property SourceFile: string read GetSourceFile;
    property FunctionName: string read GetFunctionName;
    property SrcClassName: string read GetSrcClassName;
    property Line: integer read GetLine;
    property RegisterValueList: TDbgRegisterValueList read GetRegisterValueList;
    property ProcSymbol: TFpSymbol read GetProcSymbol;
    property Index: integer read FIndex;
    property AutoFillRegisters: boolean read FAutoFillRegisters write FAutoFillRegisters;
    property Context: TFpDbgSimpleLocationContext read GetContext write SetContext;
  end;

  { TDbgCallstackEntryList }

  TDbgCallstackEntryList = class(specialize TFPGObjectList<TDbgCallstackEntry>)
  private
    FHasReadAllAvailableFrames: boolean;
  protected
  public
    procedure SetHasReadAllAvailableFrames;
    procedure Clear;
    property HasReadAllAvailableFrames: boolean read FHasReadAllAvailableFrames;
  end;

  TDbgProcess = class;
  TFpWatchPointData = class;

  { TDbgMemReader }

  TDbgMemReader = class(TFpDbgMemReaderBase)
  protected
    function GetDbgProcess: TDbgProcess; virtual; abstract;
    function GetDbgThread(AContext: TFpDbgLocationContext): TDbgThread; virtual;
  public
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; override; overload;
    function ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer; out ABytesRead: Cardinal): Boolean; override; overload;
    function ReadMemoryEx(AnAddress, AnAddressSpace: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean; override;
    function WriteMemory(AnAddress: TDbgPtr; ASize: Cardinal; ASource: Pointer): Boolean; override; overload;
    function ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean; override;
    function RegisterSize(ARegNum: Cardinal): Integer; override;
    function RegisterNumber(ARegName: String; out ARegNum: Cardinal): Boolean; override;
    function GetRegister(const ARegNum: Cardinal; AContext: TFpDbgLocationContext): TDbgRegisterValue; override;

    function WriteRegister(ARegNum: Cardinal; const AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean; override;
  end;

  { TDbgStackFrameInfo
    This can be overridden by each OS dependen class. Or it could be gotten from the Disassemble, if it is CPU specific
    This default assumes an Intel like stack, with StackPointer and FrameBase.
    This default assumes the stack grows by decreasing addresses.
  }

  TDbgStackFrameInfo = class
  private
    FThread: TDbgThread;
    FStoredStackFrame, FStoredStackPointer: TDBGPtr;
    FHasSteppedOut: Boolean;
    FProcessAfterRun: Boolean;
    FLeaveState: (lsNone, lsWasAtLeave1, lsWasAtLeave2, lsLeaveDone);
    Procedure DoAfterRun;
  protected
    procedure DoCheckNextInstruction(ANextInstruction: TDbgAsmInstruction; NextIsSingleStep: Boolean); virtual;
    function  CalculateHasSteppedOut: Boolean;  virtual;
  public
    constructor Create(AThread: TDbgThread);
    procedure CheckNextInstruction(ANextInstruction: TDbgAsmInstruction; NextIsSingleStep: Boolean); inline;
    function  HasSteppedOut: Boolean; inline;
    procedure FlagAsSteppedOut; inline;

    // only for FpLldbDebugger
    property StoredStackFrame: TDBGPtr read FStoredStackFrame;
  end;

  TTDbgStackUnwindResult = (suSuccess, suFailed,
    suFailedAtEOS, // this is the End Of Stack
    suGuessed      // Got a frame, but may be wrong
  );

  TDbgStackUnwinder = class
  public
    procedure InitForThread(AThread: TDbgThread); virtual; abstract;
    // FrameBasePointer is optional
    procedure GetTopFrame(out CodePointer, StackPointer, FrameBasePointer: TDBGPtr;
                          out ANewFrame: TDbgCallstackEntry); virtual; abstract;
    procedure InitForFrame(ACurrentFrame: TDbgCallstackEntry;
                           out CodePointer, StackPointer, FrameBasePointer: TDBGPtr); virtual; abstract;
    // AFrameIndex: The frame-index to be read. Starts at 1 (since 0 is top-lever, and handled by GetTopFrame)
    function Unwind(AFrameIndex: integer;
                    var CodePointer, StackPointer, FrameBasePointer: TDBGPtr;
                    ACurrentFrame: TDbgCallstackEntry; // nil for top frame
                    out ANewFrame: TDbgCallstackEntry
                   ): TTDbgStackUnwindResult; virtual; abstract;
  end;

  { TDbgStackUnwinderX86Base }
  // Avoid circular unit refs

  TDbgStackUnwinderX86Base = class(TDbgStackUnwinder)
  private
    FThread: TDbgThread;
    FProcess: TDbgProcess;
    FAddressSize: Integer;
  protected
    FDwarfNumIP, FDwarfNumBP, FDwarfNumSP: integer;
    FNameIP, FNameBP, FNameSP: String;
    property Process: TDbgProcess read FProcess;
    property Thread: TDbgThread read FThread;
    property AddressSize: Integer read FAddressSize;
  public
    constructor Create(AProcess: TDbgProcess);
    procedure InitForThread(AThread: TDbgThread); override;
    procedure InitForFrame(ACurrentFrame: TDbgCallstackEntry; out CodePointer,
      StackPointer, FrameBasePointer: TDBGPtr); override;
    procedure GetTopFrame(out CodePointer, StackPointer, FrameBasePointer: TDBGPtr;
      out ANewFrame: TDbgCallstackEntry); override;
  end;

  { TDbgThread }
  TFpInternalBreakpoint = class;

  TDbgThread = class(TObject)
  private
    FNextIsSingleStep: boolean;
    FNum: Integer;
    FProcess: TDbgProcess;
    FID: Integer;
    FHandle: THandle;
    FStoredBreakpointInfoState: (rbUnknown, rbNone, rbFound{, rbFoundAndDec});
    FStoredBreakpointInfoAddress: TDBGPtr;
    FPausedAtHardcodeBreakPoint: Boolean;
    FSuspendCount: Integer;

    function GetRegisterValueList: TDbgRegisterValueList;
  protected
    FCallStackEntryList: TDbgCallstackEntryList;
    FRegisterValueListValid: boolean;
    FRegisterValueList,
    FPreviousRegisterValueList: TDbgRegisterValueList;
    FStoreStepSrcFilename, FStoreStepFuncName: string;
    FStoreStepStartAddr, FStoreStepEndAddr: TDBGPtr;
    FStoreStepSrcLineNo: integer;
    FStoreStepFuncAddr: TDBGPtr;
    FStackBeforeAlloc: TDBGPtr;

    procedure StoreHasBreakpointInfoForAddress(AnAddr: TDBGPtr); inline;
    procedure ClearHasBreakpointInfoForAddressMismatch(AKeepOnlyForAddr: TDBGPtr); inline;
    procedure ClearHasBreakpointInfoForAddress; inline;
    function  HasBreakpointInfoForAddressMismatch(AnAddr: TDBGPtr): boolean; inline;

    procedure LoadRegisterValues; virtual;
    property Process: TDbgProcess read FProcess;
    function ResetInstructionPointerAfterBreakpoint: boolean; virtual; abstract;
    procedure DoBeforeBreakLocationMapChange; // A new location added / or a location removed => memory will change
    procedure ValidateRemovedBreakPointInfo;
    function GetName: String; virtual;
    function GetStackUnwinder: TDbgStackUnwinder; virtual; abstract;

    (* The "HasBreakpointInfoForAddress" is used if a breakpoint was hit,
       and removed while some DbgThread may still need to know it was there.
       The address of interest is therefore where the breakpoint is.
       Depending on the architecture the IP has to be adjusted.
    *)
    function GetInstructionPointerForHasBreakpointInfoForAddress: TDBGPtr; virtual;
  public
    constructor Create(const AProcess: TDbgProcess; const AID: Integer; const AHandle: THandle); virtual;
    procedure DoBeforeProcessLoop;
    function HasInsertedBreakInstructionAtLocation(const ALocation: TDBGPtr): Boolean; // include removed breakpoints that (may have) already triggered
    (* CheckAndResetInstructionPointerAfterBreakpoint
       This will check if the last instruction was a breakpoint (int3).
       It must ONLY be called, if the signal indicated that it should have been.
       Since the previous IP is not known, this assumes the length of the
         previous asm statement to be the same as the length of int3.
       If a longer command would end in the signature of int3, then this would
         detect the int3 (false positive)
    *)
    procedure CheckAndResetInstructionPointerAfterBreakpoint;
    function CheckForHardcodeBreakPoint(AnAddr: TDBGPtr): boolean;
    procedure BeforeContinue; virtual;
    procedure ApplyWatchPoints(AWatchPointData: TFpWatchPointData); virtual;
    function DetectHardwareWatchpoint: Pointer; virtual;
    // This function changes the value of a register in the debugee.
    procedure SetRegisterValue(AName: string; AValue: QWord); virtual; abstract;

    function GetInstructionPointerRegisterValue: TDbgPtr; virtual; abstract;
    function GetStackBasePointerRegisterValue: TDbgPtr; virtual; abstract;
    function GetStackPointerRegisterValue: TDbgPtr; virtual; abstract;
    procedure SetStackPointerRegisterValue(AValue: TDbgPtr); virtual; abstract;
    procedure SetInstructionPointerRegisterValue(AValue: TDbgPtr); virtual; abstract;
    function GetCurrentStackFrameInfo: TDbgStackFrameInfo;

    function AllocStackMem(ASize: Integer): TDbgPtr; virtual;
    procedure RestoreStackMem;

    procedure PrepareCallStackEntryList(AFrameRequired: Integer = -1); virtual;
    function  FindCallStackEntryByBasePointer(AFrameBasePointer: TDBGPtr; AMaxFrameToSearch: Integer; AStartFrame: integer = 0): Integer; //virtual;
    function  FindCallStackEntryByInstructionPointer(AInstructionPointer: TDBGPtr; AMaxFrameToSearch: Integer; AStartFrame: integer = 0): Integer; //virtual;
    procedure ClearCallStack;
    // Use these functions to 'save' the value of all registers, and to reset
    // them to their original values. (Used to be able to restore the original
    // situation after calling functions inside the debugee)
    procedure StoreRegisters; virtual; abstract;
    procedure RestoreRegisters; virtual; abstract;
    // It could be that an signal led to an exception, and that this
    // signal is stored to be send to the debuggee again upon continuation.
    // Use ClearExceptionSignal to remove/eat this signal.
    procedure ClearExceptionSignal; virtual;

    procedure IncSuspendCount;
    procedure DecSuspendCount;
    property  SuspendCount: Integer read FSuspendCount;

    destructor Destroy; override;
    function CompareStepInfo(AnAddr: TDBGPtr = 0; ASubLine: Boolean = False): TFPDCompareStepInfo;
    function IsAtStartOfLine: boolean;
    function StoreStepInfo(AnAddr: TDBGPtr = 0): boolean;
    property ID: Integer read FID;
    property Num: Integer read FNum;
    property Handle: THandle read FHandle;
    property Name: String read GetName;
    property NextIsSingleStep: boolean read FNextIsSingleStep write FNextIsSingleStep;
    property RegisterValueList: TDbgRegisterValueList read GetRegisterValueList;
    property CallStackEntryList: TDbgCallstackEntryList read FCallStackEntryList;
    property StoreStepFuncName: String read FStoreStepFuncName;
    property StoreStepFuncAddr: TDBGPtr read FStoreStepFuncAddr;
    property PausedAtHardcodeBreakPoint: Boolean read FPausedAtHardcodeBreakPoint;
  end;
  TDbgThreadClass = class of TDbgThread;

  { TThreadMapUnLockedEnumerator }

  TThreadMapUnLockedEnumerator = class(TMapIterator)
  private
    FDoneFirst: Boolean;
    function GetCurrent: TDbgThread;
  public
    function MoveNext: Boolean;
    property Current: TDbgThread read GetCurrent;
  end;

    { TThreadMapEnumerator }

  TThreadMapEnumerator = class(TLockedMapIterator)
  private
    FDoneFirst: Boolean;
    function GetCurrent: TDbgThread;
  public
    function MoveNext: Boolean;
    property Current: TDbgThread read GetCurrent;
  end;

  { TThreadMap }

  TThreadMap = class(TMap)
  private
    FNumCounter: integer;
  public
    function GetEnumerator: TThreadMapEnumerator;
    procedure Add(const AId, AData); reintroduce;
  end;

  // Simple array to pass a list of multiple libraries in a parameter. Does
  // not own or do anything other with the libraries.
  TDbgLibraryArr = array of TDbgLibrary;

  { TLibraryMapEnumerator }

  TLibraryMapEnumerator = class(TMapIterator)
  private
    FDoneFirst: Boolean;
    function GetCurrent: TDbgLibrary;
  public
    function MoveNext: Boolean;
    property Current: TDbgLibrary read GetCurrent;
  end;

  { TLibraryMap }

  TLibraryMap = class(TMap)
  private
    FLibrariesAdded: TDbgLibraryArr;
    FLibrariesRemoved: TDbgLibraryArr;
  public
    function GetEnumerator: TLibraryMapEnumerator;
    procedure Add(const AId, AData);
    function Delete(const AId): Boolean;
    function GetLib(const AHandle: THandle; out ALib: TDbgLibrary): Boolean;
    function GetLib(const AName: String; out ALib: TDbgLibrary; IsFullName: Boolean = True): Boolean;
    procedure ClearAddedAndRemovedLibraries;
    property LibrariesAdded: TDbgLibraryArr read FLibrariesAdded;
  end;

  TFpInternalBreakpointArray = array of TFpInternalBreakpoint;
  TFpBreakPointTargetHandler = class;
  TFpBreakPointTargetHandlerData = record end;
  PFpBreakPointTargetHandlerDataPointer = ^TFpBreakPointTargetHandlerData;

  { TFpBreakPointMap }

  TFpBreakPointMap = class(TMap)
  strict protected type
    { TFpBreakPointMapEntry }
    TFpBreakPointMapEntry = record
      InternalBreakPoint: Pointer;  // TFpInternalBreakpoint or TFpInternalBreakpointArray
      IsBreakList: ByteBool;
      ErrorSetting: ByteBool;
      TargetHandlerData: TFpBreakPointTargetHandlerData; // must be last
    end;
    PFpBreakPointMapEntry = ^TFpBreakPointMapEntry;

  public type
    { TFpBreakPointMapEnumerationData }
    TFpBreakPointMapEnumerationData = record
      Location: TDBGPtr;
      MapDataPtr: PFpBreakPointMapEntry;
      TargetHandlerDataPtr: PFpBreakPointTargetHandlerDataPointer;
    end;

    { TFpBreakPointMapEnumerator }
    TFpBreakPointMapEnumerator = class(TMapIterator)
    private
      FDoneFirst: Boolean;
      function GetCurrent: TFpBreakPointMapEnumerationData;
    public
      function MoveNext: Boolean;
      property Current: TFpBreakPointMapEnumerationData read GetCurrent;
    end;

  strict private
    FProcess: TDbgProcess;
    FTargetHandler: TFpBreakPointTargetHandler;
    FDataSize: integer;
    FTmpDataPtr: PFpBreakPointMapEntry;
  strict protected
    property Process: TDbgProcess read FProcess;
    property TargetHandler: TFpBreakPointTargetHandler read FTargetHandler;
  public
    constructor Create(AProcess: TDbgProcess; ATargetHandler: TFpBreakPointTargetHandler);
    destructor Destroy; override;
    procedure Clear; reintroduce;

    procedure AddLocation   (const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint; AnIgnoreIfExists: Boolean = True; AForceRetrySetting: Boolean = False);
    procedure RemoveLocation(const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint);
    function HasInsertedBreakInstructionAtLocation(const ALocation: TDBGPtr): Boolean;
    function GetInternalBreaksAtLocation(const ALocation: TDBGPtr): TFpInternalBreakpointArray;

    function GetDataPtr(const AId): PFpBreakPointMapEntry; reintroduce; inline;
    function GetTargetDataPtr(const AId): PFpBreakPointTargetHandlerDataPointer;

    function GetEnumerator: TFpBreakPointMapEnumerator;
  end;

  { TFpBreakPointTargetHandler }

  TFpBreakPointTargetHandler = class abstract
  protected
    class var DBG__VERBOSE, DBG__WARNINGS, DBG__BREAKPOINTS: PLazLoggerLogGroup;
  strict private
    FProcess: TDbgProcess;
    FBreakMap: TFpBreakPointMap;
  protected
    property Process: TDbgProcess read FProcess;
    property BreakMap: TFpBreakPointMap read FBreakMap write FBreakMap;
  public
    constructor Create(AProcess: TDbgProcess);
    function GetDataSize: integer; virtual; abstract;

    function InsertBreakInstructionCode(const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer): boolean; virtual; abstract;
    procedure RemoveBreakInstructionCode(const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer); virtual; abstract;

    // When the debugger modifies the debuggee's code, it might be that the
    // original value underneeth the breakpoint has to be changed. This function
    // makes this possible.
    procedure UpdateMapForNewTargetCode(const AAdress: TDbgPtr; const ASize: Cardinal; const AData); virtual; abstract;

    function IsHardcodeBreakPoint(const ALocation: TDBGPtr): Boolean; virtual; abstract;
    // IsHardcodeBreakPointInCode checks even if no TFpInternalBreakpoint is set at the location
    function IsHardcodeBreakPointInCode(const ALocation: TDBGPtr): Boolean; virtual; abstract;

    procedure TempRemoveBreakInstructionCode(const ALocation: TDBGPtr); virtual; abstract;
    procedure RestoreTempBreakInstructionCodes; virtual; abstract;
    procedure MaskBreakpointsInReadData(const AAdress: TDbgPtr; const ASize: Cardinal; var AData); virtual; abstract;
  end;

  { TGenericBreakPointTargetHandler }

  generic TGenericBreakPointTargetHandler<_BRK_STORE, _BREAK> = class(TFpBreakPointTargetHandler)
  strict protected type
    { TInternalBreakLocationEntry }
    TInternalBreakLocationEntry = packed record
      OrigValue: _BRK_STORE;
    end;
    PInternalBreakLocationEntry = ^TInternalBreakLocationEntry;
    P_BRK_STORE = ^_BRK_STORE;

  private
    FTmpRemovedBreaks: array of TDBGPtr;

  strict protected
    function HPtr(Src: PFpBreakPointTargetHandlerDataPointer): PInternalBreakLocationEntry; inline;
    function GetOrigValueAtLocation(const ALocation: TDBGPtr): _BRK_STORE; // returns break instruction, if there is no break at this location
    procedure AdaptOriginalValueAtLocation(const ALocation: TDBGPtr; const NewOrigValue: _BRK_STORE);

    // Default implementation is to write break instruction to memory
    function DoInsertBreakInstructionCode(const ALocation: TDBGPtr; out OrigValue: _BRK_STORE; AMakeTempRemoved: Boolean): Boolean; virtual;
    function DoRemoveBreakInstructionCode(const ALocation: TDBGPtr; const OrigValue: _BRK_STORE): Boolean; virtual;
  public
    function GetDataSize: integer; override;

    function InsertBreakInstructionCode(const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer): boolean; override;
    procedure RemoveBreakInstructionCode(const ALocation: TDBGPtr; const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer); override;

    // When the debugger modifies the debuggee's code, it might be that the
    // original value underneeth the breakpoint has to be changed. This function
    // makes this possible.
    procedure UpdateMapForNewTargetCode(const AAdress: TDbgPtr; const ASize: Cardinal; const AData); override;

    function IsHardcodeBreakPoint(const ALocation: TDBGPtr): Boolean; override;
    function IsHardcodeBreakPointInCode(const ALocation: TDBGPtr): Boolean; override;

    procedure TempRemoveBreakInstructionCode(const ALocation: TDBGPtr); override;
    procedure RestoreTempBreakInstructionCodes; override;
    procedure MaskBreakpointsInReadData(const AAdress: TDbgPtr; const ASize: Cardinal; var AData); override;
  end;

  { TFpDbgBreakpoint }

  TFpDbgBreakpoint = class;

  TFpDbgBreakpointState = (bksUnknown, bksOk, bksFailed, bksPending);
  TFpDbgBreakpointStateChangeEvent = procedure(Sender: TFpDbgBreakpoint; ANewState: TFpDbgBreakpointState) of object;

  TFpDbgBreakpoint = class(TObject)
  private
    FFreeByDbgProcess: Boolean;
    FEnabled: boolean;
    FOn_Thread_StateChange: TFpDbgBreakpointStateChangeEvent;
  protected
    procedure SetFreeByDbgProcess(AValue: Boolean); virtual;
    procedure SetEnabled(AValue: boolean);
    function GetState: TFpDbgBreakpointState; virtual;
  public
    function Hit(const AThreadID: Integer; ABreakpointAddress: TDBGPtr): Boolean; virtual; abstract;
    function HasLocation(const ALocation: TDBGPtr): Boolean; virtual; abstract;
    // A breakpoint could also be inside/part of a library.

    procedure AddAddress(const ALocation: TDBGPtr); virtual; abstract;
    procedure RemoveAddress(const ALocation: TDBGPtr); virtual; abstract;
    procedure RemoveAllAddresses; virtual; abstract;

    procedure SetBreak; virtual; abstract;
    procedure ResetBreak; virtual; abstract;

    // FreeByDbgProcess: The breakpoint will be freed by TDbgProcess.Destroy
    // If the breakpoint does not have a process, it will be destroyed immediately
    property FreeByDbgProcess: Boolean read FFreeByDbgProcess write SetFreeByDbgProcess;
    property Enabled: boolean read FEnabled write SetEnabled;
    property State: TFpDbgBreakpointState read GetState;
    // Event runs in dbg-thread
    property On_Thread_StateChange: TFpDbgBreakpointStateChangeEvent read FOn_Thread_StateChange write FOn_Thread_StateChange;
  end;

  { TFpInternalBreakBase }

  TFpInternalBreakBase = class(TFpDbgBreakpoint)
  strict private
    FProcess: TDbgProcess;
  private
    procedure SetProcessToNil;
  protected
    procedure SetFreeByDbgProcess(AValue: Boolean); override;
    procedure UpdateForLibraryLoaded(ALib: TDbgLibrary); virtual;
    procedure UpdateForLibrareUnloaded(ALib: TDbgLibrary); virtual;
    property Process: TDbgProcess read FProcess;
  public
    constructor Create(const AProcess: TDbgProcess); virtual;
  end;

  TFpInternalBreakpointList = specialize TFPGObjectList<TFpInternalBreakBase>;

  { TFpInternalBreakpoint }

  TFpInternalBreakpoint = class(TFpInternalBreakBase)
  private
    FLocation: TDBGPtrArray;
    FInternal: Boolean;
    FState: TFpDbgBreakpointState;
    FErrorSettingCount: integer;
    FUpdateStateLock: integer;
    FNeedUpdateState: boolean;
  protected
    procedure BeginUpdate;
    procedure EndUpdate;
    procedure TriggerUpdateState;
    procedure AddErrorSetting(ALocation: TDBGPtr);
    procedure RemoveErrorSetting(ALocation: TDBGPtr);
    function GetState: TFpDbgBreakpointState; override;
    procedure SetState(AState: TFpDbgBreakpointState);
    procedure UpdateState; virtual;
    procedure UpdateForLibrareUnloaded(ALib: TDbgLibrary); override;
    property Location: TDBGPtrArray read FLocation;
  public
    constructor Create(const AProcess: TDbgProcess; const ALocation: TDBGPtrArray; AnEnabled: Boolean); virtual;
    destructor Destroy; override;
    function Hit(const AThreadID: Integer; ABreakpointAddress: TDBGPtr): Boolean; override;
    function HasLocation(const ALocation: TDBGPtr): Boolean; override;

    procedure AddAddress(const ALocation: TDBGPtr); override;
    procedure AddAddress(const ALocations: TDBGPtrArray);
    procedure RemoveAddress(const ALocation: TDBGPtr); override;
    procedure RemoveAllAddresses; override;

    procedure SetBreak; override;
    procedure ResetBreak; override;

  end;

  { TFpInternalBreakpointAtAddress }

  TFpInternalBreakpointAtAddress = class(TFpInternalBreakpoint) // single address ONLY
  private
    FRemovedLoc: TDBGPtrArray;
  protected
    procedure UpdateState; override;
    procedure UpdateForLibraryLoaded(ALib: TDbgLibrary); override;
    procedure UpdateForLibrareUnloaded(ALib: TDbgLibrary); override; // Don't remove from location list
  public
    destructor Destroy; override;
  end;

  { TFpInternalBreakpointAtSymbol }

  TFpInternalBreakpointAtSymbol = class(TFpInternalBreakpoint)
  private
    FFuncName: String;
    FSymInstance: TDbgInstance;
  protected
    procedure UpdateState; override;
    procedure UpdateForLibraryLoaded(ALib: TDbgLibrary); override;
  public
    constructor Create(const AProcess: TDbgProcess; const AFuncName: String; AnEnabled: Boolean; ASymInstance: TDbgInstance = nil; AIgnoreCase: Boolean = False); virtual;
  end;

  { TFpInternalBreakpointAtFileLine }

  TFpInternalBreakpointAtFileLine = class(TFpInternalBreakpoint)
  private
    FFileName: String;
    FLine: Cardinal;
    FSymInstance: TDbgInstance;
    FFoundFileWithoutLine: Boolean;
  protected
    procedure UpdateState; override;
    procedure UpdateForLibraryLoaded(ALib: TDbgLibrary); override;
  public
    constructor Create(const AProcess: TDbgProcess; const AFileName: String; ALine: Cardinal;
      AnEnabled: Boolean; ASymInstance: TDbgInstance = nil); virtual;
  end;

  { TFpInternalWatchpoint }

  TFpInternalWatchpoint  = class(TFpInternalBreakBase)
  private
    FLocation: TDBGPtr;
    FSize: Cardinal;
    FReadWrite: TDBGWatchPointKind;
    FScope: TDBGWatchPointScope;

    FOtherWatchCount: Integer;
    FFirstWatchLocation: TDBGPtr;
    FFirstWatchSize,
    FOtherWatchesSize,
    FLastWatchSize: Integer;
  protected
    property Location: TDBGPtr read FLocation;
    property Size: Cardinal read FSize;
    property ReadWrite: TDBGWatchPointKind read FReadWrite;
    property Scope: TDBGWatchPointScope read FScope;
  public
    constructor Create(const AProcess: TDbgProcess; const ALocation: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind;
                      AScope: TDBGWatchPointScope); virtual;
    destructor Destroy; override;

    procedure SetBreak; override;
    procedure ResetBreak; override;
  end;

  // Container to hold target specific process info
  TDbgProcessConfig = class(TPersistent)
  end;

  { TDbgConfig }

  TDbgConfig = class
  private
    FBreakpointSearchMaxLines: integer;
    // WindowBounds
    FUseConsoleWinPos: boolean;
    FUseConsoleWinSize: boolean;
    FUseConsoleWinBuffer: boolean;
    FConsoleWinPos: TPoint;
    FConsoleWinSize: TPoint;
    FConsoleWinBuffer: TPoint;
    // Redir
    FStdInRedirFile: String;
    FStdOutRedirFile: String;
    FStdErrRedirFile: String;
    FFileOverwriteStdIn: Boolean;
    FFileOverwriteStdOut: Boolean;
    FFileOverwriteStdErr: Boolean;
  public
    // WindowBounds
    property UseConsoleWinPos: boolean read FUseConsoleWinPos write FUseConsoleWinPos;
    property UseConsoleWinSize: boolean read FUseConsoleWinSize write FUseConsoleWinSize;
    property UseConsoleWinBuffer: boolean read FUseConsoleWinBuffer write FUseConsoleWinBuffer;
    property ConsoleWinPos: TPoint read FConsoleWinPos write FConsoleWinPos;
    property ConsoleWinSize: TPoint read FConsoleWinSize write FConsoleWinSize;
    property ConsoleWinBuffer: TPoint read FConsoleWinBuffer write FConsoleWinBuffer;
    // Redir
    property StdInRedirFile: String read FStdInRedirFile write FStdInRedirFile;
    property StdOutRedirFile: String read FStdOutRedirFile write FStdOutRedirFile;
    property StdErrRedirFile: String read FStdErrRedirFile write FStdErrRedirFile;
    property FileOverwriteStdIn:  Boolean read FFileOverwriteStdIn  write FFileOverwriteStdIn;
    property FileOverwriteStdOut: Boolean read FFileOverwriteStdOut write FFileOverwriteStdOut;
    property FileOverwriteStdErr: Boolean read FFileOverwriteStdErr write FFileOverwriteStdErr;
    // Breakpoints
    property BreakpointSearchMaxLines: integer read FBreakpointSearchMaxLines  write FBreakpointSearchMaxLines;
  end;

  { TDbgInstance }

  TDbgInstance = class(TObject)
  private
    FMemManager: TFpDbgMemManager;
    FMemModel: TFpDbgMemModel;
    FMode: TFPDMode;
    FFileName: String;
    FProcess: TDbgProcess;
    FSymbolTableInfo: TFpSymbolInfo;
    FLoaderList: TDbgImageLoaderList;
    FLastLineAddressesFoundFile: Boolean;
    function GetOSDbgClasses: TOSDbgClasses;
    function GetPointerSize: Integer;

    function  GetLineAddresses(AFileName: String; ALine: Cardinal; var AResultList: TDBGPtrArray;
      AFindSibling: TGetLineAddrFindSibling = fsNone; AMaxSiblingDistance: integer = 0): Boolean;
    function FindProcSymbol(const AName: String; AIgnoreCase: Boolean = False): TFpSymbol; overload;
    function FindProcSymbol(AAdress: TDbgPtr): TFpSymbol; overload;
  protected
    FDbgInfo: TDbgInfo;
    procedure InitializeLoaders; virtual;
    procedure SetFileName(const AValue: String);
    procedure SetMode(AMode: TFPDMode); experimental; // for testcase
    function FindCallFrameInfo(AnAddress: TDBGPtr; out CIE: TDwarfCIE; out Row: TDwarfCallFrameInformationRow): Boolean;
  public
    constructor Create(const AProcess: TDbgProcess); virtual;
    destructor Destroy; override;

    // Returns the addresses at the given source-filename and line-number.
    // Searches the program and all libraries. This can lead to multiple hits,
    // as the application and libraries can share sourcecode but have their own
    // binary code.

    function  FindProcStartEndPC(AAdress: TDbgPtr; out AStartPC, AEndPC: TDBGPtr): boolean;

    // Check if a certain (range of) address(es) belongs to a specific Instance
    // (for example a library)
    function EnclosesAddress(AnAddress: TDBGPtr): Boolean;
    function EnclosesAddressRange(AStartAddress, AnEndAddress: TDBGPtr): Boolean;

    procedure LoadInfo; virtual;

    property Process: TDbgProcess read FProcess;
    property OSDbgClasses: TOSDbgClasses read GetOSDbgClasses;
    property DbgInfo: TDbgInfo read FDbgInfo;
    property SymbolTableInfo: TFpSymbolInfo read FSymbolTableInfo;
    property Mode: TFPDMode read FMode;
    property PointerSize: Integer read GetPointerSize;
    property MemManager: TFpDbgMemManager read FMemManager;
    property MemModel: TFpDbgMemModel read FMemModel;
    property LoaderList: TDbgImageLoaderList read FLoaderList;
  end;

  { TDbgLibrary }

  TDbgLibrary = class(TDbgInstance)
  private
    FModuleHandle: THandle;
    FBreakUpdateDone: Boolean;
  public
    constructor Create(const AProcess: TDbgProcess; const ADefaultName: String; const AModuleHandle: THandle);
    property Name: String read FFileName;
    property ModuleHandle: THandle read FModuleHandle;
  end;

  TStartInstanceFlag = (siRediretOutput, siForceNewConsole);
  TStartInstanceFlags = set of TStartInstanceFlag;

  { TDbgAsmInstruction }

  TDbgAsmInstruction = class(TRefCountedObject)
  public
    // returns byte len of call instruction at AAddress // 0 if not a call intruction
    function IsCallInstruction: boolean; virtual;
    function IsReturnInstruction: boolean; virtual;
    function IsLeaveStackFrame: boolean; virtual;
    //function ModifiesBasePointer: boolean; virtual;
    function ModifiesStackPointer: boolean; virtual;
    function IsJumpInstruction(IncludeConditional: Boolean = True; IncludeUncoditional: Boolean = True): boolean; virtual;
    function InstructionLength: Integer; virtual;
  end;

  TDbgInstInfo = record
    InstrType: (itAny, itJump);
    InstrTargetOffs: Int64; // offset from the START address of instruction
  end;

  { TDbgAsmDecoder }

  TDbgAsmDecoder = class
  protected
    function GetLastErrorWasMemReadErr: Boolean; virtual;
    function GetMaxInstrSize: integer; virtual; abstract;
    function GetMinInstrSize: integer; virtual; abstract;
    function GetCanReverseDisassemble: boolean; virtual;
  public
    constructor Create(AProcess: TDbgProcess); virtual; abstract;

    procedure Disassemble(var AAddress: Pointer; out ACodeBytes: String; out ACode: String; out AnInfo: TDbgInstInfo); virtual; overload;
    procedure Disassemble(var AAddress: Pointer; out ACodeBytes: String; out ACode: String); virtual; abstract; overload;
    procedure ReverseDisassemble(var AAddress: Pointer; out ACodeBytes: String; out ACode: String); virtual;

    function GetInstructionInfo(AnAddress: TDBGPtr): TDbgAsmInstruction; virtual; abstract;
    function GetFunctionFrameInfo(AnAddress: TDBGPtr; out AnIsOutsideFrame: Boolean): Boolean; virtual;
    function IsAfterCallInstruction(AnAddress: TDBGPtr): boolean; virtual;
    function UnwindFrame(var AnAddress, AStackPtr, AFramePtr: TDBGPtr; AQuick: boolean; ARegisterValueList: TDbgRegisterValueList): boolean; virtual;

    property LastErrorWasMemReadErr: Boolean read GetLastErrorWasMemReadErr;
    property MaxInstructionSize: integer read GetMaxInstrSize;  // abstract
    property MinInstructionSize: integer read GetMinInstrSize;  // abstract
    property CanReverseDisassemble: boolean read GetCanReverseDisassemble;
  end;
  TDbgDisassemblerClass = class of TDbgAsmDecoder;

  TDebugOutputEvent = procedure(Sender: TObject; ProcessId, ThreadId: Integer; AMessage: String) of object;

  TFpDbgDataCache = class(specialize TFPGMapObject<Pointer, TObject>);

  { TDbgProcess }

  TDbgProcess = class(TDbgInstance)
  private
    FDisassembler: TDbgAsmDecoder;
    FExceptionClass: string;
    FExceptionMessage: string;
    FExitCode: DWord;
    FGotExitProcess: Boolean;
    FLastLibraryUnloaded: TDbgLibrary;
    FOnDebugOutputEvent: TDebugOutputEvent;
    FOSDbgClasses: TOSDbgClasses;
    FProcessID: Integer;
    FThreadID: Integer;
    FWatchPointData: TFpWatchPointData;
    FProcessConfig: TDbgProcessConfig;
    FConfig: TDbgConfig;
    FGlobalCache: TFpDbgDataCache;
    function DoGetCfiFrameBase(AContext: TFpDbgLocationContext; out AnError: TFpError): TDBGPtr;
    function DoGetFrameBase(AContext: TFpDbgLocationContext; out AnError: TFpError): TDBGPtr;
    function GetDisassembler: TDbgAsmDecoder;
    function GetLastLibrariesLoaded: TDbgLibraryArr;
    function GetLastLibrariesUnloaded: TDbgLibraryArr;
    function GetPauseRequested: boolean;
    procedure SetPauseRequested(AValue: boolean);
    procedure ThreadDestroyed(const AThread: TDbgThread);
  protected
    FBreakpointList, FWatchPointList: TFpInternalBreakpointList;
    FCurrentBreakpoint: TFpInternalBreakpoint;  // set if we are executing the code at the break
                                         // if the singlestep is done, set the break again
    FCurrentBreakpointList: TFpInternalBreakpointArray; // further current breakpoint
    FCurrentWatchpoint: Pointer;         // Indicates the owner
    FReEnableBreakStep: Boolean;         // Set when we are reenabling a breakpoint
                                         // We need a single step, so the IP is after the break to set

    FSymInstances: TList;  // list of dbgInstances with debug info

    FThreadMap: TThreadMap; // map ThreadID -> ThreadObject
    FLibMap: TLibraryMap;    // map LibAddr -> LibObject
    FBreakMap: TFpBreakPointMap;  // map BreakAddr -> BreakObject
    FBreakTargetHandler: TFpBreakPointTargetHandler;
    FPauseRequested: longint;

    FMainThread: TDbgThread;
    function GetHandle: THandle; virtual;
    procedure SetThreadId(AThreadId: Integer);
    procedure SetExitCode(AValue: DWord);
    function GetLastEventProcessIdentifier: THandle; virtual;
    function DoBreak(BreakpointAddress: TDBGPtr; AThreadID: integer): Boolean;
    procedure SetLastLibraryUnloaded(ALib: TDbgLibrary);
    procedure SetLastLibraryUnloadedNil(ALib: TDbgLibrary);
    procedure AddLibrary(ALib: TDbgLibrary; AnID: TDbgPtr);
    function GetRequiresExecutionInDebuggerThread: boolean; virtual;

    procedure BeforeChangingInstructionCode(const ALocation: TDBGPtr; ACount: Integer); virtual;
    procedure AfterChangingInstructionCode(const ALocation: TDBGPtr; ACount: Integer); virtual;
    procedure AfterBreakpointAdded(ABreak: TFpDbgBreakpoint);

    procedure MaskBreakpointsInReadData(const AAdress: TDbgPtr; const ASize: Cardinal; var AData);
    // Should create a TDbgThread-instance for the given ThreadIdentifier.
    function CreateThread(AthreadIdentifier: THandle; out IsMainThread: boolean): TDbgThread; virtual; abstract;
    // Should analyse why the debugger has stopped.
    function AnalyseDebugEvent(AThread: TDbgThread): TFPDEvent; virtual; abstract;

    function CreateWatchPointData: TFpWatchPointData; virtual;
    procedure Init(const AProcessID, AThreadID: Integer);
    function CreateConfig: TDbgConfig;
    function CreateBreakPointTargetHandler: TFpBreakPointTargetHandler; virtual; abstract;
    procedure InitializeLoaders; override;
  public
    class function isSupported(ATargetInfo: TTargetDescriptor): boolean; virtual;
    constructor Create(const AFileName: string; AnOsClasses: TOSDbgClasses;
                      AMemManager: TFpDbgMemManager; AMemModel: TFpDbgMemModel;
                      AProcessConfig: TDbgProcessConfig = nil); virtual;
    destructor Destroy; override;

    function StartInstance(AParams, AnEnvironment: TStrings; AWorkingDirectory, AConsoleTty: string;
                      AFlags: TStartInstanceFlags; out AnError: TFpError): boolean; virtual;
    function AttachToInstance(APid: Integer; out AnError: TFpError): boolean; virtual;

    function  AddInternalBreak(const ALocation: TDBGPtr): TFpInternalBreakpoint; overload;
    function  AddInternalBreak(const ALocation: TDBGPtrArray): TFpInternalBreakpoint; overload;
    (* ASymInstance: nil = anywhere / TDbgProcess or TDbgLibrary to limit *)
    function  AddBreak(const ALocation: TDBGPtr; AnEnabled: Boolean = True): TFpDbgBreakpoint; overload;
    function  AddBreak(const ALocation: TDBGPtrArray; AnEnabled: Boolean = True): TFpDbgBreakpoint; overload;
    function  AddBreak(const AFileName: String; ALine: Cardinal; AnEnabled: Boolean = True; ASymInstance: TDbgInstance = nil): TFpDbgBreakpoint; overload;
    function  AddBreak(const AFuncName: String; AnEnabled: Boolean = True; ASymInstance: TDbgInstance = nil; AIgnoreCase: Boolean = False): TFpDbgBreakpoint; overload;
    function  AddUserBreak(const ALocation: TDBGPtr; AnEnabled: Boolean = True): TFpDbgBreakpoint; overload;
    function  AddWatch(const ALocation: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind;
                      AScope: TDBGWatchPointScope): TFpInternalWatchpoint;
    property WatchPointData: TFpWatchPointData read FWatchPointData;
    (* FindProcSymbol(Address)
         Search the program and all libraries.
       FindProcSymbol(Name)
         Search ONLY the program.
       FindProcSymbol(Name, ASymInstance)
         Search ASymInstance (process or lib) / if nil, search all
         Names can be ambigious, as dll can have the same names.
    *)
    function  FindProcSymbol(const AName: String): TFpSymbol; overload; // deprecated 'backward compatible / use FindProcSymbol(AName, TheDbgProcess)';
    function  FindProcSymbol(const AName: String; ASymInstance: TDbgInstance): TFpSymbol; overload;
    procedure FindProcSymbol(const AName: String; ASymInstance: TDbgInstance; out ASymList: TFpSymbolArray; AIgnoreCase: Boolean = False);
    function  FindProcSymbol(const AName, ALibraryName: String; IsFullLibName: Boolean = True): TFpSymbol;  overload;deprecated 'XXXXXXXXXXXXXXXXXXXXXXXXXX';
    function  FindProcSymbol(AAdress: TDbgPtr): TFpSymbol;  overload;
    function  FindSymbolScope(AThreadId, AStackFrame: Integer): TFpDbgSymbolScope;
    function  FindProcStartEndPC(const AAdress: TDbgPtr; out AStartPC, AEndPC: TDBGPtr): boolean;
    function FindCallFrameInfo(AnAddress: TDBGPtr; out CIE: TDwarfCIE; out Row: TDwarfCallFrameInformationRow): Boolean; reintroduce;

    function  GetLineAddresses(AFileName: String; ALine: Cardinal; var AResultList: TDBGPtrArray; ASymInstance: TDbgInstance = nil;
      AFindSibling: TGetLineAddrFindSibling = fsNone; AMaxSiblingDistance: integer = 0): Boolean;
    //function  ContextFromProc(AThreadId, AStackFrame: Integer; AProcSym: TFpSymbol): TFpDbgLocationContext; inline; deprecated 'use TFpDbgSimpleLocationContext.Create';
    function  GetLib(const AHandle: THandle; out ALib: TDbgLibrary): Boolean;
    property  LibMap: TLibraryMap read FLibMap;
    property  LastLibrariesLoaded: TDbgLibraryArr read GetLastLibrariesLoaded;
    property  LastLibrariesUnloaded: TDbgLibraryArr read GetLastLibrariesUnloaded;
    procedure UpdateBreakpointsForLibraryLoaded(ALib: TDbgLibrary);
    procedure UpdateBreakpointsForLibraryUnloaded(ALib: TDbgLibrary);
    function  GetThread(const AID: Integer; out AThread: TDbgThread): Boolean;
    procedure RemoveBreak(const ABreakPoint: TFpDbgBreakpoint);
    procedure DoBeforeBreakLocationMapChange;
    function  HasBreak(const ALocation: TDbgPtr): Boolean; // TODO: remove, once an address can have many breakpoints
    procedure RemoveThread(const AID: DWord);
    function FormatAddress(const AAddress): String;
    function  Pause: boolean; virtual;

    function ReadData(const AAdress: TDbgPtr; const ASize: Cardinal; out AData): Boolean; virtual;
    function ReadData(const AAdress: TDbgPtr; const ASize: Cardinal; out AData; out APartSize: Cardinal): Boolean; virtual;
    function ReadAddress(const AAdress: TDbgPtr; out AData: TDBGPtr): Boolean; virtual;
    function ReadOrdinal(const AAdress: TDbgPtr; out AData): Boolean; virtual;
    function ReadString(const AAdress: TDbgPtr; const AMaxSize: Cardinal; out AData: String): Boolean; virtual;
    function ReadWString(const AAdress: TDbgPtr; const AMaxSize: Cardinal; out AData: WideString): Boolean; virtual;
    // Get the default location for parameters in default calling mode // Note functions may take result as argument
    function CallParamDefaultLocation(AParamIdx: Integer): TFpDbgMemLocation; virtual;

    //function LocationIsBreakInstructionCode(const ALocation: TDBGPtr): Boolean; // excludes TempRemoved
    procedure TempRemoveBreakInstructionCode(const ALocation: TDBGPtr);
    procedure RestoreTempBreakInstructionCodes;
    function HasInsertedBreakInstructionAtLocation(const ALocation: TDBGPtr): Boolean; // returns Int3, if there is no break at this location

    function CanContinueForWatchEval(ACurrentThread: TDbgThread): boolean; virtual;
    function Continue(AProcess: TDbgProcess; AThread: TDbgThread; SingleStep: boolean): boolean; virtual;
    function WaitForDebugEvent(out ProcessIdentifier, ThreadIdentifier: THandle): boolean; virtual; abstract;
    function ResolveDebugEvent(AThread: TDbgThread): TFPDEvent; virtual;

    // Remove (and free if applicable) all breakpoints for this process. When a
    // library is specified as OnlyForLibrary, only breakpoints that belong to this
    // library are cleared.
    procedure RemoveAllBreakPoints;

    function CheckForConsoleOutput(ATimeOutMs: integer): integer; virtual;
    function GetConsoleOutput: string; virtual;
    procedure SendConsoleInput(AString: string); virtual;

    procedure ClearAddedAndRemovedLibraries;
    procedure DoBeforeProcessLoop;
    function AddThread(AThreadIdentifier: THandle): TDbgThread;
    function GetThreadArray: TFPDThreadArray;
    procedure ThreadsBeforeContinue;
    procedure ThreadsClearCallStack;
    procedure LoadInfo; override;

    function WriteData(const AAdress: TDbgPtr; const ASize: Cardinal; const AData): Boolean; virtual;
    // Modify the debugee's code.
    function WriteInstructionCode(const AAdress: TDbgPtr; const ASize: Cardinal; const AData): Boolean; virtual;

    procedure TerminateProcess; virtual; abstract;
    function Detach(AProcess: TDbgProcess; AThread: TDbgThread): boolean; virtual;

    property OSDbgClasses: TOSDbgClasses read FOSDbgClasses;
    property RequiresExecutionInDebuggerThread: boolean read GetRequiresExecutionInDebuggerThread;
    property Handle: THandle read GetHandle;
    property Name: String read FFileName write SetFileName;
    property ProcessID: integer read FProcessID;
    property ThreadID: integer read FThreadID;
    property ExitCode: DWord read FExitCode;
    property CurrentBreakpoint: TFpInternalBreakpoint read FCurrentBreakpoint;
    property CurrentBreakpointList: TFpInternalBreakpointArray read FCurrentBreakpointList; experimental; // need getter
    property CurrentWatchpoint: Pointer read FCurrentWatchpoint;
    property PauseRequested: boolean read GetPauseRequested write SetPauseRequested;
    function GetAndClearPauseRequested: Boolean;

    // Properties valid when last event was an deException
    property ExceptionMessage: string read FExceptionMessage write FExceptionMessage;
    property ExceptionClass: string read FExceptionClass write FExceptionClass;
    property OnDebugOutputEvent: TDebugOutputEvent read FOnDebugOutputEvent write FOnDebugOutputEvent;

    property LastEventProcessIdentifier: THandle read GetLastEventProcessIdentifier;
    property MainThread: TDbgThread read FMainThread;
    property GotExitProcess: Boolean read FGotExitProcess write FGotExitProcess;
    property Disassembler: TDbgAsmDecoder read GetDisassembler;
    property ThreadMap: TThreadMap read FThreadMap;
    property Config: TDbgConfig read FConfig;
    property GlobalCache: TFpDbgDataCache read FGlobalCache write FGlobalCache;
  end;
  TDbgProcessClass = class of TDbgProcess;

  { TFpWatchPointData }

  TFpWatchPointData = class
  private
    FChanged: Boolean;
  public
    function AddOwnedWatchpoint(AnOwner: Pointer; AnAddr: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind): boolean; virtual;
    function RemoveOwnedWatchpoint(AnOwner: Pointer): boolean; virtual;
    property Changed: Boolean read FChanged write FChanged;
  end;

  { TFpIntelWatchPointData }

  TFpIntelWatchPointData = class(TFpWatchPointData)
  private
    // For Intel: Dr0..Dr3
    FOwners: array [0..3] of Pointer;
    FDr03: array [0..3] of TDBGPtr;
    FDr7: DWord;
    function GetDr03(AnIndex: Integer): TDBGPtr; inline;
    function GetOwner(AnIndex: Integer): Pointer; inline;
  public
    function AddOwnedWatchpoint(AnOwner: Pointer; AnAddr: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind): boolean; override;
    function RemoveOwnedWatchpoint(AnOwner: Pointer): boolean; override;
    property Dr03[AnIndex: Integer]: TDBGPtr read GetDr03;
    property Dr7: DWord read FDr7;
    property Owner[AnIndex: Integer]: Pointer read GetOwner;
  end;

  { TOSDbgClasses }

  TOSDbgClasses = class
  public
    DbgProcessClass : TDbgProcessClass;
    DbgThreadClass : TDbgThreadClass;
    DbgDisassemblerClass : TDbgDisassemblerClass;
    constructor Create(
      ADbgProcessClass: TDbgProcessClass;
      ADbgThreadClass: TDbgThreadClass;
      ADbgDisassemblerClass: TDbgDisassemblerClass
    );
    function Equals(AnOther: TOSDbgClasses): Boolean;
  end;

const
  FPDEventNames: array[TFPDEvent] of string = (
    'deNone',
    'deExitProcess', 'deCreateProcess',
    'deLoadLibrary', 'deUnloadLibrary',
    'deFinishedStep', 'deBreakpoint', 'deHardCodedBreakpoint',
    'deException',
    'deInternalContinue',
    'deDetachFromProcess',
    'deFailed'
  );


(* TODO:  refactor those methods to work with a Context, and move (partly) to CFI *)
// GetCanonicalFrameAddress: Get FrameBase
function GetCanonicalFrameAddress(RegisterValueList: TDbgRegisterValueList;
  Row: TDwarfCallFrameInformationRow; out FrameBase: TDBGPtr): Boolean;
function TryObtainNextCallFrame( CurrentCallStackEntry: TDbgCallstackEntry;
  CIE: TDwarfCIE; Size, NextIdx: Integer; Thread: TDbgThread;
  Row: TDwarfCallFrameInformationRow; Process: TDbgProcess;
  out NewCallStackEntry: TDbgCallstackEntry): Boolean;

function GetDbgProcessClass(ATargetInfo: TTargetDescriptor): TOSDbgClasses;

procedure RegisterDbgOsClasses(ADbgOsClasses: TOSDbgClasses);

implementation

uses
  FpDbgDwarfDataClasses,
  FpDbgDwarf;

type
  TOSDbgClassesList = class(specialize TFPGObjectList<TOSDbgClasses>)
  public
    function Find(a: TOSDbgClasses): Integer;
  end;
var
  DBG_VERBOSE, DBG_WARNINGS, DBG_BREAKPOINTS, FPDBG_COMMANDS, FPDBG_DWARF_CFI_WARNINGS: PLazLoggerLogGroup;
  RegisteredDbgProcessClasses: TOSDbgClassesList;

function GetDbgProcessClass(ATargetInfo: TTargetDescriptor): TOSDbgClasses;
var
  i   : Integer;
begin
  for i := 0 to RegisteredDbgProcessClasses.Count - 1 do
  begin
    Result := RegisteredDbgProcessClasses[i];
    try
      if Result.DbgProcessClass.isSupported(ATargetInfo) then
        Exit;
    except
      on e: exception do
      begin
        //writeln('exception! WHY? ', e.Message);
      end;
    end;
  end;
  Result := nil;
end;

procedure RegisterDbgOsClasses(ADbgOsClasses: TOSDbgClasses);
begin
  if not Assigned(RegisteredDbgProcessClasses) then
    RegisteredDbgProcessClasses := TOSDbgClassesList.Create;
  if RegisteredDbgProcessClasses.Find(ADbgOsClasses) < 0 then // TODO: by content
    RegisteredDbgProcessClasses.Add(ADbgOsClasses);
end;

{ TFpDbgBreakpoint }

function TFpDbgBreakpoint.GetState: TFpDbgBreakpointState;
begin
  Result := bksUnknown;
end;

procedure TFpDbgBreakpoint.SetFreeByDbgProcess(AValue: Boolean);
begin
  FFreeByDbgProcess := AValue;
end;

procedure TFpDbgBreakpoint.SetEnabled(AValue: boolean);
begin
  if AValue then
    SetBreak
  else
    ResetBreak;
end;

{ TDbgCallstackEntryList }

procedure TDbgCallstackEntryList.SetHasReadAllAvailableFrames;
begin
  FHasReadAllAvailableFrames := True;
end;

procedure TDbgCallstackEntryList.Clear;
begin
  inherited Clear;
  FHasReadAllAvailableFrames := False;
end;

{ TOSDbgClasses }

constructor TOSDbgClasses.Create(ADbgProcessClass: TDbgProcessClass;
  ADbgThreadClass: TDbgThreadClass;
  ADbgDisassemblerClass: TDbgDisassemblerClass);
begin
  DbgProcessClass      := ADbgProcessClass;
  DbgThreadClass       := ADbgThreadClass;
  DbgDisassemblerClass := ADbgDisassemblerClass;
end;

function TOSDbgClasses.Equals(AnOther: TOSDbgClasses): Boolean;
begin
  Result := (DbgThreadClass       = AnOther.DbgThreadClass) and
            (DbgProcessClass      = AnOther.DbgProcessClass) and
            (DbgDisassemblerClass = AnOther.DbgDisassemblerClass);
end;

{ TOSDbgClassesList }

function TOSDbgClassesList.Find(a: TOSDbgClasses): Integer;
begin
  Result := Count - 1;
  while (Result >= 0) and not (Items[Result].Equals(a)) do
    dec(Result);
end;

{ TThreadMapUnLockedEnumerator }

function TThreadMapUnLockedEnumerator.GetCurrent: TDbgThread;
begin
  GetData(Result);
end;

function TThreadMapUnLockedEnumerator.MoveNext: Boolean;
begin
  if FDoneFirst then
    Next
  else
    First;
  FDoneFirst := True;
  Result := not EOM;
end;

{ TThreadMapEnumerator }

function TThreadMapEnumerator.GetCurrent: TDbgThread;
begin
  GetData(Result);
end;

function TThreadMapEnumerator.MoveNext: Boolean;
begin
  if FDoneFirst then
    Next
  else
    First;
  FDoneFirst := True;
  Result := not EOM;
end;

{ TThreadMap }

function TThreadMap.GetEnumerator: TThreadMapEnumerator;
begin
  Result := TThreadMapEnumerator.Create(Self);
end;

procedure TThreadMap.Add(const AId, AData);
begin
  inc(FNumCounter);
  TDbgThread(AData).FNum := FNumCounter;
  inherited Add(AId, AData);
end;

{ TLibraryMapEnumerator }

function TLibraryMapEnumerator.GetCurrent: TDbgLibrary;
begin
  GetData(Result);
end;

function TLibraryMapEnumerator.MoveNext: Boolean;
begin
  if FDoneFirst then
    Next
  else
    First;
  FDoneFirst := True;
  Result := not EOM;
end;

{ TLibraryMap }

function TLibraryMap.GetEnumerator: TLibraryMapEnumerator;
begin
  Result := TLibraryMapEnumerator.Create(Self);
end;

procedure TLibraryMap.Add(const AId, AData);
begin
  inherited Add(AId, AData);
  FLibrariesAdded := Concat(FLibrariesAdded, [TDbgLibrary(AData)]);
end;

function TLibraryMap.Delete(const AId): Boolean;
var
  ALib: TDbgLibrary;
begin
  if GetData(AId, ALib) then
    FLibrariesRemoved := Concat(FLibrariesRemoved, [TDbgLibrary(ALib)]);
  Result := inherited Delete(AId);
end;

function TLibraryMap.GetLib(const AHandle: THandle; out ALib: TDbgLibrary
  ): Boolean;
var
  Iterator: TMapIterator;
  Lib: TDbgLibrary;
begin
  Result := False;
  Iterator := TMapIterator.Create(Self);
  while not Iterator.EOM do
  begin
    Iterator.GetData(Lib);
    Result := Lib.ModuleHandle = AHandle;
    if Result
    then begin
      ALib := Lib;
      Break;
    end;
    Iterator.Next;
  end;
  Iterator.Free;
end;

function TLibraryMap.GetLib(const AName: String; out ALib: TDbgLibrary;
  IsFullName: Boolean): Boolean;
var
  Iterator: TMapIterator;
  Lib: TDbgLibrary;
  s: String;
begin
  Result := False;
  Iterator := TMapIterator.Create(Self);
  while not Iterator.EOM do
  begin
    Iterator.GetData(Lib);
    if IsFullName then
      s := Lib.Name
    else
      s := ExtractFileName(Lib.Name);
    Result := CompareText(s, AName) = 0;
    if Result
    then begin
      ALib := Lib;
      Break;
    end;
    Iterator.Next;
  end;
  Iterator.Free;
end;

procedure TLibraryMap.ClearAddedAndRemovedLibraries;
var
  lib: TDbgLibrary;
begin
  for lib in FLibrariesRemoved do
    lib.Free;
  FLibrariesAdded := [];
  FLibrariesRemoved := [];
end;

{ TFpBreakPointMap.TFpBreakPointMapEnumerator }

function TFpBreakPointMap.TFpBreakPointMapEnumerator.GetCurrent: TFpBreakPointMapEnumerationData;
begin
  Result.MapDataPtr := DataPtr;
  Result.TargetHandlerDataPtr := @Result.MapDataPtr^.TargetHandlerData;
  GetID(Result.Location);
end;

function TFpBreakPointMap.TFpBreakPointMapEnumerator.MoveNext: Boolean;
begin
  if FDoneFirst then
    Next
  else
    First;
  FDoneFirst := True;
  Result := not EOM;
end;

{ TFpBreakPointMap }

constructor TFpBreakPointMap.Create(AProcess: TDbgProcess;
  ATargetHandler: TFpBreakPointTargetHandler);
begin
  FProcess := AProcess;
  FTargetHandler := ATargetHandler;
  ATargetHandler.BreakMap := Self;
  FDataSize := SizeOf(TFpBreakPointMapEntry) + ATargetHandler.GetDataSize;
  FTmpDataPtr := AllocMem(FDataSize);
  inherited Create(itu8, FDataSize);
end;

destructor TFpBreakPointMap.Destroy;
begin
  Clear;
  Freemem(FTmpDataPtr);
  inherited Destroy;
end;

procedure TFpBreakPointMap.Clear;
var
  MapEnumData: TFpBreakPointMap.TFpBreakPointMapEnumerationData;
begin
  debugln(DBG_VERBOSE or DBG_BREAKPOINTS, ['TGenericBreakPointTargetHandler.Clear ']);
  for MapEnumData in Self do begin
    if MapEnumData.MapDataPtr^.IsBreakList then
      TFpInternalBreakpointArray(MapEnumData.MapDataPtr^.InternalBreakPoint) := nil;
  end;
  inherited Clear;
end;

procedure TFpBreakPointMap.AddLocation(const ALocation: TDBGPtr;
  const AnInternalBreak: TFpInternalBreakpoint; AnIgnoreIfExists: Boolean;
  AForceRetrySetting: Boolean);
var
  MapEntryPtr: PFpBreakPointMapEntry;
  Len, i: Integer;
  BList: TFpInternalBreakpointArray;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadIdNotMain('TGenericBreakPointTargetHandler.AddLocation');{$ENDIF}
  MapEntryPtr := GetDataPtr(ALocation);

  if MapEntryPtr <> nil then begin
    if MapEntryPtr^.IsBreakList then begin
      Len := Length(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint));
      if AnIgnoreIfExists then begin
        i := Len - 1;
        while (i >= 0) and (TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i] <> AnInternalBreak) do
          dec(i);
        if i >= 0 then
          exit;
      end;

      SetLength(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint), Len+1);
      TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[Len] := AnInternalBreak;
    end
    else begin
      if AnIgnoreIfExists and (TFpInternalBreakpoint(MapEntryPtr^.InternalBreakPoint) = AnInternalBreak) then
        exit;

      MapEntryPtr^.IsBreakList := True;
      SetLength(BList, 2);
      BList[0] := TFpInternalBreakpoint(MapEntryPtr^.InternalBreakPoint);
      BList[1] := AnInternalBreak;
      MapEntryPtr^.InternalBreakPoint := nil;
      TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint) := BList;
    end;

    if MapEntryPtr^.ErrorSetting then begin
      if AForceRetrySetting then begin
        FProcess.DoBeforeBreakLocationMapChange; // Only if a new breakpoint is set => memory changed
        MapEntryPtr^.ErrorSetting := not TargetHandler.InsertBreakInstructionCode(ALocation, AnInternalBreak, @MapEntryPtr^.TargetHandlerData);
        if MapEntryPtr^.ErrorSetting then begin
          AnInternalBreak.AddErrorSetting(ALocation);
        end
        else
        if MapEntryPtr^.IsBreakList then begin
          debugln(DBG_VERBOSE or DBG_BREAKPOINTS, ['Retrying failed breakpoint updated multiple instances']);
          for i := 0 to Length(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)) - 1 do
            if TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i] <> AnInternalBreak then
              TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i].RemoveErrorSetting(ALocation);
        end;
      end
      else begin
        AnInternalBreak.AddErrorSetting(ALocation);
      end;
    end;
    exit;
  end;


  FillByte(FTmpDataPtr^, FDataSize, 0);
  FTmpDataPtr^.IsBreakList := False;
  FTmpDataPtr^.InternalBreakPoint := AnInternalBreak;

  FProcess.DoBeforeBreakLocationMapChange; // Only if a new breakpoint is set => memory changed
  FTmpDataPtr^.ErrorSetting := not TargetHandler.InsertBreakInstructionCode(ALocation, AnInternalBreak, @FTmpDataPtr^.TargetHandlerData);
  if FTmpDataPtr^.ErrorSetting then
    AnInternalBreak.AddErrorSetting(ALocation);

  Add(ALocation, FTmpDataPtr^);
end;

procedure TFpBreakPointMap.RemoveLocation(const ALocation: TDBGPtr;
  const AnInternalBreak: TFpInternalBreakpoint);
var
  MapEntryPtr: PFpBreakPointMapEntry;
  Len, i: Integer;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadIdNotMain('TGenericBreakPointTargetHandler.RemoveLocation');{$ENDIF}
  MapEntryPtr := GetDataPtr(ALocation);
  if MapEntryPtr = nil then begin
    DebugLn(DBG_WARNINGS or DBG_BREAKPOINTS, ['Missing breakpoint for loc ', FormatAddress(ALocation)]);
    exit;
  end;

  if MapEntryPtr^.IsBreakList then begin
    Len := Length(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint));
    i := Len - 1;
    while (i >= 0) and (TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i] <> AnInternalBreak) do
      dec(i);
    if i < 0 then begin
      DebugLn(DBG_WARNINGS or DBG_BREAKPOINTS, ['Wrong break for loc ', FormatAddress(ALocation)]);
      exit;
    end;
    if i < Len - 1 then
      move(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i+1],
           TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)[i],
           (Len - 1 - i) * sizeof(TFpInternalBreakpoint));
    SetLength(TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint), Len-1);
    if MapEntryPtr^.ErrorSetting then
      AnInternalBreak.RemoveErrorSetting(ALocation);

    if Len > 1 then
      exit;
  end
  else begin
    if AnInternalBreak <> TFpInternalBreakpoint(MapEntryPtr^.InternalBreakPoint) then begin
      DebugLn(DBG_WARNINGS or DBG_BREAKPOINTS, ['Wrong break for loc ', FormatAddress(ALocation)]);
      exit;
    end;

    if MapEntryPtr^.ErrorSetting then
      AnInternalBreak.RemoveErrorSetting(ALocation);
  end;

  FProcess.DoBeforeBreakLocationMapChange; // Only if a breakpoint is removed => memory changed
  if not MapEntryPtr^.ErrorSetting then
    TargetHandler.RemoveBreakInstructionCode(ALocation, AnInternalBreak, @MapEntryPtr^.TargetHandlerData);
  Delete(ALocation);
end;

function TFpBreakPointMap.HasInsertedBreakInstructionAtLocation(
  const ALocation: TDBGPtr): Boolean;
begin
  Result := GetDataPtr(ALocation) <> nil;
end;

function TFpBreakPointMap.GetInternalBreaksAtLocation(const ALocation: TDBGPtr): TFpInternalBreakpointArray;
var
  MapEntryPtr: PFpBreakPointMapEntry;
begin
  MapEntryPtr := GetDataPtr(ALocation);
  if MapEntryPtr = nil then begin
    DebugLn(DBG_WARNINGS or DBG_BREAKPOINTS, ['Missing breakpoint for loc ', FormatAddress(ALocation)]);
    Result := nil;
    exit;
  end;

  if MapEntryPtr^.IsBreakList then begin
    Result := TFpInternalBreakpointArray(MapEntryPtr^.InternalBreakPoint)
  end
  else begin
    SetLength(Result, 1);
    Result[0] := TFpInternalBreakpoint(MapEntryPtr^.InternalBreakPoint);
  end;
end;

function TFpBreakPointMap.GetDataPtr(const AId): PFpBreakPointMapEntry;
begin
  Result := inherited GetDataPtr(AId);
end;

function TFpBreakPointMap.GetTargetDataPtr(const AId): PFpBreakPointTargetHandlerDataPointer;
var
  r: PFpBreakPointMapEntry;
begin
  r := GetDataPtr(AId);
  if r = nil then
    Result := nil
  else
    Result := @GetDataPtr(AId)^.TargetHandlerData;
end;

function TFpBreakPointMap.GetEnumerator: TFpBreakPointMapEnumerator;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadId('TGenericBreakPointTargetHandler.GetEnumerator');{$ENDIF}
  Result := TFpBreakPointMapEnumerator.Create(Self);
end;

{ TFpBreakPointTargetHandler }

constructor TFpBreakPointTargetHandler.Create(AProcess: TDbgProcess);
begin
  FProcess := AProcess;
  inherited Create;
end;

{ TGenericBreakPointTargetHandler }

function TGenericBreakPointTargetHandler.GetDataSize: integer;
begin
  Result := SizeOf(TInternalBreakLocationEntry);
end;

procedure TGenericBreakPointTargetHandler.UpdateMapForNewTargetCode(const AAdress: TDbgPtr;
  const ASize: Cardinal; const AData);
var
  i: Integer;
begin
  for i := 0 to ASize -1 do
    if BreakMap.HasInsertedBreakInstructionAtLocation(AAdress+i) then
      AdaptOriginalValueAtLocation(AAdress+i, PByte(@AData+i)^);
end;

function TGenericBreakPointTargetHandler.GetOrigValueAtLocation(const ALocation: TDBGPtr
  ): _BRK_STORE;
var
  LocData: PInternalBreakLocationEntry;
begin
  LocData := HPtr(BreakMap.GetTargetDataPtr(ALocation));
  if LocData = nil then begin
    DebugLn(DBG__WARNINGS or DBG__BREAKPOINTS, ['Missing breakpoint for loc ', FormatAddress(ALocation)]);
    Result := _BREAK._CODE;
    exit;
  end;
  Result := LocData^.OrigValue;
end;

function TGenericBreakPointTargetHandler.IsHardcodeBreakPoint(const ALocation: TDBGPtr
  ): Boolean;
begin
  Result := GetOrigValueAtLocation(ALocation) = _BREAK._CODE;
end;

function TGenericBreakPointTargetHandler.IsHardcodeBreakPointInCode(
  const ALocation: TDBGPtr): Boolean;
var
  OVal: _BRK_STORE;
begin
  Result := False;
  if Process.ReadData(ALocation, SizeOf(_BRK_STORE), OVal) then
    Result := OVal = _BREAK._CODE;
end;

procedure TGenericBreakPointTargetHandler.TempRemoveBreakInstructionCode(
  const ALocation: TDBGPtr);
var
  OVal: _BRK_STORE;
  l, i: Integer;
begin
  DebugLn(DBG__VERBOSE or DBG__BREAKPOINTS, ['>>> TempRemoveBreakInstructionCode']);
  l := length(FTmpRemovedBreaks);
  for i := 0 to l-1 do
    if FTmpRemovedBreaks[i] = ALocation then
      exit;

  OVal := GetOrigValueAtLocation(ALocation);
  if OVal = _BREAK._CODE then
    exit;

  SetLength(FTmpRemovedBreaks, l+1);
  FTmpRemovedBreaks[l] := ALocation;
  DoRemoveBreakInstructionCode(ALocation, OVal); // Do not update FBreakMap
  DebugLn(DBG__VERBOSE or DBG__BREAKPOINTS, ['<<< TempRemoveBreakInstructionCode']);
end;

procedure TGenericBreakPointTargetHandler.RestoreTempBreakInstructionCodes;
var
  OVal: _BRK_STORE;
  t: array of TDBGPtr;
  i: Integer;
begin
  if Length(FTmpRemovedBreaks) = 0 then
    exit;
  DebugLnEnter(DBG__VERBOSE or DBG__BREAKPOINTS, ['>>> RestoreTempBreakInstructionCodes']);
  t := FTmpRemovedBreaks;
  FTmpRemovedBreaks := nil;
  for i := 0 to length(t) - 1 do
    if BreakMap.HasId(t[i]) then // may have been removed
      DoInsertBreakInstructionCode(t[i], OVal, False);
  DebugLnExit(DBG__VERBOSE or DBG__BREAKPOINTS, ['<<< RestoreTempBreakInstructionCodes']);
end;

procedure TGenericBreakPointTargetHandler.MaskBreakpointsInReadData(const AAdress: TDbgPtr;
  const ASize: Cardinal; var AData);
var
  MapEnumData: TFpBreakPointMap.TFpBreakPointMapEnumerationData;
  i, len: TDBGPtr;
  PtrOrig: Pointer;
begin
  for MapEnumData in BreakMap do begin
    // Does break instruction fall completely outside AData
    {$PUSH}{$R-}{$Q-}
    if (MapEnumData.Location + SizeOf(_BRK_STORE) <= AAdress) or
       (MapEnumData.Location >= (AAdress + ASize)) or
       (MapEnumData.MapDataPtr^.ErrorSetting)
    then
      continue;
    {$POP}

    if (MapEnumData.Location >= AAdress) and (MapEnumData.Location + SizeOf(_BRK_STORE) <= (AAdress + ASize)) then begin
      // Breakpoint is completely inside AData
      // MapEnumData.Location >= AAdress
      i := MapEnumData.Location - AAdress;
      P_BRK_STORE(@AData + i)^ := HPtr(MapEnumData.TargetHandlerDataPtr)^.OrigValue;
    end
    else
    if (MapEnumData.Location < AAdress) then begin
      // Breakpoint starts on or partially overlaps with start of AData
      // Breakpoint may overhang past end of AData
      // AAdress > MapEnumData.Location
      i := AAdress - MapEnumData.Location;
      // i < SizeOf(_BRK_STORE) / since MapEnumData.Location + SizeOf(_BRK_STORE) > AAdress
      len := SizeOf(_BRK_STORE) - i;
      // Do not write past end of AData
      if len > ASize then
        len := ASize;

      PtrOrig := @HPtr(MapEnumData.TargetHandlerDataPtr)^.OrigValue;
      move(PByte(PtrOrig+i)^, PByte(@AData)^, len);
    end
    else begin
      // Breakpoint partially overlaps with end of AData
      // MapEnumData.Location > AAdress
      // MapEnumData.Location < AAdress + ASize;
      i := MapEnumData.Location - AAdress;
      len := ASize - i;  // AAdress + ASize - MapEnumData.Location;
      PtrOrig := @HPtr(MapEnumData.TargetHandlerDataPtr)^.OrigValue;
      move(PByte(PtrOrig)^, PByte(@AData+i)^, len);
    end;
  end;
end;

procedure TGenericBreakPointTargetHandler.AdaptOriginalValueAtLocation(const ALocation: TDBGPtr; const NewOrigValue: _BRK_STORE);
var
  LocData: PInternalBreakLocationEntry;
begin
  LocData := HPtr(BreakMap.GetTargetDataPtr(ALocation));
  if Assigned(LocData) then
    LocData^.OrigValue := NewOrigValue;
end;

function TGenericBreakPointTargetHandler.DoInsertBreakInstructionCode(
  const ALocation: TDBGPtr; out OrigValue: _BRK_STORE;
  AMakeTempRemoved: Boolean): Boolean;
begin
  Result := Process.ReadData(ALocation, SizeOf(_BRK_STORE), OrigValue);
  if not Result then begin
    DebugLn(DBG__WARNINGS or DBG__BREAKPOINTS, 'Unable to read pre-breakpoint at '+FormatAddress(ALocation));
    exit;
  end;

  if (OrigValue = _BREAK._CODE) or AMakeTempRemoved then
    exit; // breakpoint on a hardcoded breakpoint

  Process.BeforeChangingInstructionCode(ALocation, SizeOf(_BRK_STORE));

  Result := Process.WriteData(ALocation, SizeOf(_BRK_STORE), _BREAK._CODE);
  DebugLn(DBG__VERBOSE or DBG__BREAKPOINTS, ['Breakpoint set to '+Process.FormatAddress(ALocation), ' Result:',Result, ' OVal:', OrigValue]);
  if not Result then
    DebugLn(DBG__WARNINGS or DBG__BREAKPOINTS, 'Unable to set breakpoint at '+FormatAddress(ALocation));

  if Result then
    Process.AfterChangingInstructionCode(ALocation, SizeOf(_BRK_STORE));
end;

function TGenericBreakPointTargetHandler.DoRemoveBreakInstructionCode(
  const ALocation: TDBGPtr; const OrigValue: _BRK_STORE): Boolean;
begin
  if OrigValue = _BREAK._CODE then
    exit(True); // breakpoint on a hardcoded breakpoint

  Process.BeforeChangingInstructionCode(ALocation, SizeOf(_BRK_STORE));

  Result := Process.WriteData(ALocation, SizeOf(_BRK_STORE), OrigValue);
  DebugLn(DBG__VERBOSE or DBG__BREAKPOINTS, ['Breakpoint removed from '+FormatAddress(ALocation), ' Result:',Result, ' OVal:', OrigValue]);
  DebugLn((not Result) and (not Process.GotExitProcess) and (DBG__WARNINGS or DBG__BREAKPOINTS), 'Unable to reset breakpoint at %s', [FormatAddress(ALocation)]);

  if Result then
    Process.AfterChangingInstructionCode(ALocation, SizeOf(_BRK_STORE));
end;

function TGenericBreakPointTargetHandler.HPtr(Src: PFpBreakPointTargetHandlerDataPointer): PInternalBreakLocationEntry;
begin
  Result := PInternalBreakLocationEntry(Src);
end;

function TGenericBreakPointTargetHandler.InsertBreakInstructionCode(const ALocation: TDBGPtr;
  const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer
  ): boolean;
var
  LocData: PInternalBreakLocationEntry absolute AnEntry;
  IsTempRemoved: Boolean;
  i: Integer;
begin
  Result := False;
  IsTempRemoved := False;
  for i := 0 to high(FTmpRemovedBreaks) do begin
    IsTempRemoved := ALocation = FTmpRemovedBreaks[i];
    if IsTempRemoved then
      break;
  end;

  Result := DoInsertBreakInstructionCode(ALocation, LocData^.OrigValue, IsTempRemoved);
end;

procedure TGenericBreakPointTargetHandler.RemoveBreakInstructionCode(const ALocation: TDBGPtr;
  const AnInternalBreak: TFpInternalBreakpoint; AnEntry: PFpBreakPointTargetHandlerDataPointer);
var
  LocData: PInternalBreakLocationEntry absolute AnEntry;
begin
  DoRemoveBreakInstructionCode(ALocation, LocData^.OrigValue);
end;

{ TDbgCallstackEntry }

function TDbgCallstackEntry.GetProcSymbol: TFpSymbol;
begin
  if not FIsSymbolResolved then begin
    if (FIndex > 0) and (FAnAddress <> 0) then
      FSymbol := FThread.Process.FindProcSymbol(FAnAddress - 1) // -1 => inside the call instruction
    else
      FSymbol := FThread.Process.FindProcSymbol(FAnAddress);

    if FSymbol is TFpSymbolDwarfDataProc then
      FSymbol := TFpSymbolDwarfDataProc(FSymbol).ResolveInternalFinallySymbol(FThread.Process);


    FIsSymbolResolved := FSymbol <> nil
  end;
  result := FSymbol;
end;

function TDbgCallstackEntry.GetFunctionName: string;
var
  Symbol: TFpSymbol;
begin
  Symbol := GetProcSymbol;
  if assigned(Symbol) then begin
    if Symbol is TFpSymbolTableProc then begin
      if AnAddress > Symbol.Address.Address then
        result := Format('%s+%d', [Symbol.Name, AnAddress - Symbol.Address.Address])
      else
        result := Symbol.Name;
    end
    else
      result := Symbol.Name;
  end
  else
    result := '';
end;

function TDbgCallstackEntry.GetContext: TFpDbgSimpleLocationContext;
begin
  Result := FContext;
end;

function TDbgCallstackEntry.GetLine: integer;
var
  Symbol: TFpSymbol;
begin
  Symbol := GetProcSymbol;
  if assigned(Symbol) then
    result := Symbol.Line
  else
    result := -1;
end;

function TDbgCallstackEntry.GetRegisterValueList: TDbgRegisterValueList;
var
  i: Integer;
  L: TDbgRegisterValueList;
  R: TDbgRegisterValue;
begin
  if (FAutoFillRegisters) and (FRegisterValueList.Count = 0) then begin
    FRegisterValueList.Assign(FThread.RegisterValueList);
    FAutoFillRegisters := False;
  end;
  Result := FRegisterValueList;
end;

function TDbgCallstackEntry.GetSourceFile: string;
var
  Symbol: TFpSymbol;
begin
  Symbol := GetProcSymbol;
  if assigned(Symbol) then
    result := Symbol.FileName
  else
    result := '';
end;

function TDbgCallstackEntry.GetSrcClassName: string;
var
  Symbol: TFpSymbol;
begin
  result := '';
  Symbol := GetProcSymbol;
  if assigned(Symbol) then begin
    Symbol := Symbol.Parent;
    if assigned(Symbol) then begin
      result := Symbol.Name;
      Symbol.ReleaseReference;
    end;
  end;
end;

procedure TDbgCallstackEntry.SetContext(AValue: TFpDbgSimpleLocationContext);
begin
  if FContext = AValue then
    exit;
  if FContext <> nil then
    FContext.ReleaseReference;
  FContext := AValue;
  if FContext <> nil then
    FContext.AddReference;
end;

constructor TDbgCallstackEntry.create(AThread: TDbgThread; AnIndex: integer; AFrameAddress, AnAddress: TDBGPtr);
begin
  FThread := AThread;
  FFrameAdress:=AFrameAddress;
  FAnAddress:=AnAddress;
  FIndex:=AnIndex;
  FRegisterValueList := TDbgRegisterValueList.Create;
end;

destructor TDbgCallstackEntry.Destroy;
begin
  FreeAndNil(FRegisterValueList);
  ReleaseRefAndNil(FSymbol);
  FContext.ReleaseReference;
  inherited Destroy;
end;

{ TDbgMemReader }

function TDbgMemReader.GetDbgThread(AContext: TFpDbgLocationContext): TDbgThread;
var
  Process: TDbgProcess;
begin
  Process := GetDbgProcess;
  // In fact, AContext should always be assigned, assuming that the main thread
  // should be used is dangerous. But functions like TFpDbgMemManager.ReadSignedInt
  // have a default value of nil for the context. Which is a lot of work to fix.
  if not Assigned(AContext) or not Process.GetThread(AContext.ThreadId, Result) then
    Result := Process.MainThread;
end;

function TDbgMemReader.ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean;
begin
  result := GetDbgProcess.ReadData(AnAddress, ASize, ADest^);
end;

function TDbgMemReader.ReadMemory(AnAddress: TDbgPtr; ASize: Cardinal;
  ADest: Pointer; out ABytesRead: Cardinal): Boolean;
begin
  result := GetDbgProcess.ReadData(AnAddress, ASize, ADest^, ABytesRead);
end;

function TDbgMemReader.ReadMemoryEx(AnAddress, AnAddressSpace: TDbgPtr; ASize: Cardinal; ADest: Pointer): Boolean;
begin
  Assert(AnAddressSpace>0,'TDbgMemReader.ReadMemoryEx ignores AddressSpace');
  result := GetDbgProcess.ReadData(AnAddress, ASize, ADest^);
end;

function TDbgMemReader.WriteMemory(AnAddress: TDbgPtr; ASize: Cardinal;
  ASource: Pointer): Boolean;
begin
  result := GetDbgProcess.WriteData(AnAddress, ASize, ASource^);
end;

function TDbgMemReader.ReadRegister(ARegNum: Cardinal; out AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean;
var
  ARegister: TDbgRegisterValue;
  StackFrame: Integer;
  AFrame: TDbgCallstackEntry;
  CtxThread: TDbgThread;
begin
  // TODO: Thread with ID
  result := false;
  CtxThread := GetDbgThread(AContext);
  if CtxThread = nil then
    exit;

  if AContext <> nil then // TODO: Always true?
    StackFrame := AContext.StackFrame
  else
    StackFrame := 0;
  if StackFrame = 0 then
    begin
    ARegister:=CtxThread.RegisterValueList.FindRegisterByDwarfIndex(ARegNum);
    end
  else
    begin
    CtxThread.PrepareCallStackEntryList(StackFrame+1);
    if CtxThread.CallStackEntryList.Count <= StackFrame then
      exit;
    AFrame := CtxThread.CallStackEntryList[StackFrame];
    if AFrame <> nil then
      ARegister:=AFrame.RegisterValueList.FindRegisterByDwarfIndex(ARegNum)
    else
      ARegister:=nil;
    end;
  if assigned(ARegister) then
    begin
    AValue := ARegister.NumValue;
    result := true;
    end;
end;

function TDbgMemReader.WriteRegister(ARegNum: Cardinal; const AValue: TDbgPtr; AContext: TFpDbgLocationContext): Boolean;
var
  ARegister: TDbgRegisterValue;
  StackFrame: Integer;
  CtxThread: TDbgThread;
begin
  result := false;
  CtxThread := GetDbgThread(AContext);
  if CtxThread = nil then
    exit;

  if AContext <> nil then // TODO: Always true?
    StackFrame := AContext.StackFrame
  else
    StackFrame := 0;
  if StackFrame = 0 then
    begin
    ARegister:=CtxThread.RegisterValueList.FindRegisterByDwarfIndex(ARegNum);
    if assigned(ARegister) then
      begin
      CtxThread.SetRegisterValue(ARegister.Name, AValue);
      CtxThread.LoadRegisterValues;
      result := true;
      end;
    end
end;

function TDbgMemReader.RegisterSize(ARegNum: Cardinal): Integer;
var
  ARegister: TDbgRegisterValue;
begin
  ARegister:=GetDbgProcess.MainThread.RegisterValueList.FindRegisterByDwarfIndex(ARegNum);
  if assigned(ARegister) then
    result := ARegister.Size
  else
    result := sizeof(pointer);
end;

function TDbgMemReader.RegisterNumber(ARegName: String; out ARegNum: Cardinal
  ): Boolean;
var
  ARegister: TDbgRegisterValue;
  CtxThread: TDbgThread;
begin
  Result := False;
  CtxThread := GetDbgThread(nil);
  if CtxThread = nil then
    exit;

  ARegister:=CtxThread.RegisterValueList.FindRegisterByName(ARegName);
  Result := ARegister <> nil;
  if Result then
    ARegNum := ARegister.DwarfIdx;
end;

function TDbgMemReader.GetRegister(const ARegNum: Cardinal; AContext: TFpDbgLocationContext
  ): TDbgRegisterValue;
var
  ARegister: TDbgRegisterValue;
  StackFrame: Integer;
  AFrame: TDbgCallstackEntry;
  CtxThread: TDbgThread;
begin
  // TODO: Thread with ID
  result := nil;
  CtxThread := GetDbgThread(AContext);
  if CtxThread = nil then
    exit;

  if AContext <> nil then // TODO: Always true?
    StackFrame := AContext.StackFrame
  else
    StackFrame := 0;
  if StackFrame = 0 then
    begin
    Result:=CtxThread.RegisterValueList.FindRegisterByDwarfIndex(ARegNum);
    end
  else
    begin
    CtxThread.PrepareCallStackEntryList(StackFrame+1);
    if CtxThread.CallStackEntryList.Count <= StackFrame then
      exit;
    AFrame := CtxThread.CallStackEntryList[StackFrame];
    if AFrame <> nil then
      Result:=AFrame.RegisterValueList.FindRegisterByDwarfIndex(ARegNum)
    else
      Result:=nil;
    end;
end;

{ TDbgRegisterValueList }

function TDbgRegisterValueList.GetDbgRegister(AName: string
  ): TDbgRegisterValue;
var
  i: integer;
begin
  AName := UpperCase(AName);
  for i := 0 to Count -1 do
    if UpperCase(Items[i].Name)=AName then
      begin
      result := items[i];
      exit;
      end;
  result := nil;
end;

function TDbgRegisterValueList.GetDbgRegisterAutoCreate(const AName: string
  ): TDbgRegisterValue;
begin
  result := GetDbgRegister(AName);
  if not Assigned(result) then
    begin
    result := TDbgRegisterValue.Create(AName);
    add(result);
    end;
end;

function TDbgRegisterValueList.GetDbgRegisterCreate(AName: string): TDbgRegisterValue;
begin
  result := TDbgRegisterValue.Create(AName);
  add(result);
end;

function TDbgRegisterValueList.GetIsModified(AReg: TDbgRegisterValue): boolean;
begin
  Result := FPreviousRegisterValueList <> nil;
  if not Result then
    exit;

  Result := not FPreviousRegisterValueList.FindRegisterByDwarfIndex(AReg.DwarfIdx).HasEqualVal(AReg);
end;

procedure TDbgRegisterValueList.Assign(ASource: TDbgRegisterValueList);
var
  i: Integer;
  Dest: TDbgRegisterValue;
begin
  If Count > ASource.Count then
    Count := ASource.Count;
  Capacity := ASource.Count;

  for i := 0 to ASource.Count - 1 do begin
    if i >= Count then begin
      Dest := TDbgRegisterValue.Create('');
      Add(Dest);
    end
    else
      Dest := Items[i];
    Dest.Assign(ASource[i]);
  end;
end;

function TDbgRegisterValueList.FindRegisterByDwarfIndex(AnIdx: cardinal): TDbgRegisterValue;
var
  i: Integer;
begin
  for i := 0 to Count-1 do
    if Items[i].DwarfIdx=AnIdx then
    begin
      result := Items[i];
      exit;
    end;
  result := nil;
end;

function TDbgRegisterValueList.FindRegisterByName(AnName: String
  ): TDbgRegisterValue;
begin
  Result := GetDbgRegister(AnName);
end;

{ TDbgAsmInstruction }

function TDbgAsmInstruction.IsCallInstruction: boolean;
begin
  Result := False;
end;

function TDbgAsmInstruction.IsReturnInstruction: boolean;
begin
  Result := False;
end;

function TDbgAsmInstruction.IsLeaveStackFrame: boolean;
begin
  Result := False;
end;

function TDbgAsmInstruction.ModifiesStackPointer: boolean;
begin
  Result := False;
end;

function TDbgAsmInstruction.IsJumpInstruction(IncludeConditional: Boolean;
  IncludeUncoditional: Boolean): boolean;
begin
  Result := False;
end;

function TDbgAsmInstruction.InstructionLength: Integer;
begin
  Result := 0;
end;

{ TDbgAsmDecoder }

function TDbgAsmDecoder.GetLastErrorWasMemReadErr: Boolean;
begin
  Result := False;
end;

function TDbgAsmDecoder.GetCanReverseDisassemble: boolean;
begin
  Result := false;
end;

procedure TDbgAsmDecoder.Disassemble(var AAddress: Pointer; out
  ACodeBytes: String; out ACode: String; out AnInfo: TDbgInstInfo);
begin
  AnInfo := Default(TDbgInstInfo);
  Disassemble(AAddress, ACodeBytes, ACode);
end;

// Naive backwards scanner, decode MaxInstructionSize
// if pointer to next instruction matches, done!
// If not decrease instruction size and try again.
// Many pitfalls with X86 instruction encoding...
// Avr may give 130/65535 = 0.2% errors per instruction reverse decoded
procedure TDbgAsmDecoder.ReverseDisassemble(var AAddress: Pointer; out
  ACodeBytes: String; out ACode: String);
var
  instrLen: integer;
  tmpAddress: PtrUint;
begin
  // Decode max instruction length backwards,
  instrLen := MaxInstructionSize + MinInstructionSize;
  repeat
    dec(instrLen, MinInstructionSize);
    tmpAddress := PtrUInt(AAddress) - instrLen;
    Disassemble(pointer(tmpAddress), ACodeBytes, ACode);
  until (tmpAddress >= PtrUInt(AAddress)) or (instrLen = MinInstructionSize);

  // After disassemble tmpAddress points to the starting address of next instruction
  // Decrement with the instruction length to point to the start of this instruction
  AAddress := AAddress - instrLen;
end;

function TDbgAsmDecoder.GetFunctionFrameInfo(AnAddress: TDBGPtr; out
  AnIsOutsideFrame: Boolean): Boolean;
begin
  Result := False;
end;

function TDbgAsmDecoder.IsAfterCallInstruction(AnAddress: TDBGPtr): boolean;
begin
  Result := True; // if we don't know, then assume yes
end;

function TDbgAsmDecoder.UnwindFrame(var AnAddress, AStackPtr, AFramePtr: TDBGPtr; AQuick: boolean;
  ARegisterValueList: TDbgRegisterValueList): boolean;
begin
  Result := False;
end;

{ TDbgInstance }


function TDbgInstance.FindProcSymbol(const AName: String; AIgnoreCase: Boolean
  ): TFpSymbol;
begin
  if FDbgInfo <> nil then
    Result := FDbgInfo.FindProcSymbol(AName)
  else
    Result := nil;
  if (Result = nil) and (SymbolTableInfo <> nil) then
    Result := SymbolTableInfo.FindProcSymbol(AName, AIgnoreCase);
end;

constructor TDbgInstance.Create(const AProcess: TDbgProcess);
begin
  FProcess := AProcess;
  FMemManager := AProcess.MemManager;
  FMemModel := AProcess.MemModel;
  FLoaderList := TDbgImageLoaderList.Create(True);

  inherited Create;
end;

destructor TDbgInstance.Destroy;
begin
  FreeAndNil(FDbgInfo);
  FreeAndNil(FSymbolTableInfo);
  FreeAndNil(FLoaderList);
  inherited;
end;

function TDbgInstance.GetLineAddresses(AFileName: String; ALine: Cardinal;
  var AResultList: TDBGPtrArray; AFindSibling: TGetLineAddrFindSibling;
  AMaxSiblingDistance: integer): Boolean;
var
  FoundLine: Integer;
begin
  FLastLineAddressesFoundFile := False;
  if Assigned(DbgInfo) and DbgInfo.HasInfo then
    Result := DbgInfo.GetLineAddresses(AFileName, ALine, AResultList, AFindSibling, @FoundLine, @FLastLineAddressesFoundFile, AMaxSiblingDistance)
  else
    Result := False;
end;

function TDbgInstance.FindProcSymbol(AAdress: TDbgPtr): TFpSymbol;
var
  LI: TFpSymbol;
begin
  {$PUSH}{$R-}{$Q-}
  AAdress := AAdress;
  {$POP}
  Result := nil;
  LI := FDbgInfo.FindLineInfo(AAdress);
  if (LI <> nil) and (LI.Kind in [skFunction, skProcedure]) then begin
    Result := LI;
  end
  else begin
    Result := FSymbolTableInfo.FindProcSymbol(AAdress);
    if (Result <> nil) and (Result is TFpSymbolTableProc) then
      TFpSymbolTableProc(Result).SetLineSym(LI);
    LI.ReleaseReference;
  end;
end;

function TDbgInstance.FindProcStartEndPC(AAdress: TDbgPtr; out AStartPC,
  AEndPC: TDBGPtr): boolean;
begin
  {$PUSH}{$R-}{$Q-}
  AAdress := AAdress;
  {$POP}
  Result := FDbgInfo.FindProcStartEndPC(AAdress, AStartPC, AEndPC);
end;

function TDbgInstance.EnclosesAddress(AnAddress: TDBGPtr): Boolean;
begin
  Result := EnclosesAddressRange(AnAddress, AnAddress);
end;

function TDbgInstance.EnclosesAddressRange(AStartAddress, AnEndAddress: TDBGPtr): Boolean;
begin
  Result := FLoaderList.EnclosesAddressRange(AStartAddress, AnEndAddress);
end;

procedure TDbgInstance.LoadInfo;
begin
  InitializeLoaders;
  if FLoaderList.TargetInfo.bitness = b64 then  //Image64Bit then
    FMode:=dm64
  else
    FMode:=dm32;
  FDbgInfo := TFpDwarfInfo.Create(FLoaderList, MemManager, MemModel);
  TFpDwarfInfo(FDbgInfo).LoadCompilationUnits;
  if self is TDbgProcess then
    FSymbolTableInfo := TFpSymbolInfo.Create(FLoaderList, MemManager, MemModel)
  else
    FSymbolTableInfo := TFpSymbolInfo.Create(FLoaderList, MemManager, ExtractFileNameOnly(FFileName), MemModel);
  TFpDwarfInfo(FDbgInfo).LoadCallFrameInstructions;
end;

procedure TDbgInstance.SetFileName(const AValue: String);
begin
  FFileName := AValue;
end;

procedure TDbgInstance.SetMode(AMode: TFPDMode);
begin
  FMode := AMode;
end;

function TDbgInstance.FindCallFrameInfo(AnAddress: TDBGPtr; out CIE: TDwarfCIE; out
  Row: TDwarfCallFrameInformationRow): Boolean;
begin
  if FDbgInfo <> nil then
    Result := (FDbgInfo as TFpDwarfInfo).FindCallFrameInfo(AnAddress, CIE, Row)
  else
    Result := False;
end;

function TDbgInstance.GetPointerSize: Integer;
const
  PTRSZ: array[TFPDMode] of Integer = (4, 8); // (dm32, dm64)
begin
  Result := PTRSZ[FMode];
end;

function TDbgInstance.GetOSDbgClasses: TOSDbgClasses;
begin
  Result := FProcess.OSDbgClasses;
end;

procedure TDbgInstance.InitializeLoaders;
begin
  // Do nothing;
end;

{ TDbgLibrary }

constructor TDbgLibrary.Create(const AProcess: TDbgProcess; const ADefaultName: String; const AModuleHandle: THandle);

begin
  inherited Create(AProcess);
  FModuleHandle:=AModuleHandle;
end;

{ TDbgProcess }

function TDbgProcess.AddBreak(const ALocation: TDBGPtr; AnEnabled: Boolean
  ): TFpDbgBreakpoint;
var
  a: TDBGPtrArray;
begin
  SetLength(a, 1);
  a[0] := ALocation;
  Result := AddBreak(a, AnEnabled);
// TODO: if a = GetInstructionPointerRegisterValue (of any thread?)
end;

function TDbgProcess.AddBreak(const ALocation: TDBGPtrArray; AnEnabled: Boolean
  ): TFpDbgBreakpoint;
begin
  Result := TFpInternalBreakpoint.Create(Self, ALocation, AnEnabled);
  AfterBreakpointAdded(Result);
end;

function TDbgProcess.AddBreak(const AFileName: String; ALine: Cardinal;
  AnEnabled: Boolean; ASymInstance: TDbgInstance): TFpDbgBreakpoint;
begin
  Result := TFpInternalBreakpointAtFileLine.Create(Self, AFileName, ALine, AnEnabled, ASymInstance);
  AfterBreakpointAdded(Result);
end;

function TDbgProcess.AddBreak(const AFuncName: String; AnEnabled: Boolean;
  ASymInstance: TDbgInstance; AIgnoreCase: Boolean): TFpDbgBreakpoint;
begin
  Result := TFpInternalBreakpointAtSymbol.Create(Self, AFuncName, AnEnabled, ASymInstance, AIgnoreCase);
  AfterBreakpointAdded(Result);
end;

function TDbgProcess.AddUserBreak(const ALocation: TDBGPtr; AnEnabled: Boolean): TFpDbgBreakpoint;
var
  a: TDBGPtrArray;
begin
  SetLength(a, 1);
  a[0] := ALocation;
  Result := TFpInternalBreakpointAtAddress.Create(Self, a, AnEnabled);
  AfterBreakpointAdded(Result);
// TODO: if a = GetInstructionPointerRegisterValue (of any thread?)
end;

function TDbgProcess.AddWatch(const ALocation: TDBGPtr; ASize: Cardinal;
  AReadWrite: TDBGWatchPointKind; AScope: TDBGWatchPointScope
  ): TFpInternalWatchpoint;
begin
  Result := TFpInternalWatchpoint.Create(Self, ALocation, ASize, AReadWrite, AScope);
end;

function TDbgProcess.FindProcSymbol(const AName: String; ASymInstance: TDbgInstance
  ): TFpSymbol;
var
  Lib: TDbgLibrary;
begin
  if ASymInstance <> nil then begin
    Result := ASymInstance.FindProcSymbol(AName);
  end
  else begin
    Result := FindProcSymbol(AName);
    if Result <> nil then
      exit;
    for Lib in FLibMap do begin
      Result := Lib.FindProcSymbol(AName);
      if Result <> nil then
        exit;
    end;
  end;
end;

procedure TDbgProcess.FindProcSymbol(const AName: String;
  ASymInstance: TDbgInstance; out ASymList: TFpSymbolArray; AIgnoreCase: Boolean
  );
var
  Lib: TDbgLibrary;
  Sym: TFpSymbol;
begin
  // TODO: find multiple symbols within the same DbgInfo
  ASymList := nil;
  if ASymInstance <> nil then begin
    Sym := ASymInstance.FindProcSymbol(AName, AIgnoreCase);
    if Sym <> nil then begin
      SetLength(ASymList, 1);
      ASymList[0] := Sym;
    end;
  end
  else begin
    Sym := FindProcSymbol(AName, AIgnoreCase);
    if Sym <> nil then begin
      SetLength(ASymList, 1);
      ASymList[0] := Sym;
    end;

    for Lib in FLibMap do begin
      Sym := Lib.FindProcSymbol(AName, AIgnoreCase);
      if Sym <> nil then begin
        SetLength(ASymList, 1);
        ASymList[0] := Sym;
      end;
    end;
  end;
end;

function TDbgProcess.FindProcSymbol(const AName: String): TFpSymbol;
begin
  Result := inherited FindProcSymbol(AName);
end;

function TDbgProcess.FindProcSymbol(const AName, ALibraryName: String;
  IsFullLibName: Boolean): TFpSymbol;
var
  lib: TDbgLibrary;
begin
  Result := nil;
  if not FLibMap.GetLib(ALibraryName, lib, IsFullLibName) then
    exit;
  Result := lib.FindProcSymbol(AName);
end;

constructor TDbgProcess.Create(const AFileName: string;
  AnOsClasses: TOSDbgClasses; AMemManager: TFpDbgMemManager;
  AMemModel: TFpDbgMemModel; AProcessConfig: TDbgProcessConfig);
const
  {.$IFDEF CPU64}
  MAP_ID_SIZE = itu8;
  {.$ELSE}
//  MAP_ID_SIZE = itu4;
  {.$ENDIF}
begin
  FConfig := CreateConfig;
  FMemManager := AMemManager;
  FMemModel := AMemModel;
  FProcessID := 0;
  FThreadID := 0;
  FOSDbgClasses := AnOsClasses;
  FProcessConfig := AProcessConfig;

  FGlobalCache := TFpDbgDataCache.Create;
  FBreakpointList := TFpInternalBreakpointList.Create(False);
  FWatchPointList := TFpInternalBreakpointList.Create(False);
  FThreadMap := TThreadMap.Create(itu4, SizeOf(TDbgThread));
  FLibMap := TLibraryMap.Create(MAP_ID_SIZE, SizeOf(TDbgLibrary));
  FWatchPointData := CreateWatchPointData;

  FBreakTargetHandler := CreateBreakPointTargetHandler;
  FBreakMap := TFpBreakPointMap.Create(Self, FBreakTargetHandler);
  FBreakTargetHandler.BreakMap := FBreakMap;

  FCurrentBreakpoint := nil;
  FCurrentBreakpointList := nil;
  FCurrentWatchpoint := nil;

  FSymInstances := TList.Create;

  SetFileName(AFileName);

  inherited Create(Self);
end;

destructor TDbgProcess.Destroy;

  procedure FreeItemsInMap(AMap: TMap);
  var
    AnObject: TObject;
    Iterator: TMapIterator;
  begin
    iterator := TMapIterator.Create(AMap);
    try
      Iterator.First;
      while not Iterator.EOM do
      begin
        Iterator.GetData(AnObject);
        AnObject.Free;
        iterator.Next;
      end;
    finally
      Iterator.Free;
    end;
  end;

var
  i: Integer;
begin
  FProcessID:=0;
  SetLastLibraryUnloaded(nil);

  for i := 0 to FBreakpointList.Count - 1 do
    FBreakpointList[i].SetProcessToNil;
  for i := 0 to FWatchPointList.Count - 1 do
    FWatchPointList[i].SetProcessToNil;
  FreeAndNil(FBreakpointList);
  FreeAndNil(FWatchPointList);
  //Assert(FBreakMap.Count=0, 'No breakpoints left');
  //FreeItemsInMap(FBreakMap);
  FreeItemsInMap(FThreadMap);
  FreeItemsInMap(FLibMap);
  FLibMap.ClearAddedAndRemovedLibraries;

  FGlobalCache.Free;
  FreeAndNil(FWatchPointData);
  FBreakTargetHandler.BreakMap := nil;
  FreeAndNil(FBreakMap);
  FreeAndNil(FBreakTargetHandler);
  FreeAndNil(FThreadMap);
  FreeAndNil(FLibMap);
  FreeAndNil(FSymInstances);
  FreeAndNil(FDisassembler);
  FreeAndNil(FConfig);
  inherited;
end;

function TDbgProcess.StartInstance(AParams, AnEnvironment: TStrings;
  AWorkingDirectory, AConsoleTty: string; AFlags: TStartInstanceFlags; out
  AnError: TFpError): boolean;
begin
  DebugLn(DBG_VERBOSE, 'Debug support is not available for this platform.');
  result := false;
end;

function TDbgProcess.AttachToInstance(APid: Integer; out AnError: TFpError): boolean;
begin
  DebugLn(DBG_VERBOSE, 'Attach not supported');
  Result := false;
end;

function TDbgProcess.AddInternalBreak(const ALocation: TDBGPtr): TFpInternalBreakpoint;
begin
  Result := TFpInternalBreakpoint(AddBreak(ALocation));
  Result.FInternal := True;
end;

function TDbgProcess.AddInternalBreak(const ALocation: TDBGPtrArray): TFpInternalBreakpoint;
begin
  Result := TFpInternalBreakpoint(AddBreak(ALocation));
  Result.FInternal := True;
end;

function TDbgProcess.FindProcSymbol(AAdress: TDbgPtr): TFpSymbol;
var
  n: Integer;
  Inst: TDbgInstance;
begin
  for n := 0 to FSymInstances.Count - 1 do
  begin
    Inst := TDbgInstance(FSymInstances[n]);
    Result := Inst.FindProcSymbol(AAdress);
    if Result <> nil then Exit;
  end;
  Result := nil;
end;

function TDbgProcess.FindSymbolScope(AThreadId, AStackFrame: Integer): TFpDbgSymbolScope;
var
  Thread: TDbgThread;
  Frame: TDbgCallstackEntry;
  Addr: TDBGPtr;
  Ctx: TFpDbgSimpleLocationContext;
  sym: TFpSymbol;
begin
  Result := nil;
  Ctx := nil;

  if GetThread(AThreadId, Thread) then begin
    Thread.PrepareCallStackEntryList(AStackFrame + 1);

    if AStackFrame < Thread.CallStackEntryList.Count then begin
      Frame := Thread.CallStackEntryList[AStackFrame];

      if Frame <> nil then begin
        Addr := Frame.AnAddress;
        Ctx := Frame.Context;
        if Ctx <> nil then begin
          Ctx.AddReference;
        end
        else begin
          Ctx := TFpDbgSimpleLocationContext.Create(MemManager, Addr, DBGPTRSIZE[Mode], AThreadId, AStackFrame);
          Ctx.SetFrameBaseCallback(@DoGetFrameBase);
          Ctx.SetCfaFrameBaseCallback(@DoGetCfiFrameBase);
          Ctx.SymbolTableInfo := SymbolTableInfo;
          Frame.Context := Ctx;
        end;
        sym := Frame.ProcSymbol;
        if sym <> nil then
          Result := sym.CreateSymbolScope(Ctx);

        if Result = nil then begin
          if (Addr <> 0) or (FDbgInfo.TargetInfo.machineType = mtAVR8) then
            Result := FDbgInfo.FindSymbolScope(Ctx, Addr);
        end;
      end;
    end;

    // SymbolTableInfo.FindSymbolScope()
  end;

  if Result = nil then begin
    if Ctx = nil then
      Ctx := TFpDbgSimpleLocationContext.Create(MemManager, 0, DBGPTRSIZE[Mode], AThreadId, AStackFrame);
    Result := TFpDbgSymbolScope.Create(Ctx);
  end;

  Ctx.ReleaseReference;
end;

function TDbgProcess.FindProcStartEndPC(const AAdress: TDbgPtr; out AStartPC,
  AEndPC: TDBGPtr): boolean;
var
  n: Integer;
  Inst: TDbgInstance;
begin
  for n := 0 to FSymInstances.Count - 1 do
  begin
    Inst := TDbgInstance(FSymInstances[n]);
    Result := Inst.FindProcStartEndPC(AAdress, AStartPC, AEndPC);
    if Result then Exit;
  end;
end;

function TDbgProcess.FindCallFrameInfo(AnAddress: TDBGPtr; out CIE: TDwarfCIE; out
  Row: TDwarfCallFrameInformationRow): Boolean;
var
  Lib: TDbgLibrary;
begin
  Result := inherited FindCallFrameInfo(AnAddress, CIE, Row);
  if Result then
    exit;

  for Lib in FLibMap do begin
    Result := Lib.FindCallFrameInfo(AnAddress, CIE, Row);
    if Result then
      exit;
  end;
end;

function TDbgProcess.GetLineAddresses(AFileName: String; ALine: Cardinal;
  var AResultList: TDBGPtrArray; ASymInstance: TDbgInstance;
  AFindSibling: TGetLineAddrFindSibling; AMaxSiblingDistance: integer): Boolean;
var
  Lib: TDbgLibrary;
begin
  FLastLineAddressesFoundFile := False;
  if ASymInstance <> nil then begin
    if ASymInstance = self then begin
      Result := inherited GetLineAddresses(AFileName, ALine, AResultList, AFindSibling, AMaxSiblingDistance);
    end
    else begin
      Result := ASymInstance.GetLineAddresses(AFileName, ALine, AResultList, AFindSibling, AMaxSiblingDistance);
      if ASymInstance.FLastLineAddressesFoundFile then
        FLastLineAddressesFoundFile := True;
    end;
    exit;
  end;

  Result := inherited GetLineAddresses(AFileName, ALine, AResultList, AFindSibling, AMaxSiblingDistance);
  for Lib in FLibMap do begin
    if Lib.GetLineAddresses(AFileName, ALine, AResultList, AFindSibling, AMaxSiblingDistance) then
      Result := True;
    if Lib.FLastLineAddressesFoundFile then
      FLastLineAddressesFoundFile := True;
  end;
end;

//function TDbgProcess.ContextFromProc(AThreadId, AStackFrame: Integer;
//  AProcSym: TFpSymbol): TFpDbgLocationContext;
//begin
//  Result := TFpDbgSimpleLocationContext.Create(MemManager, LocToAddrOrNil(AProcSym.Address), DBGPTRSIZE[Mode], AThreadId, AStackFrame);
//end;

function TDbgProcess.GetLib(const AHandle: THandle; out ALib: TDbgLibrary): Boolean;
begin
  Result := FLibMap.GetLib(AHandle, ALib);
end;

procedure TDbgProcess.UpdateBreakpointsForLibraryLoaded(ALib: TDbgLibrary);
var
  i: Integer;
begin
  if (ALib.DbgInfo.HasInfo) or (ALib.SymbolTableInfo.HasInfo) then begin
    debugln(DBG_VERBOSE and (ALib.FBreakUpdateDone), ['TDbgProcess.UpdateBreakpointsForLibraryLoaded: Called twice for ', ALib.Name]);
    assert(not ALib.FBreakUpdateDone, 'TDbgProcess.UpdateBreakpointsForLibraryLoaded: not ALib.FBreakUpdateDone');
    if ALib.FBreakUpdateDone then
      exit;
    ALib.FBreakUpdateDone := True;
    debuglnEnter(DBG_BREAKPOINTS,['> TDbgProcess.UpdateBreakpointsForLibraryLoaded ',ALib.Name ]); try
    for i := 0 to FBreakpointList.Count - 1 do
      FBreakpointList[i].UpdateForLibraryLoaded(ALib);
    finally debuglnExit(DBG_BREAKPOINTS,['< TDbgProcess.UpdateBreakpointsForLibraryLoaded ' ]); end;
  end;
end;

procedure TDbgProcess.UpdateBreakpointsForLibraryUnloaded(ALib: TDbgLibrary);
var
  i: LongInt;
  b: TFpInternalBreakBase;
begin
  // The library is unloaded by the OS, so all breakpoints are already gone.
  // This is more to update our administration and free some memory.
  debuglnEnter(DBG_BREAKPOINTS, ['> TDbgProcess.UpdateBreakpointsForLibraryUnloaded ' ]); try if ALib <> nil then debugln(DBG_BREAKPOINTS, [ALib.Name]);
  i := FBreakpointList.Count - 1;
  while i >= 0 do begin
    b := FBreakpointList[i];
    b.UpdateForLibrareUnloaded(ALib);
    dec(i);
  end;
  i := FWatchPointList.Count - 1;
  while i >= 0 do begin
    b := FWatchPointList[i];
    b.UpdateForLibrareUnloaded(ALib);
    dec(i);
  end;
  finally debuglnExit(DBG_BREAKPOINTS,['< TDbgProcess.UpdateBreakpointsForLibraryUnloaded ' ]); end;
end;

function TDbgProcess.GetThread(const AID: Integer; out AThread: TDbgThread): Boolean;
var
  Thread: TDbgThread;
begin
  AThread := nil;
  Result := FThreadMap.GetData(AID, Thread) and (Thread <> nil);
  if Result
  then AThread := Thread;
end;

function TDbgProcess.ReadData(const AAdress: TDbgPtr; const ASize: Cardinal; out AData): Boolean;
begin
  result := false
end;

function TDbgProcess.ReadData(const AAdress: TDbgPtr; const ASize: Cardinal;
  out AData; out APartSize: Cardinal): Boolean;
var
  SizeRemaining, sz: Cardinal;
  Offs: Integer;
  APartAddr: TDBGPtr;
  Dummy: QWord;
begin
  // subclasses can do better implementation if checking for error reasons, such as part_read
  APartSize := ASize;
  Result := ReadData(AAdress, APartSize, AData);
  if Result then
    exit;

  SizeRemaining := ASize;
  Offs := 0;
  APartAddr := AAdress;
  APartSize := 0;

  // check if the address is readable at all
  Result := ReadData(AAdress, 1, Dummy);
  if not Result then
    exit;

  while SizeRemaining > 0 do begin
    Result := False;
    sz := SizeRemaining;
    while (not Result) and (sz > 1) do begin
      sz := sz div 2;
      Result := ReadData(APartAddr, sz, (@AData + Offs)^);
    end;
    if not Result then
      break;

    APartSize := APartSize + sz;
    Offs := Offs + sz;
    APartAddr := APartAddr + sz;
    SizeRemaining := SizeRemaining - sz;
  end;

  Result := APartSize > 0;
end;

function TDbgProcess.ReadAddress(const AAdress: TDbgPtr; out AData: TDBGPtr): Boolean;
var
  dw: DWord;
  qw: QWord;
begin
  case Mode of
    dm32:
      begin
        result := ReadData(AAdress, sizeof(dw), dw);
        AData:=dw;
      end;
    dm64:
      begin
        result := ReadData(AAdress, sizeof(qw), qw);
        AData:=qw;
      end;
  end;
end;

function TDbgProcess.ReadOrdinal(const AAdress: TDbgPtr; out AData): Boolean;
begin
  Result := ReadData(AAdress, 4, AData);
end;

function TDbgProcess.ReadString(const AAdress: TDbgPtr; const AMaxSize: Cardinal; out AData: String): Boolean;
begin
  Result := false;
end;

function TDbgProcess.ReadWString(const AAdress: TDbgPtr; const AMaxSize: Cardinal; out AData: WideString): Boolean;
begin
  result := false;
end;

function TDbgProcess.CallParamDefaultLocation(AParamIdx: Integer
  ): TFpDbgMemLocation;
begin
  Result := InvalidLoc;
end;

function TDbgProcess.Continue(AProcess: TDbgProcess; AThread: TDbgThread;
  SingleStep: boolean): boolean;
begin
  result := false;
end;

function TDbgProcess.ResolveDebugEvent(AThread: TDbgThread): TFPDEvent;
var
  CurrentAddr: TDBGPtr;
begin
  if AThread <> nil then
    AThread.ValidateRemovedBreakPointInfo;
  result := AnalyseDebugEvent(AThread);

  if (result = deBreakpoint) and (AThread <> nil) then
  begin
    // Determine the address where the execution has stopped
    CurrentAddr:=AThread.GetInstructionPointerRegisterValue;
    FCurrentWatchpoint:=AThread.DetectHardwareWatchpoint;
    if (FCurrentWatchpoint <> nil) and (FWatchPointList.IndexOf(TFpInternalWatchpoint(FCurrentWatchpoint)) < 0) then
      FCurrentWatchpoint := Pointer(-1);
    FCurrentBreakpoint:=nil;
    FCurrentBreakpointList := nil;
    AThread.NextIsSingleStep:=false;

    // Whatever reason there was to change the result to deInternalContinue,
    // if a breakpoint has been hit, always trigger it...
    if DoBreak(CurrentAddr, AThread.ID) then
      result := deBreakpoint;
  end
end;

function TDbgProcess.CheckForConsoleOutput(ATimeOutMs: integer): integer;
begin
  result := -1;
end;

function TDbgProcess.GetConsoleOutput: string;
begin
  result := '';
end;

procedure TDbgProcess.SendConsoleInput(AString: string);
begin
  // Do nothing
end;

procedure TDbgProcess.ClearAddedAndRemovedLibraries;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadIdNotMain('ClearAddedAndRemovedLibraries');{$ENDIF}
  FLibMap.ClearAddedAndRemovedLibraries;
end;

procedure TDbgProcess.DoBeforeProcessLoop;
var
  t: TDbgThread;
begin
  ClearAddedAndRemovedLibraries;
  FGlobalCache.Clear;

  for t in FThreadMap do
    t.DoBeforeProcessLoop;
end;

function TDbgProcess.AddThread(AThreadIdentifier: THandle): TDbgThread;
var
  IsMainThread: boolean;
begin
  result := CreateThread(AthreadIdentifier, IsMainThread);
  if assigned(result) then
  begin
    FThreadMap.Add(AThreadIdentifier, Result);
    if IsMainThread then
    begin
      assert(FMainThread=nil);
      FMainThread := result;
    end;
    Result.ApplyWatchPoints(FWatchPointData);
  end
  else
    DebugLn(DBG_WARNINGS, 'Unknown thread ID %u for process %u', [AThreadIdentifier, ProcessID]);
end;

function TDbgProcess.GetThreadArray: TFPDThreadArray;
var
  Iterator: TMapIterator;
  Thread: TDbgThread;
  I: Integer;
begin
  SetLength(Result, FThreadMap.Count);
  Iterator := TMapIterator.Create(FThreadMap);
  try
    Iterator.First;
    I := 0;
    while not Iterator.EOM do
    begin
      Iterator.GetData(Thread);
      Result[I] := Thread;
      Inc(I);
      iterator.Next;
    end;
  finally
    Iterator.Free;
  end;
end;

procedure TDbgProcess.ThreadsBeforeContinue;
var
  Iterator: TMapIterator;
  Thread: TDbgThread;
begin
  Iterator := TLockedMapIterator.Create(FThreadMap);
  try
    Iterator.First;
    while not Iterator.EOM do
    begin
      Iterator.GetData(Thread);
      if FWatchPointData.Changed then
        Thread.ApplyWatchPoints(FWatchPointData);
      Thread.BeforeContinue;
      iterator.Next;
    end;
  finally
    Iterator.Free;
  end;
  FWatchPointData.Changed := False;
end;

procedure TDbgProcess.ThreadsClearCallStack;
var
  Iterator: TMapIterator;
  Thread: TDbgThread;
begin
  GlobalCache.Clear;
  Iterator := TLockedMapIterator.Create(FThreadMap);
  try
    Iterator.First;
    while not Iterator.EOM do
    begin
      Iterator.GetData(Thread);
      Thread.ClearCallStack;
      iterator.Next;
    end;
  finally
    Iterator.Free;
  end;
end;

procedure TDbgProcess.RemoveBreak(const ABreakPoint: TFpDbgBreakpoint);
var
  i: SizeInt;
begin
  if ABreakPoint=FCurrentBreakpoint then begin
    FCurrentBreakpoint := nil;
    if Length(FCurrentBreakpointList) > 0 then begin
      FCurrentBreakpoint := FCurrentBreakpointList[0];
      SetLength(FCurrentBreakpointList, Length(FCurrentBreakpointList) - 1);
    end;
  end;

  i := Length(FCurrentBreakpointList) - 1;
  while (i >= 0) and (FCurrentBreakpointList[i] <> ABreakPoint) do
    dec(i);
  if i >= 0 then begin
    while i < Length(FCurrentBreakpointList) - 2 do begin
      FCurrentBreakpointList[i] := FCurrentBreakpointList[i+1];
      inc(i);
    end;
    SetLength(FCurrentBreakpointList, Length(FCurrentBreakpointList) - 1);
  end;
end;

procedure TDbgProcess.DoBeforeBreakLocationMapChange;
var
  t: TDbgThread;
begin
  for t in FThreadMap do
    t.DoBeforeBreakLocationMapChange;
end;

function TDbgProcess.HasBreak(const ALocation: TDbgPtr): Boolean;
begin
  if FBreakMap = nil then
    Result := False
  else
    result := FBreakMap.HasId(ALocation);
end;

procedure TDbgProcess.RemoveThread(const AID: DWord);
begin
  if FThreadMap = nil then Exit;
  FThreadMap.Delete(AID);
end;

function TDbgProcess.FormatAddress(const AAddress): String;
begin
  Result := HexValue(AAddress, DBGPTRSIZE[Mode], [hvfIncludeHexchar]);
end;

function TDbgProcess.Pause: boolean;
begin
  result := false;
end;

function TDbgProcess.GetHandle: THandle;
begin
  result := 0;
end;

procedure TDbgProcess.SetThreadId(AThreadId: Integer);
begin
  assert(FThreadID = 0, 'TDbgProcess.SetThreadId: FThreadID = 0');
  FThreadID := AThreadId;
end;

procedure TDbgProcess.SetExitCode(AValue: DWord);
begin
  FExitCode:=AValue;
end;

class function TDbgProcess.isSupported(ATargetInfo: TTargetDescriptor): boolean;
begin
  result := false;
end;

procedure TDbgProcess.ThreadDestroyed(const AThread: TDbgThread);
begin
  if AThread = FMainThread
  then FMainThread := nil;
end;

function TDbgProcess.GetPauseRequested: boolean;
begin
  Result := Boolean(InterLockedExchangeAdd(FPauseRequested, 0));
end;

function TDbgProcess.GetRequiresExecutionInDebuggerThread: boolean;
begin
  Result := False;
end;

function TDbgProcess.GetDisassembler: TDbgAsmDecoder;
begin
  if FDisassembler = nil then
    FDisassembler := OSDbgClasses.DbgDisassemblerClass.Create(Self);
  Result := FDisassembler;
end;

function TDbgProcess.DoGetCfiFrameBase(AContext: TFpDbgLocationContext; out AnError: TFpError
  ): TDBGPtr;
var
  Thrd: TDbgThread;
  CStck: TDbgCallstackEntry;
  CIE: TDwarfCIE;
  ROW: TDwarfCallFrameInformationRow;
begin
  Result := 0;
  AnError := nil;
  if (not GetThread(AContext.ThreadId, Thrd)) or (Thrd = nil) then
    exit;
  if AContext.StackFrame >= Thrd.CallStackEntryList.Count then
    exit;
  CStck := Thrd.CallStackEntryList[AContext.StackFrame];
  if CStck = nil then
    exit;

  if not FindCallFrameInfo(AContext.Address, CIE, ROW) then
    exit;

  if not GetCanonicalFrameAddress(CStck.RegisterValueList ,ROW, Result) then
    Result := 0;
end;

function TDbgProcess.DoGetFrameBase(AContext: TFpDbgLocationContext; out AnError: TFpError
  ): TDBGPtr;
var
  Thrd: TDbgThread;
  CStck: TDbgCallstackEntry;
  p: TFpSymbol;
begin
  Result := 0;
  AnError := nil;
  if (not GetThread(AContext.ThreadId, Thrd)) or (Thrd = nil) then
    exit;
  if AContext.StackFrame >= Thrd.CallStackEntryList.Count then
    exit;
  CStck := Thrd.CallStackEntryList[AContext.StackFrame];
  if CStck = nil then
    exit;

  p := CStck.ProcSymbol;
  if p =nil then
    exit;

  if p is TFpSymbolDwarfDataProc then
    Result := TFpSymbolDwarfDataProc(p).GetFrameBase(AContext, AnError);
end;

function TDbgProcess.GetLastLibrariesLoaded: TDbgLibraryArr;
begin
  Result := FLibMap.FLibrariesAdded;
end;

function TDbgProcess.GetLastLibrariesUnloaded: TDbgLibraryArr;
begin
  Result := FLibMap.FLibrariesRemoved;
end;

function TDbgProcess.GetAndClearPauseRequested: Boolean;
begin
  Result := Boolean(InterLockedExchange(FPauseRequested, ord(False)));
end;

procedure TDbgProcess.SetPauseRequested(AValue: boolean);
begin
  InterLockedExchange(FPauseRequested, ord(AValue));
end;

procedure TDbgProcess.LoadInfo;
begin
  inherited LoadInfo;

  if DbgInfo.HasInfo then
    FSymInstances.Add(Self);
end;

procedure TDbgProcess.InitializeLoaders;
begin
  inherited InitializeLoaders;
end;

function TDbgProcess.GetLastEventProcessIdentifier: THandle;
begin
  result := 0;
end;

function TDbgProcess.DoBreak(BreakpointAddress: TDBGPtr; AThreadID: integer): Boolean;
var
  BList: TFpInternalBreakpointArray;
  i, xtra: Integer;
begin
  Result := False;

  BList := FBreakMap.GetInternalBreaksAtLocation(BreakpointAddress);
  if BList = nil then exit;
  i := 0;
  FCurrentBreakpoint := nil;
  SetLength(FCurrentBreakpointList, Length(BList));
  xtra := 0;
  for i := 0 to Length(BList) - 1 do begin
    if not BList[0].FInternal then begin
      BList[i].Hit(AThreadId, BreakpointAddress);
      if (FCurrentBreakpoint = nil) then begin
        FCurrentBreakpoint := BList[i];
      end
      else begin
        FCurrentBreakpointList[xtra] := BList[i];
        inc(xtra);
        BList[i].Hit(AThreadId, BreakpointAddress);
      end;
    end;
  end;

  SetLength(FCurrentBreakpointList, xtra);
  Result := (FCurrentBreakpoint <> nil);
end;

procedure TDbgProcess.SetLastLibraryUnloaded(ALib: TDbgLibrary);
begin
  if FLastLibraryUnloaded <> nil then
    FLastLibraryUnloaded.Destroy;
  FLastLibraryUnloaded := ALib;
end;

procedure TDbgProcess.SetLastLibraryUnloadedNil(ALib: TDbgLibrary);
begin
  assert(ALib = nil, 'TDbgProcess.SetLastLibraryUnloadedNil: ALib = nil');
  SetLastLibraryUnloaded(nil);
end;

procedure TDbgProcess.AddLibrary(ALib: TDbgLibrary; AnID: TDbgPtr);
begin
  if FLibMap.HasId(AnID) then begin
    debugln(DBG_VERBOSE or DBG_WARNINGS, ['Error: Attempt to add duplicate library ', AnID]);
    exit;
  end;
  FLibMap.Add(AnID, ALib);

  if (ALib.DbgInfo.HasInfo) or (ALib.SymbolTableInfo.HasInfo) then
    FSymInstances.Add(ALib);
end;

procedure TDbgProcess.RemoveAllBreakPoints;
var
  i: LongInt;
  b: TFpInternalBreakBase;
begin
  i := FBreakpointList.Count - 1;
  while i >= 0 do begin
    b := FBreakpointList[i];
    b.ResetBreak;
    b.SetProcessToNil;
    FBreakpointList.Delete(i);
    dec(i);
  end;
  i := FWatchPointList.Count - 1;
  while i >= 0 do begin
    b := FWatchPointList[i];
    b.ResetBreak;
    b.SetProcessToNil;
    FWatchPointList.Delete(i);
    dec(i);
  end;
end;

procedure TDbgProcess.BeforeChangingInstructionCode(const ALocation: TDBGPtr; ACount: Integer);
begin
  //
end;

procedure TDbgProcess.AfterChangingInstructionCode(const ALocation: TDBGPtr; ACount: Integer);
begin
  //
end;

procedure TDbgProcess.AfterBreakpointAdded(ABreak: TFpDbgBreakpoint);
begin
  if (FMainThread <> nil) and not assigned(FCurrentBreakpoint) then begin
    // TODO: what if there is a hardcoded int3?
    if ABreak.HasLocation(FMainThread.GetInstructionPointerRegisterValue) then
      FCurrentBreakpoint := TFpInternalBreakpoint(ABreak);
  end;
end;

//function TDbgProcess.LocationIsBreakInstructionCode(const ALocation: TDBGPtr
//  ): Boolean;
//var
//  OVal: Byte;
//begin
//  Result := FBreakMap.HasId(ALocation);
//  if not Result then
//    exit;
//
//  Result := FProcess.ReadData(ALocation, 1, OVal);
//  if Result then
//    Result := OVal = Int3
//  else
//    DebugLn(DBG_WARNINGS or DBG_BREAKPOINTS'Unable to read pre-breakpoint at '+FormatAddress(ALocation));
//end;

procedure TDbgProcess.TempRemoveBreakInstructionCode(const ALocation: TDBGPtr);
begin
  FBreakTargetHandler.TempRemoveBreakInstructionCode(ALocation);
end;

procedure TDbgProcess.RestoreTempBreakInstructionCodes;
begin
  FBreakTargetHandler.RestoreTempBreakInstructionCodes;
end;

function TDbgProcess.HasInsertedBreakInstructionAtLocation(
  const ALocation: TDBGPtr): Boolean;
begin
  Result := FBreakMap.HasInsertedBreakInstructionAtLocation(ALocation);
end;

function TDbgProcess.CanContinueForWatchEval(ACurrentThread: TDbgThread
  ): boolean;
begin
  Result := True;
end;

procedure TDbgProcess.MaskBreakpointsInReadData(const AAdress: TDbgPtr; const ASize: Cardinal; var AData);
begin
  if FBreakTargetHandler <> nil then
    FBreakTargetHandler.MaskBreakpointsInReadData(AAdress, ASize, AData);
end;

function TDbgProcess.CreateWatchPointData: TFpWatchPointData;
begin
  Result := TFpWatchPointData.Create;
end;

procedure TDbgProcess.Init(const AProcessID, AThreadID: Integer);
begin
  FProcessID := AProcessID;
  FThreadID := AThreadID;
end;

function TDbgProcess.CreateConfig: TDbgConfig;
begin
  Result := TDbgConfig.Create;
end;

function TDbgProcess.WriteData(const AAdress: TDbgPtr; const ASize: Cardinal; const AData): Boolean;
begin
  result := false;
end;

function TDbgProcess.Detach(AProcess: TDbgProcess; AThread: TDbgThread
  ): boolean;
begin
  Result := False;
end;

function TDbgProcess.WriteInstructionCode(const AAdress: TDbgPtr; const ASize: Cardinal; const AData): Boolean;
begin
  FBreakTargetHandler.UpdateMapForNewTargetCode(AAdress, ASize, AData);
  BeforeChangingInstructionCode(AAdress, ASize);
  Result := WriteData(AAdress, ASize, AData);
  AfterChangingInstructionCode(AAdress, ASize);
end;


{ TDbgStackFrameInfo }

procedure TDbgStackFrameInfo.DoAfterRun;
var
  CurStackFrame: TDBGPtr;
begin
  FProcessAfterRun := False;
  case FLeaveState of
    lsWasAtLeave1: begin
        CurStackFrame   := FThread.GetStackBasePointerRegisterValue;
        FStoredStackPointer := FThread.GetStackPointerRegisterValue;
        if CurStackFrame <> FStoredStackFrame then
          FLeaveState := lsLeaveDone // real leave
        else
          FLeaveState := lsWasAtLeave2; // lea rsp,[rbp+$00] / pop ebp // epb in next command
      end;
    lsWasAtLeave2: begin
        // TODO: maybe check, if stackpointer only goes down by sizeof(pointer) "Pop bp"
        FStoredStackFrame   := FThread.GetStackBasePointerRegisterValue;
        FStoredStackPointer := FThread.GetStackPointerRegisterValue;
        FLeaveState := lsLeaveDone;
      end;
  end;
end;

procedure TDbgStackFrameInfo.DoCheckNextInstruction(
  ANextInstruction: TDbgAsmInstruction; NextIsSingleStep: Boolean);
begin
  if FProcessAfterRun then
    DoAfterRun;

  if not NextIsSingleStep then begin
    if FLeaveState = lsWasAtLeave2 then
      FLeaveState := lsLeaveDone;
    exit;
  end;

  if ANextInstruction.IsReturnInstruction then begin
    FHasSteppedOut := True;
    FLeaveState := lsLeaveDone;
  end
  else if FLeaveState = lsNone then begin
    if ANextInstruction.IsLeaveStackFrame then
      FLeaveState := lsWasAtLeave1;
  end;

  FProcessAfterRun := FLeaveState in [lsWasAtLeave1, lsWasAtLeave2];
end;

function TDbgStackFrameInfo.CalculateHasSteppedOut: Boolean;
var
  CurBp, CurSp: TDBGPtr;
begin
  if FProcessAfterRun then
    DoAfterRun;

  Result := False;
  CurBp := FThread.GetStackBasePointerRegisterValue;
  if FStoredStackFrame < CurBp then begin
    CurSp := FThread.GetStackPointerRegisterValue;
    if FStoredStackPointer >= CurSp then // this happens, if current was recorded before the BP frame was set up // a finally handle may then fake an outer frame
      exit;
//    {$PUSH}{$Q-}{$R-}
//    if CurSp = FStoredStackPointer + FThread.Process.PointerSize then
//      exit; // Still in proc, but passed asm "leave" (BP has been popped, but IP not yet)
//    {$POP}
    Result := True;
    debugln(FPDBG_COMMANDS, ['BreakStepBaseCmd.GetIsSteppedOut: Has stepped out Stored-BP=', FStoredStackFrame, ' < BP=', CurBp, ' / SP', CurSp]);
  end;
end;

constructor TDbgStackFrameInfo.Create(AThread: TDbgThread);
begin
  FThread := AThread;
  FStoredStackFrame   := AThread.GetStackBasePointerRegisterValue;
  FStoredStackPointer := AThread.GetStackPointerRegisterValue;
end;

procedure TDbgStackFrameInfo.CheckNextInstruction(
  ANextInstruction: TDbgAsmInstruction; NextIsSingleStep: Boolean);
begin
  if not FHasSteppedOut then
    DoCheckNextInstruction(ANextInstruction, NextIsSingleStep);
end;

function TDbgStackFrameInfo.HasSteppedOut: Boolean;
begin
  Result := FHasSteppedOut;
  if Result then
    exit;
  FHasSteppedOut := CalculateHasSteppedOut;
  Result := FHasSteppedOut;
end;

procedure TDbgStackFrameInfo.FlagAsSteppedOut;
begin
  FHasSteppedOut := True;
end;

{ TDbgStackUnwinderX86Base }

constructor TDbgStackUnwinderX86Base.Create(AProcess: TDbgProcess);
begin
  FProcess := AProcess;
  case AProcess.Mode of
    dm32: begin
      FAddressSize := 4;
      FDwarfNumIP := 8; // Dwarf Reg Num EIP
      FDwarfNumBP := 5; // EBP
      FDwarfNumSP := 4; // ESP
      FNameIP := 'eip';
      FNameBP := 'ebp';
      FNameSP := 'esp';
    end;
    dm64: begin
      FAddressSize := 8;
      FDwarfNumIP := 16; // Dwarf Reg Num RIP
      FDwarfNumBP := 6; // RBP
      FDwarfNumSP := 7; // RSP
      FNameIP := 'rip';
      FNameBP := 'rbp';
      FNameSP := 'rsp';
    end;
  end;
end;

procedure TDbgStackUnwinderX86Base.InitForThread(AThread: TDbgThread);
begin
  FThread := AThread;
end;

procedure TDbgStackUnwinderX86Base.InitForFrame(
  ACurrentFrame: TDbgCallstackEntry; out CodePointer, StackPointer,
  FrameBasePointer: TDBGPtr);
var
  R: TDbgRegisterValue;
begin
    CodePointer      := ACurrentFrame.AnAddress;
    FrameBasePointer := ACurrentFrame.FrameAdress;
    R := ACurrentFrame.RegisterValueList.FindRegisterByDwarfIndex(FDwarfNumBP);
    if R <> nil then
      FrameBasePointer := R.NumValue;
    StackPointer     := 0;
    R := ACurrentFrame.RegisterValueList.FindRegisterByDwarfIndex(FDwarfNumSP);
    if R = nil then exit;
    StackPointer := R.NumValue;
end;

procedure TDbgStackUnwinderX86Base.GetTopFrame(out CodePointer, StackPointer,
  FrameBasePointer: TDBGPtr; out ANewFrame: TDbgCallstackEntry);
var
  i: Integer;
  R: TDbgRegisterValue;
begin
  CodePointer      := Thread.GetInstructionPointerRegisterValue;
  StackPointer     := Thread.GetStackPointerRegisterValue;
  FrameBasePointer := Thread.GetStackBasePointerRegisterValue;
  ANewFrame        := TDbgCallstackEntry.create(Thread, 0, FrameBasePointer, CodePointer);
  ANewFrame.AutoFillRegisters := True;
end;

{ TDbgThread }

function TDbgThread.GetRegisterValueList: TDbgRegisterValueList;
begin
  if not FRegisterValueListValid then
    LoadRegisterValues;
  result := FRegisterValueList;
end;

function TDbgThread.CompareStepInfo(AnAddr: TDBGPtr; ASubLine: Boolean
  ): TFPDCompareStepInfo;
var
  Sym: TFpSymbol;
  l: TDBGPtr;
begin
  if FStoreStepSrcLineNo = -1 then begin // stepping from location with no line info
    Result := dcsiNewLine;
    exit;
  end;

  if AnAddr = 0 then
    AnAddr := GetInstructionPointerRegisterValue;

  if (FStoreStepStartAddr <> 0) then begin
    if (AnAddr > FStoreStepStartAddr) and (AnAddr < FStoreStepEndAddr)
    then begin
      result := dcsiSameLine;
      exit;
    end
    else
    if ASubLine then begin
      // this is used for the (unmarked) proloque of finally handlers in 3.1.1
      result := dcsiNewLine; // may have the same line number, but has a new address block
      exit;
    end;
  end;

  sym := FProcess.FindProcSymbol(AnAddr);
  if assigned(sym) then
  begin
    if sym is TFpSymbolDwarfDataProc then
      l := TFpSymbolDwarfDataProc(sym).LineUnfixed
    else
      l := Sym.Line;
    debugln(FPDBG_COMMANDS, ['CompareStepInfo @IP=',AnAddr,' ',sym.FileName, ':',l, ' in ',sym.Name, ' @Func=',sym.Address.Address]);
    if (((FStoreStepSrcFilename=sym.FileName) and (FStoreStepSrcLineNo=l)) {or FStepOut}) then
      result := dcsiSameLine
    else if sym.FileName = '' then
      result := dcsiNoLineInfo
    else if l = 0 then
      result := dcsiZeroLine
    else
      result := dcsiNewLine;
    sym.ReleaseReference;
  end
  else
    result := dcsiNoLineInfo;
end;

function TDbgThread.IsAtStartOfLine: boolean;
var
  AnAddr, b: TDBGPtr;
  Sym: TFpSymbol;
  CU: TDwarfCompilationUnit;
  a: TDBGPtrArray;
begin
  AnAddr := GetInstructionPointerRegisterValue;
  sym := FProcess.FindProcSymbol(AnAddr);
  if (sym is TDbgDwarfSymbolBase) then
  begin
    CU := TDbgDwarfSymbolBase(sym).CompilationUnit;
    Result := False;
    CU.Owner.GetLineAddresses(sym.FileName, sym.Line, a);
    for b in a do begin
      Result := b = AnAddr;
      if Result then break;
    end;
  end
  else
    Result := True;
  sym.ReleaseReference;
end;

function TDbgThread.StoreStepInfo(AnAddr: TDBGPtr): boolean;
var
  Sym: TFpSymbol;
begin
  if AnAddr = 0 then
    AnAddr := GetInstructionPointerRegisterValue;
  sym := FProcess.FindProcSymbol(AnAddr);
  FStoreStepStartAddr := AnAddr;
  FStoreStepEndAddr := AnAddr;
  FStoreStepFuncAddr:=0;
  if assigned(sym) then
  begin
    FStoreStepSrcFilename:=sym.FileName;
    FStoreStepFuncAddr:=sym.Address.Address;
    FStoreStepFuncName:=sym.Name;
    if sfHasLineAddrRng in sym.Flags then begin
      FStoreStepStartAddr := sym.LineStartAddress;
      FStoreStepEndAddr := sym.LineEndAddress;
    end;
    if sym is TFpSymbolDwarfDataProc then begin
      FStoreStepSrcLineNo := TFpSymbolDwarfDataProc(sym).LineUnfixed;
    end
    else
      FStoreStepSrcLineNo:=sym.Line;
    debugln(FPDBG_COMMANDS, ['StoreStepInfo @IP=',AnAddr,' ',sym.FileName, ':',FStoreStepSrcLineNo, ' in ',sym.Name, ' @Func=',sym.Address.Address]);
    sym.ReleaseReference;
  end
  else begin
    debugln(FPDBG_COMMANDS, ['StoreStepInfo @IP=',AnAddr,' - No symbol']);
    FStoreStepSrcLineNo:=-1;
  end;
  Result := (FStoreStepSrcFilename <> '') or (FStoreStepSrcLineNo > 0);
end;

procedure TDbgThread.LoadRegisterValues;
begin
  // Do nothing
end;

procedure TDbgThread.StoreHasBreakpointInfoForAddress(AnAddr: TDBGPtr);
begin
  // Already stored?
  if (FStoredBreakpointInfoState <> rbUnknown) and
     (FStoredBreakpointInfoAddress = AnAddr)
  then
    exit;

  if (AnAddr <> 0) and Process.HasInsertedBreakInstructionAtLocation(AnAddr) then begin
    (* There is a chance, that the code jumped to this Addr, instead of executing the breakpoint.
       But if the next signal for this thread is a breakpoint at this address, then
       it must be handled (even if the breakpoint has been removed since)
    *)
    FStoredBreakpointInfoAddress := AnAddr;
    FStoredBreakpointInfoState := rbFound;
    // Most likely the debugger should see the previous address (unless we got here
    // by jump.
    // Call something like ResetInstructionPointerAfterBreakpointForPendingSignal; virtual;
    ////ResetInstructionPointerAfterBreakpoint;
  end
  else
    FStoredBreakpointInfoState := rbNone;
end;

procedure TDbgThread.ClearHasBreakpointInfoForAddressMismatch(AKeepOnlyForAddr: TDBGPtr);
begin
  if (FStoredBreakpointInfoState <> rbUnknown) and
     (FStoredBreakpointInfoAddress <> AKeepOnlyForAddr)
  then begin
    FStoredBreakpointInfoAddress := 0;
    FStoredBreakpointInfoState := rbUnknown;
  end;
end;

procedure TDbgThread.ClearHasBreakpointInfoForAddress;
begin
  FStoredBreakpointInfoAddress := 0;
  FStoredBreakpointInfoState := rbUnknown;
end;

function TDbgThread.HasBreakpointInfoForAddressMismatch(AnAddr: TDBGPtr
  ): boolean;
begin
  Result := ( (FStoredBreakpointInfoState = rbFound) and
              (FStoredBreakpointInfoAddress = AnAddr) );
end;

procedure TDbgThread.DoBeforeBreakLocationMapChange;
begin
  StoreHasBreakpointInfoForAddress(GetInstructionPointerForHasBreakpointInfoForAddress);
end;

procedure TDbgThread.ValidateRemovedBreakPointInfo;
begin
  if (FStoredBreakpointInfoState <> rbUnknown) then
    ClearHasBreakpointInfoForAddressMismatch(GetInstructionPointerForHasBreakpointInfoForAddress);
end;

function TDbgThread.GetName: String;
begin
  Result := '';
end;

function TDbgThread.GetInstructionPointerForHasBreakpointInfoForAddress: TDBGPtr;
begin
  Result := GetInstructionPointerRegisterValue;
end;

constructor TDbgThread.Create(const AProcess: TDbgProcess; const AID: Integer; const AHandle: THandle);
begin
  FID := AID;
  FHandle := AHandle;
  FProcess := AProcess;
  FRegisterValueList:=TDbgRegisterValueList.Create;
  FPreviousRegisterValueList:=TDbgRegisterValueList.Create;
  inherited Create;
end;

procedure TDbgThread.DoBeforeProcessLoop;
begin
  FPreviousRegisterValueList.Assign(FRegisterValueList);
  if FRegisterValueListValid then
    FRegisterValueList.FPreviousRegisterValueList := FPreviousRegisterValueList
  else
    FRegisterValueList.FPreviousRegisterValueList := nil;
  FRegisterValueListValid:=false;
end;

function TDbgThread.HasInsertedBreakInstructionAtLocation(const ALocation: TDBGPtr): Boolean;
begin
  Result := HasBreakpointInfoForAddressMismatch(ALocation) or
            ( (ALocation <> 0) and Process.HasInsertedBreakInstructionAtLocation(ALocation) );
end;

procedure TDbgThread.CheckAndResetInstructionPointerAfterBreakpoint;
var
  t: TDBGPtr;
begin
  // todo: check that the breakpoint is NOT in the temp removed list
  t := GetInstructionPointerForHasBreakpointInfoForAddress;
  if t = 0 then
    exit;
  if HasInsertedBreakInstructionAtLocation(t)
  then begin
    FStoredBreakpointInfoState := rbFound;
    ResetInstructionPointerAfterBreakpoint;
  end
  else begin
    // TODO: allow to skip this, while detaching
    FPausedAtHardcodeBreakPoint := Process.FBreakTargetHandler.IsHardcodeBreakPointInCode(t);
  end;
end;

function TDbgThread.CheckForHardcodeBreakPoint(AnAddr: TDBGPtr): boolean;
begin
  Result := False;
  if AnAddr = 0 then
    exit;
  FPausedAtHardcodeBreakPoint := Process.FBreakTargetHandler.IsHardcodeBreakPointInCode(AnAddr);
  Result := FPausedAtHardcodeBreakPoint;
end;

procedure TDbgThread.BeforeContinue;
begin
  FPausedAtHardcodeBreakPoint := False;
  ClearHasBreakpointInfoForAddress;
end;

procedure TDbgThread.ApplyWatchPoints(AWatchPointData: TFpWatchPointData);
begin
  //
end;

function TDbgThread.DetectHardwareWatchpoint: Pointer;
begin
  result := nil;
end;

function TDbgThread.GetCurrentStackFrameInfo: TDbgStackFrameInfo;
begin
  Result := TDbgStackFrameInfo.Create(Self);
end;

function TDbgThread.AllocStackMem(ASize: Integer): TDbgPtr;
begin
  Result := GetStackPointerRegisterValue;
  if FStackBeforeAlloc = 0 then
    FStackBeforeAlloc := Result;
  dec(Result, ASize);
  SetStackPointerRegisterValue(Result);
end;

procedure TDbgThread.RestoreStackMem;
begin
  if FStackBeforeAlloc <> 0 then
    SetStackPointerRegisterValue(FStackBeforeAlloc);
  FStackBeforeAlloc := 0;
end;

procedure TDbgThread.PrepareCallStackEntryList(AFrameRequired: Integer);
const
  MAX_FRAMES = 150000; // safety net
var
  Address, FrameBase, StackPtr: TDBGPtr;
  CountNeeded, i: integer;
  AnEntry: TDbgCallstackEntry;
  NextIdx: LongInt;
  Unwinder: TDbgStackUnwinder;
  Res: TTDbgStackUnwindResult;
begin
  // TODO: use AFrameRequired // check if already partly done
  if FCallStackEntryList = nil then begin
    FCallStackEntryList := TDbgCallstackEntryList.Create;
    FCallStackEntryList.FreeObjects:=true;
  end;
  if AFrameRequired = -2 then
    exit;

  if (AFrameRequired >= 0) and (AFrameRequired < FCallStackEntryList.Count) then
    exit;

  Unwinder := GetStackUnwinder;
  Unwinder.InitForThread(Self);

  if FCallStackEntryList.Count = 0 then begin
    Unwinder.GetTopFrame(Address, StackPtr, FrameBase, AnEntry);
    FCallStackEntryList.Add(AnEntry);
  end
  else begin
    AnEntry := FCallStackEntryList[FCallStackEntryList.Count - 1];
    Unwinder.InitForFrame(AnEntry, Address, StackPtr, FrameBase);
  end;

  NextIdx := FCallStackEntryList.Count;

  if AFrameRequired < 0 then
    AFrameRequired := MaxInt;
  CountNeeded := AFrameRequired - FCallStackEntryList.Count;
  while (CountNeeded > 0) do
  begin
    Res := Unwinder.Unwind(NextIdx, Address, StackPtr, FrameBase, AnEntry, AnEntry);
    if not (Res in [suSuccess, suGuessed]) then
      break;

    FCallStackEntryList.Add(AnEntry);
    dec(CountNeeded);
    inc(NextIdx);
  end;
  if CountNeeded > 0 then // there was an error / not possible to read more frames
    FCallStackEntryList.SetHasReadAllAvailableFrames;
end;

function TDbgThread.FindCallStackEntryByBasePointer(AFrameBasePointer: TDBGPtr;
  AMaxFrameToSearch: Integer; AStartFrame: integer): Integer;
var
  RegFP: Integer;
  AFrame: TDbgCallstackEntry;
  ARegister: TDbgRegisterValue;
  fp, prev_fp: TDBGPtr;
begin
  if Process.Mode = dm64 then
    RegFP := 6
  else
    RegFP := 5;

  Result := AStartFrame;
  prev_fp := low(prev_fp);
  while Result <= AMaxFrameToSearch do begin
    PrepareCallStackEntryList(Result+1);
    if CallStackEntryList.Count <= Result then
      exit(-1);

    AFrame := CallStackEntryList[Result];
    if AFrame = nil then
      exit(-1);
    ARegister := AFrame.RegisterValueList.FindRegisterByDwarfIndex(RegFP);
    if ARegister = nil then
      exit(-1);

    fp := ARegister.NumValue;

    if fp = AFrameBasePointer then
      exit;

    if (fp < prev_fp) or (fp > AFrameBasePointer) then
      exit(-1);

    prev_fp := fp;
    inc(Result);
  end;
end;

function TDbgThread.FindCallStackEntryByInstructionPointer(
  AInstructionPointer: TDBGPtr; AMaxFrameToSearch: Integer; AStartFrame: integer
  ): Integer;
var
  RegIP: Integer;
  AFrame: TDbgCallstackEntry;
  ARegister: TDbgRegisterValue;
  ip: TDBGPtr;
begin
  if Process.Mode = dm64 then
    RegIP := 16
  else
    RegIP := 8;

  Result := AStartFrame;
  while Result <= AMaxFrameToSearch do begin
    PrepareCallStackEntryList(Result+1);
    if CallStackEntryList.Count <= Result then
      exit(-1);

    AFrame := CallStackEntryList[Result];
    if AFrame = nil then
      exit(-1);
    ARegister := AFrame.RegisterValueList.FindRegisterByDwarfIndex(RegIP);
    if ARegister = nil then
      exit(-1);

    ip := ARegister.NumValue;

    if ip = AInstructionPointer then
      exit;

    inc(Result);
  end;
end;

procedure TDbgThread.ClearCallStack;
begin
  if FCallStackEntryList <> nil then
    FCallStackEntryList.Clear;
end;

destructor TDbgThread.Destroy;
begin
  FProcess.ThreadDestroyed(Self);
  FreeAndNil(FRegisterValueList);
  FreeAndNil(FPreviousRegisterValueList);
  ClearCallStack;
  FreeAndNil(FCallStackEntryList);
  inherited;
end;

procedure TDbgThread.ClearExceptionSignal;
begin
  // To be implemented in sub-classes
end;

procedure TDbgThread.IncSuspendCount;
begin
  inc(FSuspendCount);
end;

procedure TDbgThread.DecSuspendCount;
begin
  dec(FSuspendCount);
  DebugLn((DBG_VERBOSE or DBG_WARNINGS) and (FSuspendCount < 0), ['DecSuspendCount went negative: ', FSuspendCount])
end;

{ TFpWatchPointData }

function TFpWatchPointData.AddOwnedWatchpoint(AnOwner: Pointer;
  AnAddr: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind): boolean;
begin
  Result := False;
end;

function TFpWatchPointData.RemoveOwnedWatchpoint(AnOwner: Pointer): boolean;
begin
  Result := True;
end;

{ TFpIntelWatchPointData }

function TFpIntelWatchPointData.GetDr03(AnIndex: Integer): TDBGPtr;
begin
  Result := FDr03[AnIndex];
end;

function TFpIntelWatchPointData.GetOwner(AnIndex: Integer): Pointer;
begin
  Result := FOwners[AnIndex];
end;

function TFpIntelWatchPointData.AddOwnedWatchpoint(AnOwner: Pointer;
  AnAddr: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind): boolean;
var
  SizeBits, ModeBits: DWord;
  idx: Integer;
begin
  Result := False;
  case ASize of
    1: SizeBits := $00000 shl 2;
    2: SizeBits := $10000 shl 2;
    4: SizeBits := $30000 shl 2;
    8: SizeBits := $20000 shl 2; // Only certain cpu / must be 8byte aligned
    else exit;
  end;
  case AReadWrite of
    wpkWrite:     ModeBits := $10000;
    wpkRead:      ModeBits := $30000; // caller must check
    wpkReadWrite: ModeBits := $30000;
    wkpExec:      ModeBits := $00000; // Size must be 1 (SizeBits=0)
  end;

  for idx := 0 to 3 do begin
    if (FDr7 and (1 shl (idx * 2))) = 0 then begin
      FDr7 := FDr7 or (1 shl (idx*2))
                   or (ModeBits shl (idx*4)) // read/write
                   or (SizeBits shl (idx*4)); // size
      FDr03[idx] := AnAddr;
      FOwners[idx] := AnOwner;
      Changed := True;
      Result := True;
      break;
    end;
  end;
end;

function TFpIntelWatchPointData.RemoveOwnedWatchpoint(AnOwner: Pointer
  ): boolean;
var
  idx: Integer;
begin
  Result := False;
  for idx := 0 to 3 do begin
    if FOwners[idx] = AnOwner then begin
      FDr7 := FDr7 and not (
                   (DWord(3) shl (idx*2)) or
                   (DWord($F0000) shl (idx*4))
      );
      FDr03[idx] := 0;
      FOwners[idx] := nil;
      Changed := True;
      Result := True;
    end;
  end;
end;

{ TFpInternalBreakBase }

procedure TFpInternalBreakBase.SetProcessToNil;
begin
  FProcess := nil;
  if FFreeByDbgProcess then
    Destroy;
end;

procedure TFpInternalBreakBase.SetFreeByDbgProcess(AValue: Boolean);
begin
  inherited SetFreeByDbgProcess(AValue);
  if AValue and (FProcess = nil) then
    Destroy;
end;

procedure TFpInternalBreakBase.UpdateForLibraryLoaded(ALib: TDbgLibrary);
begin
  //
end;

procedure TFpInternalBreakBase.UpdateForLibrareUnloaded(ALib: TDbgLibrary);
begin
  //
end;

constructor TFpInternalBreakBase.Create(const AProcess: TDbgProcess);
begin
  inherited Create;
  FProcess := AProcess;
end;

{ TDbgBreak }

procedure TFpInternalBreakpoint.BeginUpdate;
begin
  inc(FUpdateStateLock);
end;

procedure TFpInternalBreakpoint.EndUpdate;
begin
  dec(FUpdateStateLock);
  if (FUpdateStateLock = 0) and FNeedUpdateState then
    TriggerUpdateState;
end;

procedure TFpInternalBreakpoint.TriggerUpdateState;
begin
  FNeedUpdateState := FUpdateStateLock > 0;
  if FNeedUpdateState then
    exit;
  UpdateState;
end;

procedure TFpInternalBreakpoint.AddErrorSetting(ALocation: TDBGPtr);
begin
  inc(FErrorSettingCount);
  TriggerUpdateState;
end;

procedure TFpInternalBreakpoint.RemoveErrorSetting(ALocation: TDBGPtr);
begin
  dec(FErrorSettingCount);
  TriggerUpdateState;
end;

function TFpInternalBreakpoint.GetState: TFpDbgBreakpointState;
begin
  Result := FState;
end;

procedure TFpInternalBreakpoint.SetState(AState: TFpDbgBreakpointState);
begin
  if AState = FState then
    exit;
  FState := AState;
  if FOn_Thread_StateChange <> nil then
    FOn_Thread_StateChange(Self, AState);
end;

procedure TFpInternalBreakpoint.UpdateState;
begin
  if (Length(FLocation) > 0) and (FErrorSettingCount = 0) then
    SetState(bksOk)
  else
    SetState(bksFailed);
end;

procedure TFpInternalBreakpoint.UpdateForLibrareUnloaded(ALib: TDbgLibrary);
var
  i, j: Integer;
  a: TDBGPtr;
begin
  BeginUpdate;
  j := 0;
  for i := 0 to Length(FLocation) - 1 do begin
    a := FLocation[i];
    FLocation[j] := a;
    if ALib.EnclosesAddressRange(a, a) then
      Process.FBreakMap.RemoveLocation(a, Self)
    else
      inc(j);
  end;
  if j < Length(FLocation) then begin
    SetLength(FLocation, j);
    TriggerUpdateState;
  end;
  EndUpdate;
end;

constructor TFpInternalBreakpoint.Create(const AProcess: TDbgProcess;
  const ALocation: TDBGPtrArray; AnEnabled: Boolean);
begin
  inherited Create(AProcess);
  Process.FBreakpointList.Add(Self);
  FLocation := ALocation;
  FEnabled := AnEnabled;
  FState := bksUnknown;
  BeginUpdate;
  if AnEnabled then
    SetBreak;
  TriggerUpdateState;
  EndUpdate;
end;

destructor TFpInternalBreakpoint.Destroy;
begin
  On_Thread_StateChange := nil;
  if Process <> nil then
    Process.FBreakpointList.Remove(Self);
  ResetBreak;
  inherited;
end;

function TFpInternalBreakpoint.Hit(const AThreadID: Integer;
  ABreakpointAddress: TDBGPtr): Boolean;
begin
  Result := False;
  assert(Process<>nil, 'TFpInternalBreakpoint.Hit: Process<>nil');
  if //Process.FBreakMap.HasId(ABreakpointAddress) and
     (Process.FBreakTargetHandler.IsHardcodeBreakPoint(ABreakpointAddress))
  then
    exit; // breakpoint on a hardcoded breakpoint
          // no need to jump back and restore instruction

  Result := true;
end;

function TFpInternalBreakpoint.HasLocation(const ALocation: TDBGPtr): Boolean;
var
  i: Integer;
begin
  Result := True;
  for i := 0 to High(FLocation) do begin
    if FLocation[i] = ALocation then
      exit;
  end;
  Result := False;
end;

procedure TFpInternalBreakpoint.AddAddress(const ALocation: TDBGPtr);
var
  l: Integer;
begin
  l := Length(FLocation);
  SetLength(FLocation, l+1);
  FLocation[l] := ALocation;
  BeginUpdate;
  if Enabled then
    Process.FBreakMap.AddLocation(ALocation, Self, True);
  TriggerUpdateState;
  EndUpdate;
end;

procedure TFpInternalBreakpoint.AddAddress(const ALocations: TDBGPtrArray);
var
  l, i: Integer;
begin
  l := Length(FLocation);
  SetLength(FLocation, l + Length(ALocations));

  BeginUpdate;
  if Enabled then begin
    for i := 0 to Length(ALocations) - 1 do begin
      FLocation[l + i] := ALocations[i];
      Process.FBreakMap.AddLocation(ALocations[i], Self, True);
    end;
  end
  else begin
    for i := 0 to Length(ALocations) - 1 do
      FLocation[l + i] := ALocations[i];
  end;
  TriggerUpdateState;
  EndUpdate;
end;

procedure TFpInternalBreakpoint.RemoveAddress(const ALocation: TDBGPtr);
var
  l, i: Integer;
begin
  l := Length(FLocation) - 1;
  i := l;
  while (i >= 0) and (FLocation[i] <> ALocation) do
    dec(i);
  if i < 0 then
    exit;
  FLocation[i] := FLocation[l];
  SetLength(FLocation, l);
  BeginUpdate;
  Process.FBreakMap.RemoveLocation(ALocation, Self);
  TriggerUpdateState;
  EndUpdate;
end;

procedure TFpInternalBreakpoint.RemoveAllAddresses;
begin
  BeginUpdate;
  ResetBreak;
  SetLength(FLocation, 0);
  FErrorSettingCount := 0;
  TriggerUpdateState;
  EndUpdate;
end;

procedure TFpInternalBreakpoint.ResetBreak;
var
  i: Integer;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadId('TFpInternalBreakpoint.ResetBreak');{$ENDIF}
  if Process = nil then
    exit;

  FEnabled := False;
  BeginUpdate;
  for i := 0 to High(FLocation) do
    Process.FBreakMap.RemoveLocation(FLocation[i], Self);
  TriggerUpdateState;
  EndUpdate;
end;

procedure TFpInternalBreakpoint.SetBreak;
var
  i: Integer;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadId('TFpInternalBreakpoint.SetBreak');{$ENDIF}
  if Process = nil then
    exit;

  FEnabled := True;
  BeginUpdate;
  for i := 0 to High(FLocation) do
    Process.FBreakMap.AddLocation(FLocation[i], Self, True);
  TriggerUpdateState;
  EndUpdate;
end;

{ TFpInternalBreakpointAtAddress }

procedure TFpInternalBreakpointAtAddress.UpdateState;
begin
  if FErrorSettingCount > 0 then begin
    FRemovedLoc := FLocation;
    SetLength(FRemovedLoc, Length(FRemovedLoc));
    RemoveAllAddresses;
    exit;
  end;

  if (Length(FLocation) > 0) and (FErrorSettingCount = 0) then
    SetState(bksOk)
  else
    SetState(bksPending);
end;

procedure TFpInternalBreakpointAtAddress.UpdateForLibraryLoaded(ALib: TDbgLibrary);
var
  a: TDBGPtrArray;
begin
  if (Length(FRemovedLoc) = 0) or
     (not ALib.EnclosesAddress(FRemovedLoc[0]))
  then
    exit;

  a := FRemovedLoc;
  FRemovedLoc := nil;
  BeginUpdate;
  AddAddress(a);
  Enabled := True; // Must have been enabled when FRemovedLoc was assigned
  EndUpdate;
end;

procedure TFpInternalBreakpointAtAddress.UpdateForLibrareUnloaded(ALib: TDbgLibrary);
begin
  if (Length(FLocation) = 0) or
     (not ALib.EnclosesAddress(FLocation[0]))
  then
    exit;

  FRemovedLoc := FLocation;
  SetLength(FRemovedLoc, Length(FRemovedLoc));
  RemoveAllAddresses;
end;

destructor TFpInternalBreakpointAtAddress.Destroy;
begin
  BeginUpdate; // no need to call EndUpdate
  inherited Destroy;
  FRemovedLoc := nil;
end;

{ TFpInternalBreakpointAtSymbol }

procedure TFpInternalBreakpointAtSymbol.UpdateState;
begin
  if FErrorSettingCount > 0 then
    SetState(bksFailed)
  else
  if Length(FLocation) > 0 then
    SetState(bksOk)
  else
    SetState(bksPending);
end;

procedure TFpInternalBreakpointAtSymbol.UpdateForLibraryLoaded(ALib: TDbgLibrary
  );
var
  a: TDBGPtrArray;
  AProcList: TFpSymbolArray;
  i: Integer;
begin
  if FSymInstance <> nil then // Can not be the newly created ...
    exit;

  Process.FindProcSymbol(FFuncName, ALib, AProcList);
  SetLength(a, Length(AProcList));
  for i := 0 to Length(AProcList) - 1 do begin
    a[i] := AProcList[i].Address.Address;
    AProcList[i].ReleaseReference;
  end;

  AddAddress(a);
end;

constructor TFpInternalBreakpointAtSymbol.Create(const AProcess: TDbgProcess;
  const AFuncName: String; AnEnabled: Boolean; ASymInstance: TDbgInstance;
  AIgnoreCase: Boolean);
var
  a: TDBGPtrArray;
  AProcList: TFpSymbolArray;
  i: Integer;
begin
  FFuncName := AFuncName;
  FSymInstance := ASymInstance;

  AProcess.FindProcSymbol(AFuncName, ASymInstance, AProcList, AIgnoreCase);
  SetLength(a, Length(AProcList));
  for i := 0 to Length(AProcList) - 1 do begin
    a[i] := AProcList[i].Address.Address;
    AProcList[i].ReleaseReference;
  end;

  inherited Create(AProcess, a, AnEnabled);
end;

{ TFpInternalBreakpointAtFileLine }

procedure TFpInternalBreakpointAtFileLine.UpdateState;
begin
  if FErrorSettingCount > 0 then
    SetState(bksFailed)
  else
  if Length(FLocation) > 0 then
    SetState(bksOk)
  else
  if FFoundFileWithoutLine then
    SetState(bksFailed)
  else
    SetState(bksPending);
end;

procedure TFpInternalBreakpointAtFileLine.UpdateForLibraryLoaded(
  ALib: TDbgLibrary);
var
  addr: TDBGPtrArray;
  m: Integer;
begin
  if FSymInstance <> nil then // Can not be the newly created ...
    exit;

  addr := nil;
  m := Process.Config.BreakpointSearchMaxLines;
  if m > 0 then
    Process.GetLineAddresses(FFileName, FLine, addr, ALib, fsNextFuncLazy, m)
  else
    Process.GetLineAddresses(FFileName, FLine, addr, ALib);
  if Process.FLastLineAddressesFoundFile and (Length(addr) = 0) then
    FFoundFileWithoutLine := True;
  AddAddress(addr);
end;

constructor TFpInternalBreakpointAtFileLine.Create(const AProcess: TDbgProcess;
  const AFileName: String; ALine: Cardinal; AnEnabled: Boolean; ASymInstance: TDbgInstance);
var
  addr: TDBGPtrArray;
  m: Integer;
begin
  FFileName := AFileName;
  FLine := ALine;
  FSymInstance := ASymInstance;

  addr := nil;
  m := AProcess.Config.BreakpointSearchMaxLines;
  if m > 0 then
    AProcess.GetLineAddresses(AFileName, ALine, addr, ASymInstance, fsNextFuncLazy, m)
  else
    AProcess.GetLineAddresses(AFileName, ALine, addr, ASymInstance);
  FFoundFileWithoutLine := AProcess.FLastLineAddressesFoundFile and (Length(addr) = 0);
  inherited Create(AProcess, addr, AnEnabled);
end;

{ TFpInternalWatchpoint }

constructor TFpInternalWatchpoint.Create(const AProcess: TDbgProcess;
  const ALocation: TDBGPtr; ASize: Cardinal; AReadWrite: TDBGWatchPointKind;
  AScope: TDBGWatchPointScope);
(* FROM INTEL DOCS / About 8 byte watchpoints
For Pentium® 4 and Intel® Xeon® processors with a CPUID signature corresponding to family 15 (model 3, 4, and 6),
break point conditions permit specifying 8-byte length on data read/write with an of encoding 10B in the LENn field.
Encoding 10B is also supported in processors based on Intel Core microarchitecture or
enhanced Intel Core microarchitecture, the respective CPUID signatures corresponding to family 6, model 15,
and family 6, DisplayModel value 23 (see CPUID instruction in Chapter 3,
“Instruction Set Reference, A-L” in the Intel® 64 and IA-32 Architectures Software Developer’s Manual, Volume 2A).
The Encoding 10B is supported in processors based on Intel® Atom™ microarchitecture,
with CPUID signature of family 6, DisplayModel value 1CH. The encoding 10B is undefined for other processors
*)
const
  MAX_WATCH_SIZE = 8;
  SIZE_TO_BOUNDMASK: array[1..8] of TDBGPtr = (
    0,        // Size=1
    1, 0,     // Size=2
    3, 0,0,0, // Size=4
    7         // Size=8
    );
  SIZE_TO_WATCHSIZE: array[0..8] of Integer = (0, 1, 2, 4, 4, 8, 8, 8, 8);
var
  MaxWatchSize: Integer;
  BoundaryOffset, S, HalfSize: Integer;
begin
  inherited Create(AProcess);
  Process.FWatchPointList.Add(Self);
  FLocation := ALocation;
  FSize := ASize;
  FReadWrite := AReadWrite;
  FScope := AScope;

  MaxWatchSize := MAX_WATCH_SIZE;
//   Wach at 13FFC20:4 TO First 13FFC18:8 Other 0 (0) Last 0

  FFirstWatchSize := MaxWatchSize;
  BoundaryOffset := Integer(FLocation and SIZE_TO_BOUNDMASK[FFirstWatchSize]);
  // As long as the full first half of the watch is unused, use the next smaller watch-size
  HalfSize := FFirstWatchSize div 2;
  while (FFirstWatchSize > 1) and
        ( (BoundaryOffset >= HalfSize) or
          (FSize <= HalfSize)
        )
  do begin
    FFirstWatchSize := HalfSize;
    HalfSize := FFirstWatchSize div 2;
    BoundaryOffset := Integer(FLocation and SIZE_TO_BOUNDMASK[FFirstWatchSize]);
  end;
  FFirstWatchLocation := FLocation - BoundaryOffset;

  FOtherWatchesSize := 0;
  FOtherWatchCount := 0;
  FLastWatchSize := 0;

  S := FSize - FFirstWatchSize + BoundaryOffset; // remainder size
  if S > 0 then begin
    FOtherWatchCount := (S - 1) div MaxWatchSize;
    if FOtherWatchCount > 0 then
      FOtherWatchesSize := MaxWatchSize;

    S := S - FOtherWatchCount * FOtherWatchesSize;
    assert(S >= 0, 'TFpInternalWatchpoint.Create: S >= 0');

    FLastWatchSize := SIZE_TO_WATCHSIZE[S];
  end;
  debugln(DBG_VERBOSE, 'Wach at %x:%d TO First %x:%d Other %d (%d) Last %d',
    [FLocation, FSize, FFirstWatchLocation, FFirstWatchSize, FOtherWatchCount, FOtherWatchesSize, FLastWatchSize]);

  SetBreak;
end;

destructor TFpInternalWatchpoint.Destroy;
begin
  if Process <> nil then
    Process.FWatchPointList.Remove(Self);
  ResetBreak;
  inherited Destroy;
end;

procedure TFpInternalWatchpoint.SetBreak;
var
  a: TDBGPtr;
  wd: TFpWatchPointData;
  R: Boolean;
  i: Integer;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadId('TFpInternalWatchpoint.SetBreak');{$ENDIF}
  if Process = nil then
    exit;
  //TODO: read current mem content. So in case of overlap it can be checked

  wd := Process.WatchPointData;

  a := FFirstWatchLocation;
  R := wd.AddOwnedWatchpoint(Self, a, FFirstWatchSize, FReadWrite);
  if not R then begin
    ResetBreak;
    exit;
  end;

  a := a + FFirstWatchSize;
  for i := 0 to FOtherWatchCount - 1 do begin
    R := wd.AddOwnedWatchpoint(Self, a, FOtherWatchesSize, FReadWrite);
    if not R then begin
      ResetBreak;
      exit;
    end;
    a := a + FOtherWatchesSize;
  end;

  if FLastWatchSize > 0 then
    R := wd.AddOwnedWatchpoint(Self, a, FLastWatchSize, FReadWrite);
  if not R then
    ResetBreak;
end;

procedure TFpInternalWatchpoint.ResetBreak;
begin
  {$IFDEF FPDEBUG_THREAD_CHECK}AssertFpDebugThreadId('TFpInternalWatchpoint.ResetBreak');{$ENDIF}
  if Process = nil then
    exit;

  Process.WatchPointData.RemoveOwnedWatchpoint(Self);
end;

function GetCanonicalFrameAddress(
  RegisterValueList: TDbgRegisterValueList; Row: TDwarfCallFrameInformationRow; out
  FrameBase: TDBGPtr): Boolean;
var
  Rule: TDwarfCallFrameInformationRule;
  Reg: TDbgRegisterValue;
begin
  Result := False;
  // Get CFA (framebase)

  Rule := Row.CFARule;
  case Rule.CFARule of
    cfaRegister:
      begin
      Reg := RegisterValueList.FindRegisterByDwarfIndex(Rule.&Register);
      if Assigned(Reg) then
        begin
        FrameBase := Reg.NumValue;
        {$PUSH}{$R-}{$Q-}
        FrameBase := FrameBase + TDBGPtr(Rule.Offset);
        {$POP}
        Result := True;
        end
      else
        begin
        DebugLn(FPDBG_DWARF_CFI_WARNINGS, 'CFI requested a register [' +IntToStr(Rule.&Register)+ '] that is not available.');
        Exit;
        end;
      end;
    cfaExpression:
      begin
      DebugLn(FPDBG_DWARF_CFI_WARNINGS, 'CFI-expressions are not supported. Not possible to obtain the CFA.');
      Exit;
      end;
    else
      begin
      DebugLn(FPDBG_DWARF_CFI_WARNINGS, 'CFI available but no rule to obtain the CFA.');
      Exit;
      end;
  end; // case
end;

function TryObtainNextCallFrame(
  CurrentCallStackEntry: TDbgCallstackEntry;
  CIE: TDwarfCIE;
  Size, NextIdx: Integer;
  Thread: TDbgThread;
  Row: TDwarfCallFrameInformationRow;
  Process: TDbgProcess;
  out NewCallStackEntry: TDbgCallstackEntry): Boolean;

  function ProcessCFIColumn(Row: TDwarfCallFrameInformationRow; Column: Byte; CFA: QWord; AddressSize: Integer; Entry: TDbgCallstackEntry; out Value: TDbgPtr): Boolean;
  var
    Rule: TDwarfCallFrameInformationRule;
    Reg: TDbgRegisterValue;
  begin
    Result := True;
    Value := 0;
    Rule := Row.RegisterArray[Column];
    case Rule.RegisterRule of
      cfiUndefined:
        begin
        Result := False;
        end;
      cfiSameValue:
        begin
        Reg := CurrentCallStackEntry.RegisterValueList.FindRegisterByDwarfIndex(Column);
        if Assigned(Reg) then
          Value := Reg.NumValue
        else
          Result := False;
        end;
      cfiOffset:
        begin
        {$PUSH}{$R-}{$Q-}
        Process.ReadData(CFA+TDBGPtr(Rule.Offset), AddressSize, Value);
        {$POP}
        end;
      cfiValOffset:
        begin
        {$PUSH}{$R-}{$Q-}
        Value := CFA+TDBGPtr(Rule.Offset);
        {$POP}
        end;
      cfiRegister:
        begin
        Reg := CurrentCallStackEntry.RegisterValueList.FindRegisterByDwarfIndex(Rule.&Register);
        if Assigned(Reg) then
          Value := Reg.NumValue
        else
          Result := False;
        end
      else
        begin
        DebugLn(FPDBG_DWARF_CFI_WARNINGS, 'Encountered unsupported CFI registerrule.');
        Result := False;
        end;
    end; // case
  end;

var
  //Rule: TDwarfCallFrameInformationRule;
  Reg: TDbgRegisterValue;
  i: Integer;
  ReturnAddress, Value: TDbgPtr;
  FrameBase: TDBGPtr;
  RegName: String;
begin
  Result := False;
  NewCallStackEntry := nil;
  // Get CFA (framebase)
  if not GetCanonicalFrameAddress(CurrentCallStackEntry.RegisterValueList, Row, FrameBase) then
    exit;

  Result := True;
  // Get return ReturnAddress
  if not ProcessCFIColumn(Row, CIE.ReturnAddressRegister, FrameBase, Size, CurrentCallStackEntry, ReturnAddress) then
    // Yes, we were succesfull, but there is no return ReturnAddress, so keep
    // NewCallStackEntry nil
    begin
    Result := True;
    Exit;
    end;

  if ReturnAddress=0 then
    // Yes, we were succesfull, but there is no frame left, so keep
    // NewCallStackEntry nil
    begin
    Result := True;
    Exit;
    end;

  NewCallStackEntry := TDbgCallstackEntry.create(Thread, NextIdx, FrameBase, ReturnAddress);

  // Fill other registers
  for i := 0 to High(Row.RegisterArray) do
    begin
    if ProcessCFIColumn(Row, i, FrameBase, Size, CurrentCallStackEntry, Value) then
      begin
      Reg := CurrentCallStackEntry.RegisterValueList.FindRegisterByDwarfIndex(i);
      if Assigned(Reg) then
        RegName := Reg.Name
      else
        RegName := IntToStr(i);
      NewCallStackEntry.RegisterValueList.DbgRegisterAutoCreate[RegName].SetValue(Value, IntToStr(Value),Size, i);
      end;
    end;
end;

initialization
  DBG_VERBOSE := DebugLogger.FindOrRegisterLogGroup('DBG_VERBOSE' {$IFDEF DBG_VERBOSE} , True {$ENDIF} );
  DBG_WARNINGS := DebugLogger.FindOrRegisterLogGroup('DBG_WARNINGS' {$IFDEF DBG_WARNINGS} , True {$ENDIF} );
  DBG_BREAKPOINTS := DebugLogger.FindOrRegisterLogGroup('DBG_BREAKPOINTS' {$IFDEF DBG_BREAKPOINTS} , True {$ENDIF} );
  FPDBG_COMMANDS := DebugLogger.FindOrRegisterLogGroup('FPDBG_COMMANDS' {$IFDEF FPDBG_COMMANDS} , True {$ENDIF} );
  FPDBG_DWARF_CFI_WARNINGS  := DebugLogger.FindOrRegisterLogGroup('FPDBG_DWARF_CFI_WARNINGS' {$IFDEF FPDBG_DWARF_CFI_WARNINGS} , True {$ENDIF} );

  TFpBreakPointTargetHandler.DBG__VERBOSE     := DBG_VERBOSE;
  TFpBreakPointTargetHandler.DBG__WARNINGS    := DBG_WARNINGS;
  TFpBreakPointTargetHandler.DBG__BREAKPOINTS := DBG_BREAKPOINTS;

finalization
  if assigned(RegisteredDbgProcessClasses) then
    FreeAndNil(RegisteredDbgProcessClasses);

end.