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
| //===-- GDBRemoteCommunicationServerLLGS.cpp --------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <errno.h>
#include "lldb/Host/Config.h"
#include "GDBRemoteCommunicationServerLLGS.h"
#include "lldb/Utility/GDBRemote.h"
#include <chrono>
#include <cstring>
#include <thread>
#include "lldb/Host/ConnectionFileDescriptor.h"
#include "lldb/Host/Debug.h"
#include "lldb/Host/File.h"
#include "lldb/Host/FileAction.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/PosixApi.h"
#include "lldb/Host/common/NativeProcessProtocol.h"
#include "lldb/Host/common/NativeRegisterContext.h"
#include "lldb/Host/common/NativeThreadProtocol.h"
#include "lldb/Target/MemoryRegionInfo.h"
#include "lldb/Utility/Args.h"
#include "lldb/Utility/DataBuffer.h"
#include "lldb/Utility/Endian.h"
#include "lldb/Utility/LLDBAssert.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/RegisterValue.h"
#include "lldb/Utility/State.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/UriParser.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/ScopedPrinter.h"
#include "ProcessGDBRemote.h"
#include "ProcessGDBRemoteLog.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
using namespace llvm;
// GDBRemote Errors
namespace {
enum GDBRemoteServerError {
// Set to the first unused error number in literal form below
eErrorFirst = 29,
eErrorNoProcess = eErrorFirst,
eErrorResume,
eErrorExitStatus
};
}
// GDBRemoteCommunicationServerLLGS constructor
GDBRemoteCommunicationServerLLGS::GDBRemoteCommunicationServerLLGS(
MainLoop &mainloop, const NativeProcessProtocol::Factory &process_factory)
: GDBRemoteCommunicationServerCommon("gdb-remote.server",
"gdb-remote.server.rx_packet"),
m_mainloop(mainloop), m_process_factory(process_factory),
m_stdio_communication("process.stdio") {
RegisterPacketHandlers();
}
void GDBRemoteCommunicationServerLLGS::RegisterPacketHandlers() {
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_C,
&GDBRemoteCommunicationServerLLGS::Handle_C);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_c,
&GDBRemoteCommunicationServerLLGS::Handle_c);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_D,
&GDBRemoteCommunicationServerLLGS::Handle_D);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_H,
&GDBRemoteCommunicationServerLLGS::Handle_H);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_I,
&GDBRemoteCommunicationServerLLGS::Handle_I);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_interrupt,
&GDBRemoteCommunicationServerLLGS::Handle_interrupt);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_m,
&GDBRemoteCommunicationServerLLGS::Handle_memory_read);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_M,
&GDBRemoteCommunicationServerLLGS::Handle_M);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_p,
&GDBRemoteCommunicationServerLLGS::Handle_p);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_P,
&GDBRemoteCommunicationServerLLGS::Handle_P);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
&GDBRemoteCommunicationServerLLGS::Handle_qC);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qfThreadInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qFileLoadAddress,
&GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
&GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qMemoryRegionInfoSupported,
&GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qRegisterInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_QRestoreRegisterState,
&GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_QSaveRegisterState,
&GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_QSetDisableASLR,
&GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
&GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qsThreadInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qThreadStopInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jThreadsInfo,
&GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qWatchpointSupportInfo,
&GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_qXfer,
&GDBRemoteCommunicationServerLLGS::Handle_qXfer);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_s,
&GDBRemoteCommunicationServerLLGS::Handle_s);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_stop_reason,
&GDBRemoteCommunicationServerLLGS::Handle_stop_reason); // ?
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_vAttach,
&GDBRemoteCommunicationServerLLGS::Handle_vAttach);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_vCont,
&GDBRemoteCommunicationServerLLGS::Handle_vCont);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_vCont_actions,
&GDBRemoteCommunicationServerLLGS::Handle_vCont_actions);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_x,
&GDBRemoteCommunicationServerLLGS::Handle_memory_read);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_Z,
&GDBRemoteCommunicationServerLLGS::Handle_Z);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_z,
&GDBRemoteCommunicationServerLLGS::Handle_z);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_QPassSignals,
&GDBRemoteCommunicationServerLLGS::Handle_QPassSignals);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jTraceStart,
&GDBRemoteCommunicationServerLLGS::Handle_jTraceStart);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jTraceBufferRead,
&GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jTraceMetaRead,
&GDBRemoteCommunicationServerLLGS::Handle_jTraceRead);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jTraceStop,
&GDBRemoteCommunicationServerLLGS::Handle_jTraceStop);
RegisterMemberFunctionHandler(
StringExtractorGDBRemote::eServerPacketType_jTraceConfigRead,
&GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead);
RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_g,
&GDBRemoteCommunicationServerLLGS::Handle_g);
RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_k,
[this](StringExtractorGDBRemote packet, Status &error,
bool &interrupt, bool &quit) {
quit = true;
return this->Handle_k(packet);
});
}
void GDBRemoteCommunicationServerLLGS::SetLaunchInfo(const ProcessLaunchInfo &info) {
m_process_launch_info = info;
}
Status GDBRemoteCommunicationServerLLGS::LaunchProcess() {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!m_process_launch_info.GetArguments().GetArgumentCount())
return Status("%s: no process command line specified to launch",
__FUNCTION__);
const bool should_forward_stdio =
m_process_launch_info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
m_process_launch_info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
m_process_launch_info.GetFileActionForFD(STDERR_FILENO) == nullptr;
m_process_launch_info.SetLaunchInSeparateProcessGroup(true);
m_process_launch_info.GetFlags().Set(eLaunchFlagDebug);
if (should_forward_stdio) {
// Temporarily relax the following for Windows until we can take advantage
// of the recently added pty support. This doesn't really affect the use of
// lldb-server on Windows.
#if !defined(_WIN32)
if (llvm::Error Err = m_process_launch_info.SetUpPtyRedirection())
return Status(std::move(Err));
#endif
}
{
std::lock_guard<std::recursive_mutex> guard(m_debugged_process_mutex);
assert(!m_debugged_process_up && "lldb-server creating debugged "
"process but one already exists");
auto process_or =
m_process_factory.Launch(m_process_launch_info, *this, m_mainloop);
if (!process_or)
return Status(process_or.takeError());
m_debugged_process_up = std::move(*process_or);
}
// Handle mirroring of inferior stdout/stderr over the gdb-remote protocol as
// needed. llgs local-process debugging may specify PTY paths, which will
// make these file actions non-null process launch -i/e/o will also make
// these file actions non-null nullptr means that the traffic is expected to
// flow over gdb-remote protocol
if (should_forward_stdio) {
// nullptr means it's not redirected to file or pty (in case of LLGS local)
// at least one of stdio will be transferred pty<->gdb-remote we need to
// give the pty master handle to this object to read and/or write
LLDB_LOG(log,
"pid = {0}: setting up stdout/stderr redirection via $O "
"gdb-remote commands",
m_debugged_process_up->GetID());
// Setup stdout/stderr mapping from inferior to $O
auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
if (terminal_fd >= 0) {
LLDB_LOGF(log,
"ProcessGDBRemoteCommunicationServerLLGS::%s setting "
"inferior STDIO fd to %d",
__FUNCTION__, terminal_fd);
Status status = SetSTDIOFileDescriptor(terminal_fd);
if (status.Fail())
return status;
} else {
LLDB_LOGF(log,
"ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
"inferior STDIO since terminal fd reported as %d",
__FUNCTION__, terminal_fd);
}
} else {
LLDB_LOG(log,
"pid = {0} skipping stdout/stderr redirection via $O: inferior "
"will communicate over client-provided file descriptors",
m_debugged_process_up->GetID());
}
printf("Launched '%s' as process %" PRIu64 "...\n",
m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
m_debugged_process_up->GetID());
return Status();
}
Status GDBRemoteCommunicationServerLLGS::AttachToProcess(lldb::pid_t pid) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64,
__FUNCTION__, pid);
// Before we try to attach, make sure we aren't already monitoring something
// else.
if (m_debugged_process_up &&
m_debugged_process_up->GetID() != LLDB_INVALID_PROCESS_ID)
return Status("cannot attach to process %" PRIu64
" when another process with pid %" PRIu64
" is being debugged.",
pid, m_debugged_process_up->GetID());
// Try to attach.
auto process_or = m_process_factory.Attach(pid, *this, m_mainloop);
if (!process_or) {
Status status(process_or.takeError());
llvm::errs() << llvm::formatv("failed to attach to process {0}: {1}", pid,
status);
return status;
}
m_debugged_process_up = std::move(*process_or);
// Setup stdout/stderr mapping from inferior.
auto terminal_fd = m_debugged_process_up->GetTerminalFileDescriptor();
if (terminal_fd >= 0) {
LLDB_LOGF(log,
"ProcessGDBRemoteCommunicationServerLLGS::%s setting "
"inferior STDIO fd to %d",
__FUNCTION__, terminal_fd);
Status status = SetSTDIOFileDescriptor(terminal_fd);
if (status.Fail())
return status;
} else {
LLDB_LOGF(log,
"ProcessGDBRemoteCommunicationServerLLGS::%s ignoring "
"inferior STDIO since terminal fd reported as %d",
__FUNCTION__, terminal_fd);
}
printf("Attached to process %" PRIu64 "...\n", pid);
return Status();
}
void GDBRemoteCommunicationServerLLGS::InitializeDelegate(
NativeProcessProtocol *process) {
assert(process && "process cannot be NULL");
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
if (log) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called with "
"NativeProcessProtocol pid %" PRIu64 ", current state: %s",
__FUNCTION__, process->GetID(),
StateAsCString(process->GetState()));
}
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::SendWResponse(
NativeProcessProtocol *process) {
assert(process && "process cannot be NULL");
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// send W notification
auto wait_status = process->GetExitStatus();
if (!wait_status) {
LLDB_LOG(log, "pid = {0}, failed to retrieve process exit status",
process->GetID());
StreamGDBRemote response;
response.PutChar('E');
response.PutHex8(GDBRemoteServerError::eErrorExitStatus);
return SendPacketNoLock(response.GetString());
}
LLDB_LOG(log, "pid = {0}, returning exit type {1}", process->GetID(),
*wait_status);
StreamGDBRemote response;
response.Format("{0:g}", *wait_status);
return SendPacketNoLock(response.GetString());
}
static void AppendHexValue(StreamString &response, const uint8_t *buf,
uint32_t buf_size, bool swap) {
int64_t i;
if (swap) {
for (i = buf_size - 1; i >= 0; i--)
response.PutHex8(buf[i]);
} else {
for (i = 0; i < buf_size; i++)
response.PutHex8(buf[i]);
}
}
static void WriteRegisterValueInHexFixedWidth(
StreamString &response, NativeRegisterContext ®_ctx,
const RegisterInfo ®_info, const RegisterValue *reg_value_p,
lldb::ByteOrder byte_order) {
RegisterValue reg_value;
if (!reg_value_p) {
Status error = reg_ctx.ReadRegister(®_info, reg_value);
if (error.Success())
reg_value_p = ®_value;
// else log.
}
if (reg_value_p) {
AppendHexValue(response, (const uint8_t *)reg_value_p->GetBytes(),
reg_value_p->GetByteSize(),
byte_order == lldb::eByteOrderLittle);
} else {
// Zero-out any unreadable values.
if (reg_info.byte_size > 0) {
std::basic_string<uint8_t> zeros(reg_info.byte_size, '\0');
AppendHexValue(response, zeros.data(), zeros.size(), false);
}
}
}
static llvm::Expected<json::Object>
GetRegistersAsJSON(NativeThreadProtocol &thread) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
NativeRegisterContext& reg_ctx = thread.GetRegisterContext();
json::Object register_object;
#ifdef LLDB_JTHREADSINFO_FULL_REGISTER_SET
// Expedite all registers in the first register set (i.e. should be GPRs)
// that are not contained in other registers.
const RegisterSet *reg_set_p = reg_ctx_sp->GetRegisterSet(0);
if (!reg_set_p)
return llvm::make_error<llvm::StringError>("failed to get registers",
llvm::inconvertibleErrorCode());
for (const uint32_t *reg_num_p = reg_set_p->registers;
*reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
uint32_t reg_num = *reg_num_p;
#else
// Expedite only a couple of registers until we figure out why sending
// registers is expensive.
static const uint32_t k_expedited_registers[] = {
LLDB_REGNUM_GENERIC_PC, LLDB_REGNUM_GENERIC_SP, LLDB_REGNUM_GENERIC_FP,
LLDB_REGNUM_GENERIC_RA, LLDB_INVALID_REGNUM};
for (const uint32_t *generic_reg_p = k_expedited_registers;
*generic_reg_p != LLDB_INVALID_REGNUM; ++generic_reg_p) {
uint32_t reg_num = reg_ctx.ConvertRegisterKindToRegisterNumber(
eRegisterKindGeneric, *generic_reg_p);
if (reg_num == LLDB_INVALID_REGNUM)
continue; // Target does not support the given register.
#endif
const RegisterInfo *const reg_info_p =
reg_ctx.GetRegisterInfoAtIndex(reg_num);
if (reg_info_p == nullptr) {
LLDB_LOGF(log,
"%s failed to get register info for register index %" PRIu32,
__FUNCTION__, reg_num);
continue;
}
if (reg_info_p->value_regs != nullptr)
continue; // Only expedite registers that are not contained in other
// registers.
RegisterValue reg_value;
Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
if (error.Fail()) {
LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
__FUNCTION__,
reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
reg_num, error.AsCString());
continue;
}
StreamString stream;
WriteRegisterValueInHexFixedWidth(stream, reg_ctx, *reg_info_p,
®_value, lldb::eByteOrderBig);
register_object.try_emplace(llvm::to_string(reg_num),
stream.GetString().str());
}
return register_object;
}
static const char *GetStopReasonString(StopReason stop_reason) {
switch (stop_reason) {
case eStopReasonTrace:
return "trace";
case eStopReasonBreakpoint:
return "breakpoint";
case eStopReasonWatchpoint:
return "watchpoint";
case eStopReasonSignal:
return "signal";
case eStopReasonException:
return "exception";
case eStopReasonExec:
return "exec";
case eStopReasonInstrumentation:
case eStopReasonInvalid:
case eStopReasonPlanComplete:
case eStopReasonThreadExiting:
case eStopReasonNone:
break; // ignored
}
return nullptr;
}
static llvm::Expected<json::Array>
GetJSONThreadsInfo(NativeProcessProtocol &process, bool abridged) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
json::Array threads_array;
// Ensure we can get info on the given thread.
uint32_t thread_idx = 0;
for (NativeThreadProtocol *thread;
(thread = process.GetThreadAtIndex(thread_idx)) != nullptr;
++thread_idx) {
lldb::tid_t tid = thread->GetID();
// Grab the reason this thread stopped.
struct ThreadStopInfo tid_stop_info;
std::string description;
if (!thread->GetStopReason(tid_stop_info, description))
return llvm::make_error<llvm::StringError>(
"failed to get stop reason", llvm::inconvertibleErrorCode());
const int signum = tid_stop_info.details.signal.signo;
if (log) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
" tid %" PRIu64
" got signal signo = %d, reason = %d, exc_type = %" PRIu64,
__FUNCTION__, process.GetID(), tid, signum,
tid_stop_info.reason, tid_stop_info.details.exception.type);
}
json::Object thread_obj;
if (!abridged) {
if (llvm::Expected<json::Object> registers =
GetRegistersAsJSON(*thread)) {
thread_obj.try_emplace("registers", std::move(*registers));
} else {
return registers.takeError();
}
}
thread_obj.try_emplace("tid", static_cast<int64_t>(tid));
if (signum != 0)
thread_obj.try_emplace("signal", signum);
const std::string thread_name = thread->GetName();
if (!thread_name.empty())
thread_obj.try_emplace("name", thread_name);
const char *stop_reason = GetStopReasonString(tid_stop_info.reason);
if (stop_reason)
thread_obj.try_emplace("reason", stop_reason);
if (!description.empty())
thread_obj.try_emplace("description", description);
if ((tid_stop_info.reason == eStopReasonException) &&
tid_stop_info.details.exception.type) {
thread_obj.try_emplace(
"metype", static_cast<int64_t>(tid_stop_info.details.exception.type));
json::Array medata_array;
for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count;
++i) {
medata_array.push_back(
static_cast<int64_t>(tid_stop_info.details.exception.data[i]));
}
thread_obj.try_emplace("medata", std::move(medata_array));
}
threads_array.push_back(std::move(thread_obj));
}
return threads_array;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::SendStopReplyPacketForThread(
lldb::tid_t tid) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
// Ensure we have a debugged process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(50);
LLDB_LOG(log, "preparing packet for pid {0} tid {1}",
m_debugged_process_up->GetID(), tid);
// Ensure we can get info on the given thread.
NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
if (!thread)
return SendErrorResponse(51);
// Grab the reason this thread stopped.
struct ThreadStopInfo tid_stop_info;
std::string description;
if (!thread->GetStopReason(tid_stop_info, description))
return SendErrorResponse(52);
// FIXME implement register handling for exec'd inferiors.
// if (tid_stop_info.reason == eStopReasonExec) {
// const bool force = true;
// InitializeRegisters(force);
// }
StreamString response;
// Output the T packet with the thread
response.PutChar('T');
int signum = tid_stop_info.details.signal.signo;
LLDB_LOG(
log,
"pid {0}, tid {1}, got signal signo = {2}, reason = {3}, exc_type = {4}",
m_debugged_process_up->GetID(), tid, signum, int(tid_stop_info.reason),
tid_stop_info.details.exception.type);
// Print the signal number.
response.PutHex8(signum & 0xff);
// Include the tid.
response.Printf("thread:%" PRIx64 ";", tid);
// Include the thread name if there is one.
const std::string thread_name = thread->GetName();
if (!thread_name.empty()) {
size_t thread_name_len = thread_name.length();
if (::strcspn(thread_name.c_str(), "$#+-;:") == thread_name_len) {
response.PutCString("name:");
response.PutCString(thread_name);
} else {
// The thread name contains special chars, send as hex bytes.
response.PutCString("hexname:");
response.PutStringAsRawHex8(thread_name);
}
response.PutChar(';');
}
// If a 'QListThreadsInStopReply' was sent to enable this feature, we will
// send all thread IDs back in the "threads" key whose value is a list of hex
// thread IDs separated by commas:
// "threads:10a,10b,10c;"
// This will save the debugger from having to send a pair of qfThreadInfo and
// qsThreadInfo packets, but it also might take a lot of room in the stop
// reply packet, so it must be enabled only on systems where there are no
// limits on packet lengths.
if (m_list_threads_in_stop_reply) {
response.PutCString("threads:");
uint32_t thread_index = 0;
NativeThreadProtocol *listed_thread;
for (listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
listed_thread; ++thread_index,
listed_thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
if (thread_index > 0)
response.PutChar(',');
response.Printf("%" PRIx64, listed_thread->GetID());
}
response.PutChar(';');
// Include JSON info that describes the stop reason for any threads that
// actually have stop reasons. We use the new "jstopinfo" key whose values
// is hex ascii JSON that contains the thread IDs thread stop info only for
// threads that have stop reasons. Only send this if we have more than one
// thread otherwise this packet has all the info it needs.
if (thread_index > 1) {
const bool threads_with_valid_stop_info_only = true;
llvm::Expected<json::Array> threads_info = GetJSONThreadsInfo(
*m_debugged_process_up, threads_with_valid_stop_info_only);
if (threads_info) {
response.PutCString("jstopinfo:");
StreamString unescaped_response;
unescaped_response.AsRawOstream() << std::move(*threads_info);
response.PutStringAsRawHex8(unescaped_response.GetData());
response.PutChar(';');
} else {
LLDB_LOG(log, "failed to prepare a jstopinfo field for pid {0}:",
m_debugged_process_up->GetID(),
llvm::toString(threads_info.takeError()));
}
}
uint32_t i = 0;
response.PutCString("thread-pcs");
char delimiter = ':';
for (NativeThreadProtocol *thread;
(thread = m_debugged_process_up->GetThreadAtIndex(i)) != nullptr;
++i) {
NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
uint32_t reg_to_read = reg_ctx.ConvertRegisterKindToRegisterNumber(
eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
const RegisterInfo *const reg_info_p =
reg_ctx.GetRegisterInfoAtIndex(reg_to_read);
RegisterValue reg_value;
Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
if (error.Fail()) {
LLDB_LOGF(log, "%s failed to read register '%s' index %" PRIu32 ": %s",
__FUNCTION__,
reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
reg_to_read, error.AsCString());
continue;
}
response.PutChar(delimiter);
delimiter = ',';
WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
®_value, endian::InlHostByteOrder());
}
response.PutChar(';');
}
//
// Expedite registers.
//
// Grab the register context.
NativeRegisterContext& reg_ctx = thread->GetRegisterContext();
// Expedite all registers in the first register set (i.e. should be GPRs)
// that are not contained in other registers.
const RegisterSet *reg_set_p;
if (reg_ctx.GetRegisterSetCount() > 0 &&
((reg_set_p = reg_ctx.GetRegisterSet(0)) != nullptr)) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s expediting registers "
"from set '%s' (registers set count: %zu)",
__FUNCTION__, reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
reg_set_p->num_registers);
for (const uint32_t *reg_num_p = reg_set_p->registers;
*reg_num_p != LLDB_INVALID_REGNUM; ++reg_num_p) {
const RegisterInfo *const reg_info_p =
reg_ctx.GetRegisterInfoAtIndex(*reg_num_p);
if (reg_info_p == nullptr) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to get "
"register info for register set '%s', register index "
"%" PRIu32,
__FUNCTION__,
reg_set_p->name ? reg_set_p->name : "<unnamed-set>",
*reg_num_p);
} else if (reg_info_p->value_regs == nullptr) {
// Only expediate registers that are not contained in other registers.
RegisterValue reg_value;
Status error = reg_ctx.ReadRegister(reg_info_p, reg_value);
if (error.Success()) {
response.Printf("%.02x:", *reg_num_p);
WriteRegisterValueInHexFixedWidth(response, reg_ctx, *reg_info_p,
®_value, lldb::eByteOrderBig);
response.PutChar(';');
} else {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to read "
"register '%s' index %" PRIu32 ": %s",
__FUNCTION__,
reg_info_p->name ? reg_info_p->name : "<unnamed-register>",
*reg_num_p, error.AsCString());
}
}
}
}
const char *reason_str = GetStopReasonString(tid_stop_info.reason);
if (reason_str != nullptr) {
response.Printf("reason:%s;", reason_str);
}
if (!description.empty()) {
// Description may contains special chars, send as hex bytes.
response.PutCString("description:");
response.PutStringAsRawHex8(description);
response.PutChar(';');
} else if ((tid_stop_info.reason == eStopReasonException) &&
tid_stop_info.details.exception.type) {
response.PutCString("metype:");
response.PutHex64(tid_stop_info.details.exception.type);
response.PutCString(";mecount:");
response.PutHex32(tid_stop_info.details.exception.data_count);
response.PutChar(';');
for (uint32_t i = 0; i < tid_stop_info.details.exception.data_count; ++i) {
response.PutCString("medata:");
response.PutHex64(tid_stop_info.details.exception.data[i]);
response.PutChar(';');
}
}
return SendPacketNoLock(response.GetString());
}
void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Exited(
NativeProcessProtocol *process) {
assert(process && "process cannot be NULL");
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
PacketResult result = SendStopReasonForState(StateType::eStateExited);
if (result != PacketResult::Success) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to send stop "
"notification for PID %" PRIu64 ", state: eStateExited",
__FUNCTION__, process->GetID());
}
// Close the pipe to the inferior terminal i/o if we launched it and set one
// up.
MaybeCloseInferiorTerminalConnection();
// We are ready to exit the debug monitor.
m_exit_now = true;
m_mainloop.RequestTermination();
}
void GDBRemoteCommunicationServerLLGS::HandleInferiorState_Stopped(
NativeProcessProtocol *process) {
assert(process && "process cannot be NULL");
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
// Send the stop reason unless this is the stop after the launch or attach.
switch (m_inferior_prev_state) {
case eStateLaunching:
case eStateAttaching:
// Don't send anything per debugserver behavior.
break;
default:
// In all other cases, send the stop reason.
PacketResult result = SendStopReasonForState(StateType::eStateStopped);
if (result != PacketResult::Success) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to send stop "
"notification for PID %" PRIu64 ", state: eStateExited",
__FUNCTION__, process->GetID());
}
break;
}
}
void GDBRemoteCommunicationServerLLGS::ProcessStateChanged(
NativeProcessProtocol *process, lldb::StateType state) {
assert(process && "process cannot be NULL");
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
if (log) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s called with "
"NativeProcessProtocol pid %" PRIu64 ", state: %s",
__FUNCTION__, process->GetID(), StateAsCString(state));
}
switch (state) {
case StateType::eStateRunning:
StartSTDIOForwarding();
break;
case StateType::eStateStopped:
// Make sure we get all of the pending stdout/stderr from the inferior and
// send it to the lldb host before we send the state change notification
SendProcessOutput();
// Then stop the forwarding, so that any late output (see llvm.org/pr25652)
// does not interfere with our protocol.
StopSTDIOForwarding();
HandleInferiorState_Stopped(process);
break;
case StateType::eStateExited:
// Same as above
SendProcessOutput();
StopSTDIOForwarding();
HandleInferiorState_Exited(process);
break;
default:
if (log) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s didn't handle state "
"change for pid %" PRIu64 ", new state: %s",
__FUNCTION__, process->GetID(), StateAsCString(state));
}
break;
}
// Remember the previous state reported to us.
m_inferior_prev_state = state;
}
void GDBRemoteCommunicationServerLLGS::DidExec(NativeProcessProtocol *process) {
ClearProcessSpecificData();
}
void GDBRemoteCommunicationServerLLGS::DataAvailableCallback() {
Log *log(GetLogIfAnyCategoriesSet(GDBR_LOG_COMM));
if (!m_handshake_completed) {
if (!HandshakeWithClient()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s handshake with "
"client failed, exiting",
__FUNCTION__);
m_mainloop.RequestTermination();
return;
}
m_handshake_completed = true;
}
bool interrupt = false;
bool done = false;
Status error;
while (true) {
const PacketResult result = GetPacketAndSendResponse(
std::chrono::microseconds(0), error, interrupt, done);
if (result == PacketResult::ErrorReplyTimeout)
break; // No more packets in the queue
if ((result != PacketResult::Success)) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s processing a packet "
"failed: %s",
__FUNCTION__, error.AsCString());
m_mainloop.RequestTermination();
break;
}
}
}
Status GDBRemoteCommunicationServerLLGS::InitializeConnection(
std::unique_ptr<Connection> &&connection) {
IOObjectSP read_object_sp = connection->GetReadObject();
GDBRemoteCommunicationServer::SetConnection(connection.release());
Status error;
m_network_handle_up = m_mainloop.RegisterReadObject(
read_object_sp, [this](MainLoopBase &) { DataAvailableCallback(); },
error);
return error;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::SendONotification(const char *buffer,
uint32_t len) {
if ((buffer == nullptr) || (len == 0)) {
// Nothing to send.
return PacketResult::Success;
}
StreamString response;
response.PutChar('O');
response.PutBytesAsRawHex8(buffer, len);
return SendPacketNoLock(response.GetString());
}
Status GDBRemoteCommunicationServerLLGS::SetSTDIOFileDescriptor(int fd) {
Status error;
// Set up the reading/handling of process I/O
std::unique_ptr<ConnectionFileDescriptor> conn_up(
new ConnectionFileDescriptor(fd, true));
if (!conn_up) {
error.SetErrorString("failed to create ConnectionFileDescriptor");
return error;
}
m_stdio_communication.SetCloseOnEOF(false);
m_stdio_communication.SetConnection(conn_up.release());
if (!m_stdio_communication.IsConnected()) {
error.SetErrorString(
"failed to set connection for inferior I/O communication");
return error;
}
return Status();
}
void GDBRemoteCommunicationServerLLGS::StartSTDIOForwarding() {
// Don't forward if not connected (e.g. when attaching).
if (!m_stdio_communication.IsConnected())
return;
Status error;
lldbassert(!m_stdio_handle_up);
m_stdio_handle_up = m_mainloop.RegisterReadObject(
m_stdio_communication.GetConnection()->GetReadObject(),
[this](MainLoopBase &) { SendProcessOutput(); }, error);
if (!m_stdio_handle_up) {
// Not much we can do about the failure. Log it and continue without
// forwarding.
if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s Failed to set up stdio "
"forwarding: %s",
__FUNCTION__, error.AsCString());
}
}
void GDBRemoteCommunicationServerLLGS::StopSTDIOForwarding() {
m_stdio_handle_up.reset();
}
void GDBRemoteCommunicationServerLLGS::SendProcessOutput() {
char buffer[1024];
ConnectionStatus status;
Status error;
while (true) {
size_t bytes_read = m_stdio_communication.Read(
buffer, sizeof buffer, std::chrono::microseconds(0), status, &error);
switch (status) {
case eConnectionStatusSuccess:
SendONotification(buffer, bytes_read);
break;
case eConnectionStatusLostConnection:
case eConnectionStatusEndOfFile:
case eConnectionStatusError:
case eConnectionStatusNoConnection:
if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS))
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s Stopping stdio "
"forwarding as communication returned status %d (error: "
"%s)",
__FUNCTION__, status, error.AsCString());
m_stdio_handle_up.reset();
return;
case eConnectionStatusInterrupted:
case eConnectionStatusTimedOut:
return;
}
}
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_jTraceStart(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
if (!packet.ConsumeFront("jTraceStart:"))
return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
TraceOptions options;
uint64_t type = std::numeric_limits<uint64_t>::max();
uint64_t buffersize = std::numeric_limits<uint64_t>::max();
lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
uint64_t metabuffersize = std::numeric_limits<uint64_t>::max();
auto json_object = StructuredData::ParseJSON(packet.Peek());
if (!json_object ||
json_object->GetType() != lldb::eStructuredDataTypeDictionary)
return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
auto json_dict = json_object->GetAsDictionary();
json_dict->GetValueForKeyAsInteger("metabuffersize", metabuffersize);
options.setMetaDataBufferSize(metabuffersize);
json_dict->GetValueForKeyAsInteger("buffersize", buffersize);
options.setTraceBufferSize(buffersize);
json_dict->GetValueForKeyAsInteger("type", type);
options.setType(static_cast<lldb::TraceType>(type));
json_dict->GetValueForKeyAsInteger("threadid", tid);
options.setThreadID(tid);
StructuredData::ObjectSP custom_params_sp =
json_dict->GetValueForKey("params");
if (custom_params_sp &&
custom_params_sp->GetType() != lldb::eStructuredDataTypeDictionary)
return SendIllFormedResponse(packet, "jTraceStart: Ill formed packet ");
options.setTraceParams(
static_pointer_cast<StructuredData::Dictionary>(custom_params_sp));
if (buffersize == std::numeric_limits<uint64_t>::max() ||
type != lldb::TraceType::eTraceTypeProcessorTrace) {
LLDB_LOG(log, "Ill formed packet buffersize = {0} type = {1}", buffersize,
type);
return SendIllFormedResponse(packet, "JTrace:start: Ill formed packet ");
}
Status error;
lldb::user_id_t uid = LLDB_INVALID_UID;
uid = m_debugged_process_up->StartTrace(options, error);
LLDB_LOG(log, "uid is {0} , error is {1}", uid, error.GetError());
if (error.Fail())
return SendErrorResponse(error);
StreamGDBRemote response;
response.Printf("%" PRIx64, uid);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_jTraceStop(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
if (!packet.ConsumeFront("jTraceStop:"))
return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
lldb::user_id_t uid = LLDB_INVALID_UID;
lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
auto json_object = StructuredData::ParseJSON(packet.Peek());
if (!json_object ||
json_object->GetType() != lldb::eStructuredDataTypeDictionary)
return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
auto json_dict = json_object->GetAsDictionary();
if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
return SendIllFormedResponse(packet, "jTraceStop: Ill formed packet ");
json_dict->GetValueForKeyAsInteger("threadid", tid);
Status error = m_debugged_process_up->StopTrace(uid, tid);
if (error.Fail())
return SendErrorResponse(error);
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_jTraceConfigRead(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
if (!packet.ConsumeFront("jTraceConfigRead:"))
return SendIllFormedResponse(packet,
"jTraceConfigRead: Ill formed packet ");
lldb::user_id_t uid = LLDB_INVALID_UID;
lldb::tid_t threadid = LLDB_INVALID_THREAD_ID;
auto json_object = StructuredData::ParseJSON(packet.Peek());
if (!json_object ||
json_object->GetType() != lldb::eStructuredDataTypeDictionary)
return SendIllFormedResponse(packet,
"jTraceConfigRead: Ill formed packet ");
auto json_dict = json_object->GetAsDictionary();
if (!json_dict->GetValueForKeyAsInteger("traceid", uid))
return SendIllFormedResponse(packet,
"jTraceConfigRead: Ill formed packet ");
json_dict->GetValueForKeyAsInteger("threadid", threadid);
TraceOptions options;
StreamGDBRemote response;
options.setThreadID(threadid);
Status error = m_debugged_process_up->GetTraceConfig(uid, options);
if (error.Fail())
return SendErrorResponse(error);
StreamGDBRemote escaped_response;
StructuredData::Dictionary json_packet;
json_packet.AddIntegerItem("type", options.getType());
json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize());
json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize());
StructuredData::DictionarySP custom_params = options.getTraceParams();
if (custom_params)
json_packet.AddItem("params", custom_params);
StreamString json_string;
json_packet.Dump(json_string, false);
escaped_response.PutEscapedBytes(json_string.GetData(),
json_string.GetSize());
return SendPacketNoLock(escaped_response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_jTraceRead(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
enum PacketType { MetaData, BufferData };
PacketType tracetype = MetaData;
if (packet.ConsumeFront("jTraceBufferRead:"))
tracetype = BufferData;
else if (packet.ConsumeFront("jTraceMetaRead:"))
tracetype = MetaData;
else {
return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
}
lldb::user_id_t uid = LLDB_INVALID_UID;
uint64_t byte_count = std::numeric_limits<uint64_t>::max();
lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
uint64_t offset = std::numeric_limits<uint64_t>::max();
auto json_object = StructuredData::ParseJSON(packet.Peek());
if (!json_object ||
json_object->GetType() != lldb::eStructuredDataTypeDictionary)
return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
auto json_dict = json_object->GetAsDictionary();
if (!json_dict->GetValueForKeyAsInteger("traceid", uid) ||
!json_dict->GetValueForKeyAsInteger("offset", offset) ||
!json_dict->GetValueForKeyAsInteger("buffersize", byte_count))
return SendIllFormedResponse(packet, "jTrace: Ill formed packet ");
json_dict->GetValueForKeyAsInteger("threadid", tid);
// Allocate the response buffer.
std::unique_ptr<uint8_t[]> buffer (new (std::nothrow) uint8_t[byte_count]);
if (!buffer)
return SendErrorResponse(0x78);
StreamGDBRemote response;
Status error;
llvm::MutableArrayRef<uint8_t> buf(buffer.get(), byte_count);
if (tracetype == BufferData)
error = m_debugged_process_up->GetData(uid, tid, buf, offset);
else if (tracetype == MetaData)
error = m_debugged_process_up->GetMetaData(uid, tid, buf, offset);
if (error.Fail())
return SendErrorResponse(error);
for (auto i : buf)
response.PutHex8(i);
StreamGDBRemote escaped_response;
escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
return SendPacketNoLock(escaped_response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qProcessInfo(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
lldb::pid_t pid = m_debugged_process_up->GetID();
if (pid == LLDB_INVALID_PROCESS_ID)
return SendErrorResponse(1);
ProcessInstanceInfo proc_info;
if (!Host::GetProcessInfo(pid, proc_info))
return SendErrorResponse(1);
StreamString response;
CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qC(StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
// Make sure we set the current thread so g and p packets return the data the
// gdb will expect.
lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
SetCurrentThreadID(tid);
NativeThreadProtocol *thread = m_debugged_process_up->GetCurrentThread();
if (!thread)
return SendErrorResponse(69);
StreamString response;
response.Printf("QC%" PRIx64, thread->GetID());
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_k(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
StopSTDIOForwarding();
if (!m_debugged_process_up) {
LLDB_LOG(log, "No debugged process found.");
return PacketResult::Success;
}
Status error = m_debugged_process_up->Kill();
if (error.Fail())
LLDB_LOG(log, "Failed to kill debugged process {0}: {1}",
m_debugged_process_up->GetID(), error);
// No OK response for kill packet.
// return SendOKResponse ();
return PacketResult::Success;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_QSetDisableASLR(
StringExtractorGDBRemote &packet) {
packet.SetFilePos(::strlen("QSetDisableASLR:"));
if (packet.GetU32(0))
m_process_launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
else
m_process_launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_QSetWorkingDir(
StringExtractorGDBRemote &packet) {
packet.SetFilePos(::strlen("QSetWorkingDir:"));
std::string path;
packet.GetHexByteString(path);
m_process_launch_info.SetWorkingDirectory(FileSpec(path));
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qGetWorkingDir(
StringExtractorGDBRemote &packet) {
FileSpec working_dir{m_process_launch_info.GetWorkingDirectory()};
if (working_dir) {
StreamString response;
response.PutStringAsRawHex8(working_dir.GetCString());
return SendPacketNoLock(response.GetString());
}
return SendErrorResponse(14);
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_C(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
// Ensure we have a native process.
if (!m_debugged_process_up) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s no debugged process "
"shared pointer",
__FUNCTION__);
return SendErrorResponse(0x36);
}
// Pull out the signal number.
packet.SetFilePos(::strlen("C"));
if (packet.GetBytesLeft() < 1) {
// Shouldn't be using a C without a signal.
return SendIllFormedResponse(packet, "C packet specified without signal.");
}
const uint32_t signo =
packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
if (signo == std::numeric_limits<uint32_t>::max())
return SendIllFormedResponse(packet, "failed to parse signal number");
// Handle optional continue address.
if (packet.GetBytesLeft() > 0) {
// FIXME add continue at address support for $C{signo}[;{continue-address}].
if (*packet.Peek() == ';')
return SendUnimplementedResponse(packet.GetStringRef().data());
else
return SendIllFormedResponse(
packet, "unexpected content after $C{signal-number}");
}
ResumeActionList resume_actions(StateType::eStateRunning,
LLDB_INVALID_SIGNAL_NUMBER);
Status error;
// We have two branches: what to do if a continue thread is specified (in
// which case we target sending the signal to that thread), or when we don't
// have a continue thread set (in which case we send a signal to the
// process).
// TODO discuss with Greg Clayton, make sure this makes sense.
lldb::tid_t signal_tid = GetContinueThreadID();
if (signal_tid != LLDB_INVALID_THREAD_ID) {
// The resume action for the continue thread (or all threads if a continue
// thread is not set).
ResumeAction action = {GetContinueThreadID(), StateType::eStateRunning,
static_cast<int>(signo)};
// Add the action for the continue thread (or all threads when the continue
// thread isn't present).
resume_actions.Append(action);
} else {
// Send the signal to the process since we weren't targeting a specific
// continue thread with the signal.
error = m_debugged_process_up->Signal(signo);
if (error.Fail()) {
LLDB_LOG(log, "failed to send signal for process {0}: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x52);
}
}
// Resume the threads.
error = m_debugged_process_up->Resume(resume_actions);
if (error.Fail()) {
LLDB_LOG(log, "failed to resume threads for process {0}: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x38);
}
// Don't send an "OK" packet; response is the stopped/exited message.
return PacketResult::Success;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_c(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s called", __FUNCTION__);
packet.SetFilePos(packet.GetFilePos() + ::strlen("c"));
// For now just support all continue.
const bool has_continue_address = (packet.GetBytesLeft() > 0);
if (has_continue_address) {
LLDB_LOG(log, "not implemented for c[address] variant [{0} remains]",
packet.Peek());
return SendUnimplementedResponse(packet.GetStringRef().data());
}
// Ensure we have a native process.
if (!m_debugged_process_up) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s no debugged process "
"shared pointer",
__FUNCTION__);
return SendErrorResponse(0x36);
}
// Build the ResumeActionList
ResumeActionList actions(StateType::eStateRunning,
LLDB_INVALID_SIGNAL_NUMBER);
Status error = m_debugged_process_up->Resume(actions);
if (error.Fail()) {
LLDB_LOG(log, "c failed for process {0}: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(GDBRemoteServerError::eErrorResume);
}
LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
// No response required from continue.
return PacketResult::Success;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_vCont_actions(
StringExtractorGDBRemote &packet) {
StreamString response;
response.Printf("vCont;c;C;s;S");
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_vCont(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOGF(log, "GDBRemoteCommunicationServerLLGS::%s handling vCont packet",
__FUNCTION__);
packet.SetFilePos(::strlen("vCont"));
if (packet.GetBytesLeft() == 0) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s missing action from "
"vCont package",
__FUNCTION__);
return SendIllFormedResponse(packet, "Missing action from vCont package");
}
// Check if this is all continue (no options or ";c").
if (::strcmp(packet.Peek(), ";c") == 0) {
// Move past the ';', then do a simple 'c'.
packet.SetFilePos(packet.GetFilePos() + 1);
return Handle_c(packet);
} else if (::strcmp(packet.Peek(), ";s") == 0) {
// Move past the ';', then do a simple 's'.
packet.SetFilePos(packet.GetFilePos() + 1);
return Handle_s(packet);
}
// Ensure we have a native process.
if (!m_debugged_process_up) {
LLDB_LOG(log, "no debugged process");
return SendErrorResponse(0x36);
}
ResumeActionList thread_actions;
while (packet.GetBytesLeft() && *packet.Peek() == ';') {
// Skip the semi-colon.
packet.GetChar();
// Build up the thread action.
ResumeAction thread_action;
thread_action.tid = LLDB_INVALID_THREAD_ID;
thread_action.state = eStateInvalid;
thread_action.signal = LLDB_INVALID_SIGNAL_NUMBER;
const char action = packet.GetChar();
switch (action) {
case 'C':
thread_action.signal = packet.GetHexMaxU32(false, 0);
if (thread_action.signal == 0)
return SendIllFormedResponse(
packet, "Could not parse signal in vCont packet C action");
LLVM_FALLTHROUGH;
case 'c':
// Continue
thread_action.state = eStateRunning;
break;
case 'S':
thread_action.signal = packet.GetHexMaxU32(false, 0);
if (thread_action.signal == 0)
return SendIllFormedResponse(
packet, "Could not parse signal in vCont packet S action");
LLVM_FALLTHROUGH;
case 's':
// Step
thread_action.state = eStateStepping;
break;
default:
return SendIllFormedResponse(packet, "Unsupported vCont action");
break;
}
// Parse out optional :{thread-id} value.
if (packet.GetBytesLeft() && (*packet.Peek() == ':')) {
// Consume the separator.
packet.GetChar();
thread_action.tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
if (thread_action.tid == LLDB_INVALID_THREAD_ID)
return SendIllFormedResponse(
packet, "Could not parse thread number in vCont packet");
}
thread_actions.Append(thread_action);
}
Status error = m_debugged_process_up->Resume(thread_actions);
if (error.Fail()) {
LLDB_LOG(log, "vCont failed for process {0}: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(GDBRemoteServerError::eErrorResume);
}
LLDB_LOG(log, "continued process {0}", m_debugged_process_up->GetID());
// No response required from vCont.
return PacketResult::Success;
}
void GDBRemoteCommunicationServerLLGS::SetCurrentThreadID(lldb::tid_t tid) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
LLDB_LOG(log, "setting current thread id to {0}", tid);
m_current_tid = tid;
if (m_debugged_process_up)
m_debugged_process_up->SetCurrentThreadID(m_current_tid);
}
void GDBRemoteCommunicationServerLLGS::SetContinueThreadID(lldb::tid_t tid) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
LLDB_LOG(log, "setting continue thread id to {0}", tid);
m_continue_tid = tid;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_stop_reason(
StringExtractorGDBRemote &packet) {
// Handle the $? gdbremote command.
// If no process, indicate error
if (!m_debugged_process_up)
return SendErrorResponse(02);
return SendStopReasonForState(m_debugged_process_up->GetState());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::SendStopReasonForState(
lldb::StateType process_state) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
switch (process_state) {
case eStateAttaching:
case eStateLaunching:
case eStateRunning:
case eStateStepping:
case eStateDetached:
// NOTE: gdb protocol doc looks like it should return $OK
// when everything is running (i.e. no stopped result).
return PacketResult::Success; // Ignore
case eStateSuspended:
case eStateStopped:
case eStateCrashed: {
lldb::tid_t tid = m_debugged_process_up->GetCurrentThreadID();
// Make sure we set the current thread so g and p packets return the data
// the gdb will expect.
SetCurrentThreadID(tid);
return SendStopReplyPacketForThread(tid);
}
case eStateInvalid:
case eStateUnloaded:
case eStateExited:
return SendWResponse(m_debugged_process_up.get());
default:
LLDB_LOG(log, "pid {0}, current state reporting not handled: {1}",
m_debugged_process_up->GetID(), process_state);
break;
}
return SendErrorResponse(0);
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qRegisterInfo(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(68);
// Ensure we have a thread.
NativeThreadProtocol *thread = m_debugged_process_up->GetThreadAtIndex(0);
if (!thread)
return SendErrorResponse(69);
// Get the register context for the first thread.
NativeRegisterContext ®_context = thread->GetRegisterContext();
// Parse out the register number from the request.
packet.SetFilePos(strlen("qRegisterInfo"));
const uint32_t reg_index =
packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
if (reg_index == std::numeric_limits<uint32_t>::max())
return SendErrorResponse(69);
// Return the end of registers response if we've iterated one past the end of
// the register set.
if (reg_index >= reg_context.GetUserRegisterCount())
return SendErrorResponse(69);
const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
if (!reg_info)
return SendErrorResponse(69);
// Build the reginfos response.
StreamGDBRemote response;
response.PutCString("name:");
response.PutCString(reg_info->name);
response.PutChar(';');
if (reg_info->alt_name && reg_info->alt_name[0]) {
response.PutCString("alt-name:");
response.PutCString(reg_info->alt_name);
response.PutChar(';');
}
response.Printf("bitsize:%" PRIu32 ";offset:%" PRIu32 ";",
reg_info->byte_size * 8, reg_info->byte_offset);
switch (reg_info->encoding) {
case eEncodingUint:
response.PutCString("encoding:uint;");
break;
case eEncodingSint:
response.PutCString("encoding:sint;");
break;
case eEncodingIEEE754:
response.PutCString("encoding:ieee754;");
break;
case eEncodingVector:
response.PutCString("encoding:vector;");
break;
default:
break;
}
switch (reg_info->format) {
case eFormatBinary:
response.PutCString("format:binary;");
break;
case eFormatDecimal:
response.PutCString("format:decimal;");
break;
case eFormatHex:
response.PutCString("format:hex;");
break;
case eFormatFloat:
response.PutCString("format:float;");
break;
case eFormatVectorOfSInt8:
response.PutCString("format:vector-sint8;");
break;
case eFormatVectorOfUInt8:
response.PutCString("format:vector-uint8;");
break;
case eFormatVectorOfSInt16:
response.PutCString("format:vector-sint16;");
break;
case eFormatVectorOfUInt16:
response.PutCString("format:vector-uint16;");
break;
case eFormatVectorOfSInt32:
response.PutCString("format:vector-sint32;");
break;
case eFormatVectorOfUInt32:
response.PutCString("format:vector-uint32;");
break;
case eFormatVectorOfFloat32:
response.PutCString("format:vector-float32;");
break;
case eFormatVectorOfUInt64:
response.PutCString("format:vector-uint64;");
break;
case eFormatVectorOfUInt128:
response.PutCString("format:vector-uint128;");
break;
default:
break;
};
const char *const register_set_name =
reg_context.GetRegisterSetNameForRegisterAtIndex(reg_index);
if (register_set_name) {
response.PutCString("set:");
response.PutCString(register_set_name);
response.PutChar(';');
}
if (reg_info->kinds[RegisterKind::eRegisterKindEHFrame] !=
LLDB_INVALID_REGNUM)
response.Printf("ehframe:%" PRIu32 ";",
reg_info->kinds[RegisterKind::eRegisterKindEHFrame]);
if (reg_info->kinds[RegisterKind::eRegisterKindDWARF] != LLDB_INVALID_REGNUM)
response.Printf("dwarf:%" PRIu32 ";",
reg_info->kinds[RegisterKind::eRegisterKindDWARF]);
switch (reg_info->kinds[RegisterKind::eRegisterKindGeneric]) {
case LLDB_REGNUM_GENERIC_PC:
response.PutCString("generic:pc;");
break;
case LLDB_REGNUM_GENERIC_SP:
response.PutCString("generic:sp;");
break;
case LLDB_REGNUM_GENERIC_FP:
response.PutCString("generic:fp;");
break;
case LLDB_REGNUM_GENERIC_RA:
response.PutCString("generic:ra;");
break;
case LLDB_REGNUM_GENERIC_FLAGS:
response.PutCString("generic:flags;");
break;
case LLDB_REGNUM_GENERIC_ARG1:
response.PutCString("generic:arg1;");
break;
case LLDB_REGNUM_GENERIC_ARG2:
response.PutCString("generic:arg2;");
break;
case LLDB_REGNUM_GENERIC_ARG3:
response.PutCString("generic:arg3;");
break;
case LLDB_REGNUM_GENERIC_ARG4:
response.PutCString("generic:arg4;");
break;
case LLDB_REGNUM_GENERIC_ARG5:
response.PutCString("generic:arg5;");
break;
case LLDB_REGNUM_GENERIC_ARG6:
response.PutCString("generic:arg6;");
break;
case LLDB_REGNUM_GENERIC_ARG7:
response.PutCString("generic:arg7;");
break;
case LLDB_REGNUM_GENERIC_ARG8:
response.PutCString("generic:arg8;");
break;
default:
break;
}
if (reg_info->value_regs && reg_info->value_regs[0] != LLDB_INVALID_REGNUM) {
response.PutCString("container-regs:");
int i = 0;
for (const uint32_t *reg_num = reg_info->value_regs;
*reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
if (i > 0)
response.PutChar(',');
response.Printf("%" PRIx32, *reg_num);
}
response.PutChar(';');
}
if (reg_info->invalidate_regs && reg_info->invalidate_regs[0]) {
response.PutCString("invalidate-regs:");
int i = 0;
for (const uint32_t *reg_num = reg_info->invalidate_regs;
*reg_num != LLDB_INVALID_REGNUM; ++reg_num, ++i) {
if (i > 0)
response.PutChar(',');
response.Printf("%" PRIx32, *reg_num);
}
response.PutChar(';');
}
if (reg_info->dynamic_size_dwarf_expr_bytes) {
const size_t dwarf_opcode_len = reg_info->dynamic_size_dwarf_len;
response.PutCString("dynamic_size_dwarf_expr_bytes:");
for (uint32_t i = 0; i < dwarf_opcode_len; ++i)
response.PutHex8(reg_info->dynamic_size_dwarf_expr_bytes[i]);
response.PutChar(';');
}
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qfThreadInfo(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOG(log, "no process ({0}), returning OK",
m_debugged_process_up ? "invalid process id"
: "null m_debugged_process_up");
return SendOKResponse();
}
StreamGDBRemote response;
response.PutChar('m');
LLDB_LOG(log, "starting thread iteration");
NativeThreadProtocol *thread;
uint32_t thread_index;
for (thread_index = 0,
thread = m_debugged_process_up->GetThreadAtIndex(thread_index);
thread; ++thread_index,
thread = m_debugged_process_up->GetThreadAtIndex(thread_index)) {
LLDB_LOG(log, "iterated thread {0}(tid={2})", thread_index,
thread->GetID());
if (thread_index > 0)
response.PutChar(',');
response.Printf("%" PRIx64, thread->GetID());
}
LLDB_LOG(log, "finished thread iteration");
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qsThreadInfo(
StringExtractorGDBRemote &packet) {
// FIXME for now we return the full thread list in the initial packet and
// always do nothing here.
return SendPacketNoLock("l");
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_g(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Move past packet name.
packet.SetFilePos(strlen("g"));
// Get the thread to use.
NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
if (!thread) {
LLDB_LOG(log, "failed, no thread available");
return SendErrorResponse(0x15);
}
// Get the thread's register context.
NativeRegisterContext ®_ctx = thread->GetRegisterContext();
std::vector<uint8_t> regs_buffer;
for (uint32_t reg_num = 0; reg_num < reg_ctx.GetUserRegisterCount();
++reg_num) {
const RegisterInfo *reg_info = reg_ctx.GetRegisterInfoAtIndex(reg_num);
if (reg_info == nullptr) {
LLDB_LOG(log, "failed to get register info for register index {0}",
reg_num);
return SendErrorResponse(0x15);
}
if (reg_info->value_regs != nullptr)
continue; // skip registers that are contained in other registers
RegisterValue reg_value;
Status error = reg_ctx.ReadRegister(reg_info, reg_value);
if (error.Fail()) {
LLDB_LOG(log, "failed to read register at index {0}", reg_num);
return SendErrorResponse(0x15);
}
if (reg_info->byte_offset + reg_info->byte_size >= regs_buffer.size())
// Resize the buffer to guarantee it can store the register offsetted
// data.
regs_buffer.resize(reg_info->byte_offset + reg_info->byte_size);
// Copy the register offsetted data to the buffer.
memcpy(regs_buffer.data() + reg_info->byte_offset, reg_value.GetBytes(),
reg_info->byte_size);
}
// Write the response.
StreamGDBRemote response;
response.PutBytesAsRawHex8(regs_buffer.data(), regs_buffer.size());
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_p(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Parse out the register number from the request.
packet.SetFilePos(strlen("p"));
const uint32_t reg_index =
packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
if (reg_index == std::numeric_limits<uint32_t>::max()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, could not "
"parse register number from request \"%s\"",
__FUNCTION__, packet.GetStringRef().data());
return SendErrorResponse(0x15);
}
// Get the thread to use.
NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
if (!thread) {
LLDB_LOG(log, "failed, no thread available");
return SendErrorResponse(0x15);
}
// Get the thread's register context.
NativeRegisterContext ®_context = thread->GetRegisterContext();
// Return the end of registers response if we've iterated one past the end of
// the register set.
if (reg_index >= reg_context.GetUserRegisterCount()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, requested "
"register %" PRIu32 " beyond register count %" PRIu32,
__FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
return SendErrorResponse(0x15);
}
const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
if (!reg_info) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, requested "
"register %" PRIu32 " returned NULL",
__FUNCTION__, reg_index);
return SendErrorResponse(0x15);
}
// Build the reginfos response.
StreamGDBRemote response;
// Retrieve the value
RegisterValue reg_value;
Status error = reg_context.ReadRegister(reg_info, reg_value);
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, read of "
"requested register %" PRIu32 " (%s) failed: %s",
__FUNCTION__, reg_index, reg_info->name, error.AsCString());
return SendErrorResponse(0x15);
}
const uint8_t *const data =
reinterpret_cast<const uint8_t *>(reg_value.GetBytes());
if (!data) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to get data "
"bytes from requested register %" PRIu32,
__FUNCTION__, reg_index);
return SendErrorResponse(0x15);
}
// FIXME flip as needed to get data in big/little endian format for this host.
for (uint32_t i = 0; i < reg_value.GetByteSize(); ++i)
response.PutHex8(data[i]);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_P(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Ensure there is more content.
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Empty P packet");
// Parse out the register number from the request.
packet.SetFilePos(strlen("P"));
const uint32_t reg_index =
packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
if (reg_index == std::numeric_limits<uint32_t>::max()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, could not "
"parse register number from request \"%s\"",
__FUNCTION__, packet.GetStringRef().data());
return SendErrorResponse(0x29);
}
// Note debugserver would send an E30 here.
if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != '='))
return SendIllFormedResponse(
packet, "P packet missing '=' char after register number");
// Parse out the value.
uint8_t reg_bytes[32]; // big enough to support up to 256 bit ymmN register
size_t reg_size = packet.GetHexBytesAvail(reg_bytes);
// Get the thread to use.
NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
if (!thread) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, no thread "
"available (thread index 0)",
__FUNCTION__);
return SendErrorResponse(0x28);
}
// Get the thread's register context.
NativeRegisterContext ®_context = thread->GetRegisterContext();
const RegisterInfo *reg_info = reg_context.GetRegisterInfoAtIndex(reg_index);
if (!reg_info) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, requested "
"register %" PRIu32 " returned NULL",
__FUNCTION__, reg_index);
return SendErrorResponse(0x48);
}
// Return the end of registers response if we've iterated one past the end of
// the register set.
if (reg_index >= reg_context.GetUserRegisterCount()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, requested "
"register %" PRIu32 " beyond register count %" PRIu32,
__FUNCTION__, reg_index, reg_context.GetUserRegisterCount());
return SendErrorResponse(0x47);
}
// The dwarf expression are evaluate on host site which may cause register
// size to change Hence the reg_size may not be same as reg_info->bytes_size
if ((reg_size != reg_info->byte_size) &&
!(reg_info->dynamic_size_dwarf_expr_bytes)) {
return SendIllFormedResponse(packet, "P packet register size is incorrect");
}
// Build the reginfos response.
StreamGDBRemote response;
RegisterValue reg_value(
reg_bytes, reg_size,
m_debugged_process_up->GetArchitecture().GetByteOrder());
Status error = reg_context.WriteRegister(reg_info, reg_value);
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, write of "
"requested register %" PRIu32 " (%s) failed: %s",
__FUNCTION__, reg_index, reg_info->name, error.AsCString());
return SendErrorResponse(0x32);
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_H(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
// Parse out which variant of $H is requested.
packet.SetFilePos(strlen("H"));
if (packet.GetBytesLeft() < 1) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, H command "
"missing {g,c} variant",
__FUNCTION__);
return SendIllFormedResponse(packet, "H command missing {g,c} variant");
}
const char h_variant = packet.GetChar();
switch (h_variant) {
case 'g':
break;
case 'c':
break;
default:
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, invalid $H variant %c",
__FUNCTION__, h_variant);
return SendIllFormedResponse(packet,
"H variant unsupported, should be c or g");
}
// Parse out the thread number.
// FIXME return a parse success/fail value. All values are valid here.
const lldb::tid_t tid =
packet.GetHexMaxU64(false, std::numeric_limits<lldb::tid_t>::max());
// Ensure we have the given thread when not specifying -1 (all threads) or 0
// (any thread).
if (tid != LLDB_INVALID_THREAD_ID && tid != 0) {
NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
if (!thread) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, tid %" PRIu64
" not found",
__FUNCTION__, tid);
return SendErrorResponse(0x15);
}
}
// Now switch the given thread type.
switch (h_variant) {
case 'g':
SetCurrentThreadID(tid);
break;
case 'c':
SetContinueThreadID(tid);
break;
default:
assert(false && "unsupported $H variant - shouldn't get here");
return SendIllFormedResponse(packet,
"H variant unsupported, should be c or g");
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_I(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
packet.SetFilePos(::strlen("I"));
uint8_t tmp[4096];
for (;;) {
size_t read = packet.GetHexBytesAvail(tmp);
if (read == 0) {
break;
}
// write directly to stdin *this might block if stdin buffer is full*
// TODO: enqueue this block in circular buffer and send window size to
// remote host
ConnectionStatus status;
Status error;
m_stdio_communication.Write(tmp, read, status, &error);
if (error.Fail()) {
return SendErrorResponse(0x15);
}
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_interrupt(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOG(log, "failed, no process available");
return SendErrorResponse(0x15);
}
// Interrupt the process.
Status error = m_debugged_process_up->Interrupt();
if (error.Fail()) {
LLDB_LOG(log, "failed for process {0}: {1}", m_debugged_process_up->GetID(),
error);
return SendErrorResponse(GDBRemoteServerError::eErrorResume);
}
LLDB_LOG(log, "stopped process {0}", m_debugged_process_up->GetID());
// No response required from stop all.
return PacketResult::Success;
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_memory_read(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
// Parse out the memory address.
packet.SetFilePos(strlen("m"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Too short m packet");
// Read the address. Punting on validation.
// FIXME replace with Hex U64 read with no default value that fails on failed
// read.
const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
// Validate comma.
if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
return SendIllFormedResponse(packet, "Comma sep missing in m packet");
// Get # bytes to read.
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Length missing in m packet");
const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
if (byte_count == 0) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s nothing to read: "
"zero-length packet",
__FUNCTION__);
return SendOKResponse();
}
// Allocate the response buffer.
std::string buf(byte_count, '\0');
if (buf.empty())
return SendErrorResponse(0x78);
// Retrieve the process memory.
size_t bytes_read = 0;
Status error = m_debugged_process_up->ReadMemoryWithoutTrap(
read_addr, &buf[0], byte_count, bytes_read);
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
" mem 0x%" PRIx64 ": failed to read. Error: %s",
__FUNCTION__, m_debugged_process_up->GetID(), read_addr,
error.AsCString());
return SendErrorResponse(0x08);
}
if (bytes_read == 0) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
" mem 0x%" PRIx64 ": read 0 of %" PRIu64 " requested bytes",
__FUNCTION__, m_debugged_process_up->GetID(), read_addr,
byte_count);
return SendErrorResponse(0x08);
}
StreamGDBRemote response;
packet.SetFilePos(0);
char kind = packet.GetChar('?');
if (kind == 'x')
response.PutEscapedBytes(buf.data(), byte_count);
else {
assert(kind == 'm');
for (size_t i = 0; i < bytes_read; ++i)
response.PutHex8(buf[i]);
}
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_M(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
// Parse out the memory address.
packet.SetFilePos(strlen("M"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Too short M packet");
// Read the address. Punting on validation.
// FIXME replace with Hex U64 read with no default value that fails on failed
// read.
const lldb::addr_t write_addr = packet.GetHexMaxU64(false, 0);
// Validate comma.
if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ','))
return SendIllFormedResponse(packet, "Comma sep missing in M packet");
// Get # bytes to read.
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Length missing in M packet");
const uint64_t byte_count = packet.GetHexMaxU64(false, 0);
if (byte_count == 0) {
LLDB_LOG(log, "nothing to write: zero-length packet");
return PacketResult::Success;
}
// Validate colon.
if ((packet.GetBytesLeft() < 1) || (packet.GetChar() != ':'))
return SendIllFormedResponse(
packet, "Comma sep missing in M packet after byte length");
// Allocate the conversion buffer.
std::vector<uint8_t> buf(byte_count, 0);
if (buf.empty())
return SendErrorResponse(0x78);
// Convert the hex memory write contents to bytes.
StreamGDBRemote response;
const uint64_t convert_count = packet.GetHexBytes(buf, 0);
if (convert_count != byte_count) {
LLDB_LOG(log,
"pid {0} mem {1:x}: asked to write {2} bytes, but only found {3} "
"to convert.",
m_debugged_process_up->GetID(), write_addr, byte_count,
convert_count);
return SendIllFormedResponse(packet, "M content byte length specified did "
"not match hex-encoded content "
"length");
}
// Write the process memory.
size_t bytes_written = 0;
Status error = m_debugged_process_up->WriteMemory(write_addr, &buf[0],
byte_count, bytes_written);
if (error.Fail()) {
LLDB_LOG(log, "pid {0} mem {1:x}: failed to write. Error: {2}",
m_debugged_process_up->GetID(), write_addr, error);
return SendErrorResponse(0x09);
}
if (bytes_written == 0) {
LLDB_LOG(log, "pid {0} mem {1:x}: wrote 0 of {2} requested bytes",
m_debugged_process_up->GetID(), write_addr, byte_count);
return SendErrorResponse(0x09);
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfoSupported(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// Currently only the NativeProcessProtocol knows if it can handle a
// qMemoryRegionInfoSupported request, but we're not guaranteed to be
// attached to a process. For now we'll assume the client only asks this
// when a process is being debugged.
// Ensure we have a process running; otherwise, we can't figure this out
// since we won't have a NativeProcessProtocol.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
// Test if we can get any region back when asking for the region around NULL.
MemoryRegionInfo region_info;
const Status error =
m_debugged_process_up->GetMemoryRegionInfo(0, region_info);
if (error.Fail()) {
// We don't support memory region info collection for this
// NativeProcessProtocol.
return SendUnimplementedResponse("");
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qMemoryRegionInfo(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// Ensure we have a process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
// Parse out the memory address.
packet.SetFilePos(strlen("qMemoryRegionInfo:"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Too short qMemoryRegionInfo: packet");
// Read the address. Punting on validation.
const lldb::addr_t read_addr = packet.GetHexMaxU64(false, 0);
StreamGDBRemote response;
// Get the memory region info for the target address.
MemoryRegionInfo region_info;
const Status error =
m_debugged_process_up->GetMemoryRegionInfo(read_addr, region_info);
if (error.Fail()) {
// Return the error message.
response.PutCString("error:");
response.PutStringAsRawHex8(error.AsCString());
response.PutChar(';');
} else {
// Range start and size.
response.Printf("start:%" PRIx64 ";size:%" PRIx64 ";",
region_info.GetRange().GetRangeBase(),
region_info.GetRange().GetByteSize());
// Permissions.
if (region_info.GetReadable() || region_info.GetWritable() ||
region_info.GetExecutable()) {
// Write permissions info.
response.PutCString("permissions:");
if (region_info.GetReadable())
response.PutChar('r');
if (region_info.GetWritable())
response.PutChar('w');
if (region_info.GetExecutable())
response.PutChar('x');
response.PutChar(';');
}
// Name
ConstString name = region_info.GetName();
if (name) {
response.PutCString("name:");
response.PutStringAsRawHex8(name.AsCString());
response.PutChar(';');
}
}
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_Z(StringExtractorGDBRemote &packet) {
// Ensure we have a process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOG(log, "failed, no process available");
return SendErrorResponse(0x15);
}
// Parse out software or hardware breakpoint or watchpoint requested.
packet.SetFilePos(strlen("Z"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(
packet, "Too short Z packet, missing software/hardware specifier");
bool want_breakpoint = true;
bool want_hardware = false;
uint32_t watch_flags = 0;
const GDBStoppointType stoppoint_type =
GDBStoppointType(packet.GetS32(eStoppointInvalid));
switch (stoppoint_type) {
case eBreakpointSoftware:
want_hardware = false;
want_breakpoint = true;
break;
case eBreakpointHardware:
want_hardware = true;
want_breakpoint = true;
break;
case eWatchpointWrite:
watch_flags = 1;
want_hardware = true;
want_breakpoint = false;
break;
case eWatchpointRead:
watch_flags = 2;
want_hardware = true;
want_breakpoint = false;
break;
case eWatchpointReadWrite:
watch_flags = 3;
want_hardware = true;
want_breakpoint = false;
break;
case eStoppointInvalid:
return SendIllFormedResponse(
packet, "Z packet had invalid software/hardware specifier");
}
if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
return SendIllFormedResponse(
packet, "Malformed Z packet, expecting comma after stoppoint type");
// Parse out the stoppoint address.
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Too short Z packet, missing address");
const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
return SendIllFormedResponse(
packet, "Malformed Z packet, expecting comma after address");
// Parse out the stoppoint size (i.e. size hint for opcode size).
const uint32_t size =
packet.GetHexMaxU32(false, std::numeric_limits<uint32_t>::max());
if (size == std::numeric_limits<uint32_t>::max())
return SendIllFormedResponse(
packet, "Malformed Z packet, failed to parse size argument");
if (want_breakpoint) {
// Try to set the breakpoint.
const Status error =
m_debugged_process_up->SetBreakpoint(addr, size, want_hardware);
if (error.Success())
return SendOKResponse();
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
LLDB_LOG(log, "pid {0} failed to set breakpoint: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x09);
} else {
// Try to set the watchpoint.
const Status error = m_debugged_process_up->SetWatchpoint(
addr, size, watch_flags, want_hardware);
if (error.Success())
return SendOKResponse();
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
LLDB_LOG(log, "pid {0} failed to set watchpoint: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x09);
}
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_z(StringExtractorGDBRemote &packet) {
// Ensure we have a process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOG(log, "failed, no process available");
return SendErrorResponse(0x15);
}
// Parse out software or hardware breakpoint or watchpoint requested.
packet.SetFilePos(strlen("z"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(
packet, "Too short z packet, missing software/hardware specifier");
bool want_breakpoint = true;
bool want_hardware = false;
const GDBStoppointType stoppoint_type =
GDBStoppointType(packet.GetS32(eStoppointInvalid));
switch (stoppoint_type) {
case eBreakpointHardware:
want_breakpoint = true;
want_hardware = true;
break;
case eBreakpointSoftware:
want_breakpoint = true;
break;
case eWatchpointWrite:
want_breakpoint = false;
break;
case eWatchpointRead:
want_breakpoint = false;
break;
case eWatchpointReadWrite:
want_breakpoint = false;
break;
default:
return SendIllFormedResponse(
packet, "z packet had invalid software/hardware specifier");
}
if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
return SendIllFormedResponse(
packet, "Malformed z packet, expecting comma after stoppoint type");
// Parse out the stoppoint address.
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(packet, "Too short z packet, missing address");
const lldb::addr_t addr = packet.GetHexMaxU64(false, 0);
if ((packet.GetBytesLeft() < 1) || packet.GetChar() != ',')
return SendIllFormedResponse(
packet, "Malformed z packet, expecting comma after address");
/*
// Parse out the stoppoint size (i.e. size hint for opcode size).
const uint32_t size = packet.GetHexMaxU32 (false,
std::numeric_limits<uint32_t>::max ());
if (size == std::numeric_limits<uint32_t>::max ())
return SendIllFormedResponse(packet, "Malformed z packet, failed to parse
size argument");
*/
if (want_breakpoint) {
// Try to clear the breakpoint.
const Status error =
m_debugged_process_up->RemoveBreakpoint(addr, want_hardware);
if (error.Success())
return SendOKResponse();
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
LLDB_LOG(log, "pid {0} failed to remove breakpoint: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x09);
} else {
// Try to clear the watchpoint.
const Status error = m_debugged_process_up->RemoveWatchpoint(addr);
if (error.Success())
return SendOKResponse();
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
LLDB_LOG(log, "pid {0} failed to remove watchpoint: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x09);
}
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_s(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
// Ensure we have a process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x32);
}
// We first try to use a continue thread id. If any one or any all set, use
// the current thread. Bail out if we don't have a thread id.
lldb::tid_t tid = GetContinueThreadID();
if (tid == 0 || tid == LLDB_INVALID_THREAD_ID)
tid = GetCurrentThreadID();
if (tid == LLDB_INVALID_THREAD_ID)
return SendErrorResponse(0x33);
// Double check that we have such a thread.
// TODO investigate: on MacOSX we might need to do an UpdateThreads () here.
NativeThreadProtocol *thread = m_debugged_process_up->GetThreadByID(tid);
if (!thread)
return SendErrorResponse(0x33);
// Create the step action for the given thread.
ResumeAction action = {tid, eStateStepping, LLDB_INVALID_SIGNAL_NUMBER};
// Setup the actions list.
ResumeActionList actions;
actions.Append(action);
// All other threads stop while we're single stepping a thread.
actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
Status error = m_debugged_process_up->Resume(actions);
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s pid %" PRIu64
" tid %" PRIu64 " Resume() failed with error: %s",
__FUNCTION__, m_debugged_process_up->GetID(), tid,
error.AsCString());
return SendErrorResponse(0x49);
}
// No response here - the stop or exit will come from the resulting action.
return PacketResult::Success;
}
llvm::Expected<std::unique_ptr<llvm::MemoryBuffer>>
GDBRemoteCommunicationServerLLGS::ReadXferObject(llvm::StringRef object,
llvm::StringRef annex) {
if (object == "auxv") {
// Make sure we have a valid process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
return llvm::createStringError(llvm::inconvertibleErrorCode(),
"No process available");
}
// Grab the auxv data.
auto buffer_or_error = m_debugged_process_up->GetAuxvData();
if (!buffer_or_error)
return llvm::errorCodeToError(buffer_or_error.getError());
return std::move(*buffer_or_error);
}
if (object == "libraries-svr4") {
auto library_list = m_debugged_process_up->GetLoadedSVR4Libraries();
if (!library_list)
return library_list.takeError();
StreamString response;
response.Printf("<library-list-svr4 version=\"1.0\">");
for (auto const &library : *library_list) {
response.Printf("<library name=\"%s\" ",
XMLEncodeAttributeValue(library.name.c_str()).c_str());
response.Printf("lm=\"0x%" PRIx64 "\" ", library.link_map);
response.Printf("l_addr=\"0x%" PRIx64 "\" ", library.base_addr);
response.Printf("l_ld=\"0x%" PRIx64 "\" />", library.ld_addr);
}
response.Printf("</library-list-svr4>");
return MemoryBuffer::getMemBufferCopy(response.GetString(), __FUNCTION__);
}
return llvm::make_error<PacketUnimplementedError>(
"Xfer object not supported");
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qXfer(
StringExtractorGDBRemote &packet) {
SmallVector<StringRef, 5> fields;
// The packet format is "qXfer:<object>:<action>:<annex>:offset,length"
StringRef(packet.GetStringRef()).split(fields, ':', 4);
if (fields.size() != 5)
return SendIllFormedResponse(packet, "malformed qXfer packet");
StringRef &xfer_object = fields[1];
StringRef &xfer_action = fields[2];
StringRef &xfer_annex = fields[3];
StringExtractor offset_data(fields[4]);
if (xfer_action != "read")
return SendUnimplementedResponse("qXfer action not supported");
// Parse offset.
const uint64_t xfer_offset =
offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
if (xfer_offset == std::numeric_limits<uint64_t>::max())
return SendIllFormedResponse(packet, "qXfer packet missing offset");
// Parse out comma.
if (offset_data.GetChar() != ',')
return SendIllFormedResponse(packet,
"qXfer packet missing comma after offset");
// Parse out the length.
const uint64_t xfer_length =
offset_data.GetHexMaxU64(false, std::numeric_limits<uint64_t>::max());
if (xfer_length == std::numeric_limits<uint64_t>::max())
return SendIllFormedResponse(packet, "qXfer packet missing length");
// Get a previously constructed buffer if it exists or create it now.
std::string buffer_key = (xfer_object + xfer_action + xfer_annex).str();
auto buffer_it = m_xfer_buffer_map.find(buffer_key);
if (buffer_it == m_xfer_buffer_map.end()) {
auto buffer_up = ReadXferObject(xfer_object, xfer_annex);
if (!buffer_up)
return SendErrorResponse(buffer_up.takeError());
buffer_it = m_xfer_buffer_map
.insert(std::make_pair(buffer_key, std::move(*buffer_up)))
.first;
}
// Send back the response
StreamGDBRemote response;
bool done_with_buffer = false;
llvm::StringRef buffer = buffer_it->second->getBuffer();
if (xfer_offset >= buffer.size()) {
// We have nothing left to send. Mark the buffer as complete.
response.PutChar('l');
done_with_buffer = true;
} else {
// Figure out how many bytes are available starting at the given offset.
buffer = buffer.drop_front(xfer_offset);
// Mark the response type according to whether we're reading the remainder
// of the data.
if (xfer_length >= buffer.size()) {
// There will be nothing left to read after this
response.PutChar('l');
done_with_buffer = true;
} else {
// There will still be bytes to read after this request.
response.PutChar('m');
buffer = buffer.take_front(xfer_length);
}
// Now write the data in encoded binary form.
response.PutEscapedBytes(buffer.data(), buffer.size());
}
if (done_with_buffer)
m_xfer_buffer_map.erase(buffer_it);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_QSaveRegisterState(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Move past packet name.
packet.SetFilePos(strlen("QSaveRegisterState"));
// Get the thread to use.
NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
if (!thread) {
if (m_thread_suffix_supported)
return SendIllFormedResponse(
packet, "No thread specified in QSaveRegisterState packet");
else
return SendIllFormedResponse(packet,
"No thread was is set with the Hg packet");
}
// Grab the register context for the thread.
NativeRegisterContext& reg_context = thread->GetRegisterContext();
// Save registers to a buffer.
DataBufferSP register_data_sp;
Status error = reg_context.ReadAllRegisterValues(register_data_sp);
if (error.Fail()) {
LLDB_LOG(log, "pid {0} failed to save all register values: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x75);
}
// Allocate a new save id.
const uint32_t save_id = GetNextSavedRegistersID();
assert((m_saved_registers_map.find(save_id) == m_saved_registers_map.end()) &&
"GetNextRegisterSaveID() returned an existing register save id");
// Save the register data buffer under the save id.
{
std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
m_saved_registers_map[save_id] = register_data_sp;
}
// Write the response.
StreamGDBRemote response;
response.Printf("%" PRIu32, save_id);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_QRestoreRegisterState(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Parse out save id.
packet.SetFilePos(strlen("QRestoreRegisterState:"));
if (packet.GetBytesLeft() < 1)
return SendIllFormedResponse(
packet, "QRestoreRegisterState packet missing register save id");
const uint32_t save_id = packet.GetU32(0);
if (save_id == 0) {
LLDB_LOG(log, "QRestoreRegisterState packet has malformed save id, "
"expecting decimal uint32_t");
return SendErrorResponse(0x76);
}
// Get the thread to use.
NativeThreadProtocol *thread = GetThreadFromSuffix(packet);
if (!thread) {
if (m_thread_suffix_supported)
return SendIllFormedResponse(
packet, "No thread specified in QRestoreRegisterState packet");
else
return SendIllFormedResponse(packet,
"No thread was is set with the Hg packet");
}
// Grab the register context for the thread.
NativeRegisterContext ®_context = thread->GetRegisterContext();
// Retrieve register state buffer, then remove from the list.
DataBufferSP register_data_sp;
{
std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
// Find the register set buffer for the given save id.
auto it = m_saved_registers_map.find(save_id);
if (it == m_saved_registers_map.end()) {
LLDB_LOG(log,
"pid {0} does not have a register set save buffer for id {1}",
m_debugged_process_up->GetID(), save_id);
return SendErrorResponse(0x77);
}
register_data_sp = it->second;
// Remove it from the map.
m_saved_registers_map.erase(it);
}
Status error = reg_context.WriteAllRegisterValues(register_data_sp);
if (error.Fail()) {
LLDB_LOG(log, "pid {0} failed to restore all register values: {1}",
m_debugged_process_up->GetID(), error);
return SendErrorResponse(0x77);
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_vAttach(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// Consume the ';' after vAttach.
packet.SetFilePos(strlen("vAttach"));
if (!packet.GetBytesLeft() || packet.GetChar() != ';')
return SendIllFormedResponse(packet, "vAttach missing expected ';'");
// Grab the PID to which we will attach (assume hex encoding).
lldb::pid_t pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
if (pid == LLDB_INVALID_PROCESS_ID)
return SendIllFormedResponse(packet,
"vAttach failed to parse the process id");
// Attempt to attach.
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s attempting to attach to "
"pid %" PRIu64,
__FUNCTION__, pid);
Status error = AttachToProcess(pid);
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to attach to "
"pid %" PRIu64 ": %s\n",
__FUNCTION__, pid, error.AsCString());
return SendErrorResponse(error);
}
// Notify we attached by sending a stop packet.
return SendStopReasonForState(m_debugged_process_up->GetState());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_D(StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
StopSTDIOForwarding();
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)) {
LLDB_LOGF(
log,
"GDBRemoteCommunicationServerLLGS::%s failed, no process available",
__FUNCTION__);
return SendErrorResponse(0x15);
}
lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
// Consume the ';' after D.
packet.SetFilePos(1);
if (packet.GetBytesLeft()) {
if (packet.GetChar() != ';')
return SendIllFormedResponse(packet, "D missing expected ';'");
// Grab the PID from which we will detach (assume hex encoding).
pid = packet.GetU32(LLDB_INVALID_PROCESS_ID, 16);
if (pid == LLDB_INVALID_PROCESS_ID)
return SendIllFormedResponse(packet, "D failed to parse the process id");
}
if (pid != LLDB_INVALID_PROCESS_ID && m_debugged_process_up->GetID() != pid) {
return SendIllFormedResponse(packet, "Invalid pid");
}
const Status error = m_debugged_process_up->Detach();
if (error.Fail()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed to detach from "
"pid %" PRIu64 ": %s\n",
__FUNCTION__, m_debugged_process_up->GetID(), error.AsCString());
return SendErrorResponse(0x01);
}
return SendOKResponse();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qThreadStopInfo(
StringExtractorGDBRemote &packet) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
packet.SetFilePos(strlen("qThreadStopInfo"));
const lldb::tid_t tid = packet.GetHexMaxU32(false, LLDB_INVALID_THREAD_ID);
if (tid == LLDB_INVALID_THREAD_ID) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s failed, could not "
"parse thread id from request \"%s\"",
__FUNCTION__, packet.GetStringRef().data());
return SendErrorResponse(0x15);
}
return SendStopReplyPacketForThread(tid);
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_jThreadsInfo(
StringExtractorGDBRemote &) {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_THREAD));
// Ensure we have a debugged process.
if (!m_debugged_process_up ||
(m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID))
return SendErrorResponse(50);
LLDB_LOG(log, "preparing packet for pid {0}", m_debugged_process_up->GetID());
StreamString response;
const bool threads_with_valid_stop_info_only = false;
llvm::Expected<json::Value> threads_info = GetJSONThreadsInfo(
*m_debugged_process_up, threads_with_valid_stop_info_only);
if (!threads_info) {
LLDB_LOG(log, "failed to prepare a packet for pid {0}: {1}",
m_debugged_process_up->GetID(),
llvm::toString(threads_info.takeError()));
return SendErrorResponse(52);
}
response.AsRawOstream() << *threads_info;
StreamGDBRemote escaped_response;
escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
return SendPacketNoLock(escaped_response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qWatchpointSupportInfo(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
return SendErrorResponse(68);
packet.SetFilePos(strlen("qWatchpointSupportInfo"));
if (packet.GetBytesLeft() == 0)
return SendOKResponse();
if (packet.GetChar() != ':')
return SendErrorResponse(67);
auto hw_debug_cap = m_debugged_process_up->GetHardwareDebugSupportInfo();
StreamGDBRemote response;
if (hw_debug_cap == llvm::None)
response.Printf("num:0;");
else
response.Printf("num:%d;", hw_debug_cap->second);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_qFileLoadAddress(
StringExtractorGDBRemote &packet) {
// Fail if we don't have a current process.
if (!m_debugged_process_up ||
m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
return SendErrorResponse(67);
packet.SetFilePos(strlen("qFileLoadAddress:"));
if (packet.GetBytesLeft() == 0)
return SendErrorResponse(68);
std::string file_name;
packet.GetHexByteString(file_name);
lldb::addr_t file_load_address = LLDB_INVALID_ADDRESS;
Status error =
m_debugged_process_up->GetFileLoadAddress(file_name, file_load_address);
if (error.Fail())
return SendErrorResponse(69);
if (file_load_address == LLDB_INVALID_ADDRESS)
return SendErrorResponse(1); // File not loaded
StreamGDBRemote response;
response.PutHex64(file_load_address);
return SendPacketNoLock(response.GetString());
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationServerLLGS::Handle_QPassSignals(
StringExtractorGDBRemote &packet) {
std::vector<int> signals;
packet.SetFilePos(strlen("QPassSignals:"));
// Read sequence of hex signal numbers divided by a semicolon and optionally
// spaces.
while (packet.GetBytesLeft() > 0) {
int signal = packet.GetS32(-1, 16);
if (signal < 0)
return SendIllFormedResponse(packet, "Failed to parse signal number.");
signals.push_back(signal);
packet.SkipSpaces();
char separator = packet.GetChar();
if (separator == '\0')
break; // End of string
if (separator != ';')
return SendIllFormedResponse(packet, "Invalid separator,"
" expected semicolon.");
}
// Fail if we don't have a current process.
if (!m_debugged_process_up)
return SendErrorResponse(68);
Status error = m_debugged_process_up->IgnoreSignals(signals);
if (error.Fail())
return SendErrorResponse(69);
return SendOKResponse();
}
void GDBRemoteCommunicationServerLLGS::MaybeCloseInferiorTerminalConnection() {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
// Tell the stdio connection to shut down.
if (m_stdio_communication.IsConnected()) {
auto connection = m_stdio_communication.GetConnection();
if (connection) {
Status error;
connection->Disconnect(&error);
if (error.Success()) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s disconnect process "
"terminal stdio - SUCCESS",
__FUNCTION__);
} else {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s disconnect process "
"terminal stdio - FAIL: %s",
__FUNCTION__, error.AsCString());
}
}
}
}
NativeThreadProtocol *GDBRemoteCommunicationServerLLGS::GetThreadFromSuffix(
StringExtractorGDBRemote &packet) {
// We have no thread if we don't have a process.
if (!m_debugged_process_up ||
m_debugged_process_up->GetID() == LLDB_INVALID_PROCESS_ID)
return nullptr;
// If the client hasn't asked for thread suffix support, there will not be a
// thread suffix. Use the current thread in that case.
if (!m_thread_suffix_supported) {
const lldb::tid_t current_tid = GetCurrentThreadID();
if (current_tid == LLDB_INVALID_THREAD_ID)
return nullptr;
else if (current_tid == 0) {
// Pick a thread.
return m_debugged_process_up->GetThreadAtIndex(0);
} else
return m_debugged_process_up->GetThreadByID(current_tid);
}
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_THREAD));
// Parse out the ';'.
if (packet.GetBytesLeft() < 1 || packet.GetChar() != ';') {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
"error: expected ';' prior to start of thread suffix: packet "
"contents = '%s'",
__FUNCTION__, packet.GetStringRef().data());
return nullptr;
}
if (!packet.GetBytesLeft())
return nullptr;
// Parse out thread: portion.
if (strncmp(packet.Peek(), "thread:", strlen("thread:")) != 0) {
LLDB_LOGF(log,
"GDBRemoteCommunicationServerLLGS::%s gdb-remote parse "
"error: expected 'thread:' but not found, packet contents = "
"'%s'",
__FUNCTION__, packet.GetStringRef().data());
return nullptr;
}
packet.SetFilePos(packet.GetFilePos() + strlen("thread:"));
const lldb::tid_t tid = packet.GetHexMaxU64(false, 0);
if (tid != 0)
return m_debugged_process_up->GetThreadByID(tid);
return nullptr;
}
lldb::tid_t GDBRemoteCommunicationServerLLGS::GetCurrentThreadID() const {
if (m_current_tid == 0 || m_current_tid == LLDB_INVALID_THREAD_ID) {
// Use whatever the debug process says is the current thread id since the
// protocol either didn't specify or specified we want any/all threads
// marked as the current thread.
if (!m_debugged_process_up)
return LLDB_INVALID_THREAD_ID;
return m_debugged_process_up->GetCurrentThreadID();
}
// Use the specific current thread id set by the gdb remote protocol.
return m_current_tid;
}
uint32_t GDBRemoteCommunicationServerLLGS::GetNextSavedRegistersID() {
std::lock_guard<std::mutex> guard(m_saved_registers_mutex);
return m_next_saved_registers_id++;
}
void GDBRemoteCommunicationServerLLGS::ClearProcessSpecificData() {
Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
LLDB_LOG(log, "clearing {0} xfer buffers", m_xfer_buffer_map.size());
m_xfer_buffer_map.clear();
}
FileSpec
GDBRemoteCommunicationServerLLGS::FindModuleFile(const std::string &module_path,
const ArchSpec &arch) {
if (m_debugged_process_up) {
FileSpec file_spec;
if (m_debugged_process_up
->GetLoadedModuleFileSpec(module_path.c_str(), file_spec)
.Success()) {
if (FileSystem::Instance().Exists(file_spec))
return file_spec;
}
}
return GDBRemoteCommunicationServerCommon::FindModuleFile(module_path, arch);
}
std::string GDBRemoteCommunicationServerLLGS::XMLEncodeAttributeValue(
llvm::StringRef value) {
std::string result;
for (const char &c : value) {
switch (c) {
case '\'':
result += "'";
break;
case '"':
result += """;
break;
case '<':
result += "<";
break;
case '>':
result += ">";
break;
default:
result += c;
break;
}
}
return result;
}
|