RNBRemote.cpp 216 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313
//===-- RNBRemote.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
//
//===----------------------------------------------------------------------===//
//
//  Created by Greg Clayton on 12/12/07.
//
//===----------------------------------------------------------------------===//

#include "RNBRemote.h"

#include <errno.h>
#include <mach-o/loader.h>
#include <mach/exception_types.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <unistd.h>

#if defined(__APPLE__)
#include <pthread.h>
#include <sched.h>
#endif

#include "DNB.h"
#include "DNBDataRef.h"
#include "DNBLog.h"
#include "DNBThreadResumeActions.h"
#include "DarwinLogCollector.h"
#include "DarwinLogEvent.h"
#include "JSON.h"
#include "JSONGenerator.h"
#include "JSONGenerator.h"
#include "MacOSX/Genealogy.h"
#include "OsLogger.h"
#include "RNBContext.h"
#include "RNBServices.h"
#include "RNBSocket.h"
#include "StdStringExtractor.h"

#include <compression.h>

#include <TargetConditionals.h>
#include <iomanip>
#include <memory>
#include <sstream>
#include <unordered_set>

// constants

static const std::string OS_LOG_EVENTS_KEY_NAME("events");
static const std::string JSON_ASYNC_TYPE_KEY_NAME("type");
static const DarwinLogEventVector::size_type DARWIN_LOG_MAX_EVENTS_PER_PACKET =
    10;

// std::iostream formatting macros
#define RAW_HEXBASE std::setfill('0') << std::hex << std::right
#define HEXBASE '0' << 'x' << RAW_HEXBASE
#define RAWHEX8(x) RAW_HEXBASE << std::setw(2) << ((uint32_t)((uint8_t)x))
#define RAWHEX16 RAW_HEXBASE << std::setw(4)
#define RAWHEX32 RAW_HEXBASE << std::setw(8)
#define RAWHEX64 RAW_HEXBASE << std::setw(16)
#define HEX8(x) HEXBASE << std::setw(2) << ((uint32_t)(x))
#define HEX16 HEXBASE << std::setw(4)
#define HEX32 HEXBASE << std::setw(8)
#define HEX64 HEXBASE << std::setw(16)
#define RAW_HEX(x) RAW_HEXBASE << std::setw(sizeof(x) * 2) << (x)
#define HEX(x) HEXBASE << std::setw(sizeof(x) * 2) << (x)
#define RAWHEX_SIZE(x, sz) RAW_HEXBASE << std::setw((sz)) << (x)
#define HEX_SIZE(x, sz) HEXBASE << std::setw((sz)) << (x)
#define STRING_WIDTH(w) std::setfill(' ') << std::setw(w)
#define LEFT_STRING_WIDTH(s, w)                                                \
  std::left << std::setfill(' ') << std::setw(w) << (s) << std::right
#define DECIMAL std::dec << std::setfill(' ')
#define DECIMAL_WIDTH(w) DECIMAL << std::setw(w)
#define FLOAT(n, d)                                                            \
  std::setfill(' ') << std::setw((n) + (d) + 1) << std::setprecision(d)        \
                    << std::showpoint << std::fixed
#define INDENT_WITH_SPACES(iword_idx)                                          \
  std::setfill(' ') << std::setw((iword_idx)) << ""
#define INDENT_WITH_TABS(iword_idx)                                            \
  std::setfill('\t') << std::setw((iword_idx)) << ""
// Class to handle communications via gdb remote protocol.

// Prototypes

static std::string binary_encode_string(const std::string &s);

// Decode a single hex character and return the hex value as a number or
// -1 if "ch" is not a hex character.
static inline int xdigit_to_sint(char ch) {
  if (ch >= 'a' && ch <= 'f')
    return 10 + ch - 'a';
  if (ch >= 'A' && ch <= 'F')
    return 10 + ch - 'A';
  if (ch >= '0' && ch <= '9')
    return ch - '0';
  return -1;
}

// Decode a single hex ASCII byte. Return -1 on failure, a value 0-255
// on success.
static inline int decoded_hex_ascii_char(const char *p) {
  const int hi_nibble = xdigit_to_sint(p[0]);
  if (hi_nibble == -1)
    return -1;
  const int lo_nibble = xdigit_to_sint(p[1]);
  if (lo_nibble == -1)
    return -1;
  return (uint8_t)((hi_nibble << 4) + lo_nibble);
}

// Decode a hex ASCII string back into a string
static std::string decode_hex_ascii_string(const char *p,
                                           uint32_t max_length = UINT32_MAX) {
  std::string arg;
  if (p) {
    for (const char *c = p; ((c - p) / 2) < max_length; c += 2) {
      int ch = decoded_hex_ascii_char(c);
      if (ch == -1)
        break;
      else
        arg.push_back(ch);
    }
  }
  return arg;
}

uint64_t decode_uint64(const char *p, int base, char **end = nullptr,
                       uint64_t fail_value = 0) {
  nub_addr_t addr = strtoull(p, end, 16);
  if (addr == 0 && errno != 0)
    return fail_value;
  return addr;
}

extern void ASLLogCallback(void *baton, uint32_t flags, const char *format,
                           va_list args);

#if defined(__APPLE__) &&                                                      \
    (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101000)
// from System.framework/Versions/B/PrivateHeaders/sys/codesign.h
extern "C" {
#define CS_OPS_STATUS 0       /* return status */
#define CS_RESTRICT 0x0000800 /* tell dyld to treat restricted */
int csops(pid_t pid, unsigned int ops, void *useraddr, size_t usersize);

// from rootless.h
bool rootless_allows_task_for_pid(pid_t pid);

// from sys/csr.h
typedef uint32_t csr_config_t;
#define CSR_ALLOW_TASK_FOR_PID (1 << 2)
int csr_check(csr_config_t mask);
}
#endif

RNBRemote::RNBRemote()
    : m_ctx(), m_comm(), m_arch(), m_continue_thread(-1), m_thread(-1),
      m_mutex(), m_dispatch_queue_offsets(),
      m_dispatch_queue_offsets_addr(INVALID_NUB_ADDRESS),
      m_qSymbol_index(UINT32_MAX), m_packets_recvd(0), m_packets(),
      m_rx_packets(), m_rx_partial_data(), m_rx_pthread(0),
      m_max_payload_size(DEFAULT_GDB_REMOTE_PROTOCOL_BUFSIZE - 4),
      m_extended_mode(false), m_noack_mode(false),
      m_thread_suffix_supported(false), m_list_threads_in_stop_reply(false),
      m_compression_minsize(384), m_enable_compression_next_send_packet(false),
      m_compression_mode(compression_types::none) {
  DNBLogThreadedIf(LOG_RNB_REMOTE, "%s", __PRETTY_FUNCTION__);
  CreatePacketTable();
}

RNBRemote::~RNBRemote() {
  DNBLogThreadedIf(LOG_RNB_REMOTE, "%s", __PRETTY_FUNCTION__);
  StopReadRemoteDataThread();
}

void RNBRemote::CreatePacketTable() {
  // Step required to add new packets:
  // 1 - Add new enumeration to RNBRemote::PacketEnum
  // 2 - Create the RNBRemote::HandlePacket_ function if a new function is
  // needed
  // 3 - Register the Packet definition with any needed callbacks in this
  // function
  //          - If no response is needed for a command, then use NULL for the
  //          normal callback
  //          - If the packet is not supported while the target is running, use
  //          NULL for the async callback
  // 4 - If the packet is a standard packet (starts with a '$' character
  //      followed by the payload and then '#' and checksum, then you are done
  //      else go on to step 5
  // 5 - if the packet is a fixed length packet:
  //      - modify the switch statement for the first character in the payload
  //        in RNBRemote::CommDataReceived so it doesn't reject the new packet
  //        type as invalid
  //      - modify the switch statement for the first character in the payload
  //        in RNBRemote::GetPacketPayload and make sure the payload of the
  //        packet
  //        is returned correctly

  std::vector<Packet> &t = m_packets;
  t.push_back(Packet(ack, NULL, NULL, "+", "ACK"));
  t.push_back(Packet(nack, NULL, NULL, "-", "!ACK"));
  t.push_back(Packet(read_memory, &RNBRemote::HandlePacket_m, NULL, "m",
                     "Read memory"));
  t.push_back(Packet(read_register, &RNBRemote::HandlePacket_p, NULL, "p",
                     "Read one register"));
  t.push_back(Packet(read_general_regs, &RNBRemote::HandlePacket_g, NULL, "g",
                     "Read registers"));
  t.push_back(Packet(write_memory, &RNBRemote::HandlePacket_M, NULL, "M",
                     "Write memory"));
  t.push_back(Packet(write_register, &RNBRemote::HandlePacket_P, NULL, "P",
                     "Write one register"));
  t.push_back(Packet(write_general_regs, &RNBRemote::HandlePacket_G, NULL, "G",
                     "Write registers"));
  t.push_back(Packet(insert_mem_bp, &RNBRemote::HandlePacket_z, NULL, "Z0",
                     "Insert memory breakpoint"));
  t.push_back(Packet(remove_mem_bp, &RNBRemote::HandlePacket_z, NULL, "z0",
                     "Remove memory breakpoint"));
  t.push_back(Packet(single_step, &RNBRemote::HandlePacket_s, NULL, "s",
                     "Single step"));
  t.push_back(Packet(cont, &RNBRemote::HandlePacket_c, NULL, "c", "continue"));
  t.push_back(Packet(single_step_with_sig, &RNBRemote::HandlePacket_S, NULL,
                     "S", "Single step with signal"));
  t.push_back(
      Packet(set_thread, &RNBRemote::HandlePacket_H, NULL, "H", "Set thread"));
  t.push_back(Packet(halt, &RNBRemote::HandlePacket_last_signal,
                     &RNBRemote::HandlePacket_stop_process, "\x03", "^C"));
  //  t.push_back (Packet (use_extended_mode,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "!", "Use extended mode"));
  t.push_back(Packet(why_halted, &RNBRemote::HandlePacket_last_signal, NULL,
                     "?", "Why did target halt"));
  t.push_back(
      Packet(set_argv, &RNBRemote::HandlePacket_A, NULL, "A", "Set argv"));
  //  t.push_back (Packet (set_bp,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "B", "Set/clear
  //  breakpoint"));
  t.push_back(Packet(continue_with_sig, &RNBRemote::HandlePacket_C, NULL, "C",
                     "Continue with signal"));
  t.push_back(Packet(detach, &RNBRemote::HandlePacket_D, NULL, "D",
                     "Detach gdb from remote system"));
  //  t.push_back (Packet (step_inferior_one_cycle,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "i", "Step inferior by one
  //  clock cycle"));
  //  t.push_back (Packet (signal_and_step_inf_one_cycle,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "I", "Signal inferior, then
  //  step one clock cycle"));
  t.push_back(Packet(kill, &RNBRemote::HandlePacket_k, NULL, "k", "Kill"));
  //  t.push_back (Packet (restart,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "R", "Restart inferior"));
  //  t.push_back (Packet (search_mem_backwards,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "t", "Search memory
  //  backwards"));
  t.push_back(Packet(thread_alive_p, &RNBRemote::HandlePacket_T, NULL, "T",
                     "Is thread alive"));
  t.push_back(Packet(query_supported_features,
                     &RNBRemote::HandlePacket_qSupported, NULL, "qSupported",
                     "Query about supported features"));
  t.push_back(Packet(vattach, &RNBRemote::HandlePacket_v, NULL, "vAttach",
                     "Attach to a new process"));
  t.push_back(Packet(vattachwait, &RNBRemote::HandlePacket_v, NULL,
                     "vAttachWait",
                     "Wait for a process to start up then attach to it"));
  t.push_back(Packet(vattachorwait, &RNBRemote::HandlePacket_v, NULL,
                     "vAttachOrWait", "Attach to the process or if it doesn't "
                                      "exist, wait for the process to start up "
                                      "then attach to it"));
  t.push_back(Packet(vattachname, &RNBRemote::HandlePacket_v, NULL,
                     "vAttachName", "Attach to an existing process by name"));
  t.push_back(Packet(vcont_list_actions, &RNBRemote::HandlePacket_v, NULL,
                     "vCont;", "Verbose resume with thread actions"));
  t.push_back(Packet(vcont_list_actions, &RNBRemote::HandlePacket_v, NULL,
                     "vCont?",
                     "List valid continue-with-thread-actions actions"));
  t.push_back(Packet(read_data_from_memory, &RNBRemote::HandlePacket_x, NULL,
                     "x", "Read data from memory"));
  t.push_back(Packet(write_data_to_memory, &RNBRemote::HandlePacket_X, NULL,
                     "X", "Write data to memory"));
  //  t.push_back (Packet (insert_hardware_bp,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "Z1", "Insert hardware
  //  breakpoint"));
  //  t.push_back (Packet (remove_hardware_bp,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "z1", "Remove hardware
  //  breakpoint"));
  t.push_back(Packet(insert_write_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "Z2", "Insert write watchpoint"));
  t.push_back(Packet(remove_write_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "z2", "Remove write watchpoint"));
  t.push_back(Packet(insert_read_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "Z3", "Insert read watchpoint"));
  t.push_back(Packet(remove_read_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "z3", "Remove read watchpoint"));
  t.push_back(Packet(insert_access_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "Z4", "Insert access watchpoint"));
  t.push_back(Packet(remove_access_watch_bp, &RNBRemote::HandlePacket_z, NULL,
                     "z4", "Remove access watchpoint"));
  t.push_back(Packet(query_monitor, &RNBRemote::HandlePacket_qRcmd, NULL,
                     "qRcmd", "Monitor command"));
  t.push_back(Packet(query_current_thread_id, &RNBRemote::HandlePacket_qC, NULL,
                     "qC", "Query current thread ID"));
  t.push_back(Packet(query_echo, &RNBRemote::HandlePacket_qEcho, NULL, "qEcho:",
                     "Echo the packet back to allow the debugger to sync up "
                     "with this server"));
  t.push_back(Packet(query_get_pid, &RNBRemote::HandlePacket_qGetPid, NULL,
                     "qGetPid", "Query process id"));
  t.push_back(Packet(query_thread_ids_first,
                     &RNBRemote::HandlePacket_qThreadInfo, NULL, "qfThreadInfo",
                     "Get list of active threads (first req)"));
  t.push_back(Packet(query_thread_ids_subsequent,
                     &RNBRemote::HandlePacket_qThreadInfo, NULL, "qsThreadInfo",
                     "Get list of active threads (subsequent req)"));
  // APPLE LOCAL: qThreadStopInfo
  // syntax: qThreadStopInfoTTTT
  //  TTTT is hex thread ID
  t.push_back(Packet(query_thread_stop_info,
                     &RNBRemote::HandlePacket_qThreadStopInfo, NULL,
                     "qThreadStopInfo",
                     "Get detailed info on why the specified thread stopped"));
  t.push_back(Packet(query_thread_extra_info,
                     &RNBRemote::HandlePacket_qThreadExtraInfo, NULL,
                     "qThreadExtraInfo", "Get printable status of a thread"));
  //  t.push_back (Packet (query_image_offsets,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "qOffsets", "Report offset
  //  of loaded program"));
  t.push_back(Packet(
      query_launch_success, &RNBRemote::HandlePacket_qLaunchSuccess, NULL,
      "qLaunchSuccess", "Report the success or failure of the launch attempt"));
  t.push_back(
      Packet(query_register_info, &RNBRemote::HandlePacket_qRegisterInfo, NULL,
             "qRegisterInfo",
             "Dynamically discover remote register context information."));
  t.push_back(Packet(
      query_shlib_notify_info_addr, &RNBRemote::HandlePacket_qShlibInfoAddr,
      NULL, "qShlibInfoAddr", "Returns the address that contains info needed "
                              "for getting shared library notifications"));
  t.push_back(Packet(query_step_packet_supported,
                     &RNBRemote::HandlePacket_qStepPacketSupported, NULL,
                     "qStepPacketSupported",
                     "Replys with OK if the 's' packet is supported."));
  t.push_back(
      Packet(query_vattachorwait_supported,
             &RNBRemote::HandlePacket_qVAttachOrWaitSupported, NULL,
             "qVAttachOrWaitSupported",
             "Replys with OK if the 'vAttachOrWait' packet is supported."));
  t.push_back(
      Packet(query_sync_thread_state_supported,
             &RNBRemote::HandlePacket_qSyncThreadStateSupported, NULL,
             "qSyncThreadStateSupported",
             "Replys with OK if the 'QSyncThreadState:' packet is supported."));
  t.push_back(Packet(
      query_host_info, &RNBRemote::HandlePacket_qHostInfo, NULL, "qHostInfo",
      "Replies with multiple 'key:value;' tuples appended to each other."));
  t.push_back(Packet(
      query_gdb_server_version, &RNBRemote::HandlePacket_qGDBServerVersion,
      NULL, "qGDBServerVersion",
      "Replies with multiple 'key:value;' tuples appended to each other."));
  t.push_back(Packet(
      query_process_info, &RNBRemote::HandlePacket_qProcessInfo, NULL,
      "qProcessInfo",
      "Replies with multiple 'key:value;' tuples appended to each other."));
  t.push_back(Packet(
      query_symbol_lookup, &RNBRemote::HandlePacket_qSymbol, NULL, "qSymbol:",
      "Notify that host debugger is ready to do symbol lookups"));
  t.push_back(Packet(json_query_thread_extended_info,
                     &RNBRemote::HandlePacket_jThreadExtendedInfo, NULL,
                     "jThreadExtendedInfo",
                     "Replies with JSON data of thread extended information."));
  t.push_back(Packet(json_query_get_loaded_dynamic_libraries_infos,
                     &RNBRemote::HandlePacket_jGetLoadedDynamicLibrariesInfos,
                     NULL, "jGetLoadedDynamicLibrariesInfos",
                     "Replies with JSON data of all the shared libraries "
                     "loaded in this process."));
  t.push_back(
      Packet(json_query_threads_info, &RNBRemote::HandlePacket_jThreadsInfo,
             NULL, "jThreadsInfo",
             "Replies with JSON data with information about all threads."));
  t.push_back(Packet(json_query_get_shared_cache_info,
                     &RNBRemote::HandlePacket_jGetSharedCacheInfo, NULL,
                     "jGetSharedCacheInfo", "Replies with JSON data about the "
                                            "location and uuid of the shared "
                                            "cache in the inferior process."));
  t.push_back(Packet(start_noack_mode, &RNBRemote::HandlePacket_QStartNoAckMode,
                     NULL, "QStartNoAckMode",
                     "Request that " DEBUGSERVER_PROGRAM_NAME
                     " stop acking remote protocol packets"));
  t.push_back(Packet(prefix_reg_packets_with_tid,
                     &RNBRemote::HandlePacket_QThreadSuffixSupported, NULL,
                     "QThreadSuffixSupported",
                     "Check if thread specific packets (register packets 'g', "
                     "'G', 'p', and 'P') support having the thread ID appended "
                     "to the end of the command"));
  t.push_back(Packet(set_logging_mode, &RNBRemote::HandlePacket_QSetLogging,
                     NULL, "QSetLogging:", "Check if register packets ('g', "
                                           "'G', 'p', and 'P' support having "
                                           "the thread ID prefix"));
  t.push_back(Packet(
      set_max_packet_size, &RNBRemote::HandlePacket_QSetMaxPacketSize, NULL,
      "QSetMaxPacketSize:",
      "Tell " DEBUGSERVER_PROGRAM_NAME " the max sized packet gdb can handle"));
  t.push_back(Packet(
      set_max_payload_size, &RNBRemote::HandlePacket_QSetMaxPayloadSize, NULL,
      "QSetMaxPayloadSize:", "Tell " DEBUGSERVER_PROGRAM_NAME
                             " the max sized payload gdb can handle"));
  t.push_back(
      Packet(set_environment_variable, &RNBRemote::HandlePacket_QEnvironment,
             NULL, "QEnvironment:",
             "Add an environment variable to the inferior's environment"));
  t.push_back(
      Packet(set_environment_variable_hex,
             &RNBRemote::HandlePacket_QEnvironmentHexEncoded, NULL,
             "QEnvironmentHexEncoded:",
             "Add an environment variable to the inferior's environment"));
  t.push_back(Packet(set_launch_arch, &RNBRemote::HandlePacket_QLaunchArch,
                     NULL, "QLaunchArch:", "Set the architecture to use when "
                                           "launching a process for hosts that "
                                           "can run multiple architecture "
                                           "slices from universal files."));
  t.push_back(Packet(set_disable_aslr, &RNBRemote::HandlePacket_QSetDisableASLR,
                     NULL, "QSetDisableASLR:",
                     "Set whether to disable ASLR when launching the process "
                     "with the set argv ('A') packet"));
  t.push_back(Packet(set_stdin, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
                     "QSetSTDIN:", "Set the standard input for a process to be "
                                   "launched with the 'A' packet"));
  t.push_back(Packet(set_stdout, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
                     "QSetSTDOUT:", "Set the standard output for a process to "
                                    "be launched with the 'A' packet"));
  t.push_back(Packet(set_stderr, &RNBRemote::HandlePacket_QSetSTDIO, NULL,
                     "QSetSTDERR:", "Set the standard error for a process to "
                                    "be launched with the 'A' packet"));
  t.push_back(Packet(set_working_dir, &RNBRemote::HandlePacket_QSetWorkingDir,
                     NULL, "QSetWorkingDir:", "Set the working directory for a "
                                              "process to be launched with the "
                                              "'A' packet"));
  t.push_back(Packet(set_list_threads_in_stop_reply,
                     &RNBRemote::HandlePacket_QListThreadsInStopReply, NULL,
                     "QListThreadsInStopReply",
                     "Set if the 'threads' key should be added to the stop "
                     "reply packets with a list of all thread IDs."));
  t.push_back(Packet(
      sync_thread_state, &RNBRemote::HandlePacket_QSyncThreadState, NULL,
      "QSyncThreadState:", "Do whatever is necessary to make sure 'thread' is "
                           "in a safe state to call functions on."));
  //  t.push_back (Packet (pass_signals_to_inferior,
  //  &RNBRemote::HandlePacket_UNIMPLEMENTED, NULL, "QPassSignals:", "Specify
  //  which signals are passed to the inferior"));
  t.push_back(Packet(allocate_memory, &RNBRemote::HandlePacket_AllocateMemory,
                     NULL, "_M", "Allocate memory in the inferior process."));
  t.push_back(Packet(deallocate_memory,
                     &RNBRemote::HandlePacket_DeallocateMemory, NULL, "_m",
                     "Deallocate memory in the inferior process."));
  t.push_back(Packet(
      save_register_state, &RNBRemote::HandlePacket_SaveRegisterState, NULL,
      "QSaveRegisterState", "Save the register state for the current thread "
                            "and return a decimal save ID."));
  t.push_back(Packet(restore_register_state,
                     &RNBRemote::HandlePacket_RestoreRegisterState, NULL,
                     "QRestoreRegisterState:",
                     "Restore the register state given a save ID previously "
                     "returned from a call to QSaveRegisterState."));
  t.push_back(Packet(
      memory_region_info, &RNBRemote::HandlePacket_MemoryRegionInfo, NULL,
      "qMemoryRegionInfo", "Return size and attributes of a memory region that "
                           "contains the given address"));
  t.push_back(Packet(get_profile_data, &RNBRemote::HandlePacket_GetProfileData,
                     NULL, "qGetProfileData",
                     "Return profiling data of the current target."));
  t.push_back(Packet(set_enable_profiling,
                     &RNBRemote::HandlePacket_SetEnableAsyncProfiling, NULL,
                     "QSetEnableAsyncProfiling",
                     "Enable or disable the profiling of current target."));
  t.push_back(Packet(enable_compression,
                     &RNBRemote::HandlePacket_QEnableCompression, NULL,
                     "QEnableCompression:",
                     "Enable compression for the remainder of the connection"));
  t.push_back(Packet(watchpoint_support_info,
                     &RNBRemote::HandlePacket_WatchpointSupportInfo, NULL,
                     "qWatchpointSupportInfo",
                     "Return the number of supported hardware watchpoints"));
  t.push_back(Packet(set_process_event,
                     &RNBRemote::HandlePacket_QSetProcessEvent, NULL,
                     "QSetProcessEvent:", "Set a process event, to be passed "
                                          "to the process, can be set before "
                                          "the process is started, or after."));
  t.push_back(
      Packet(set_detach_on_error, &RNBRemote::HandlePacket_QSetDetachOnError,
             NULL, "QSetDetachOnError:",
             "Set whether debugserver will detach (1) or kill (0) from the "
             "process it is controlling if it loses connection to lldb."));
  t.push_back(Packet(
      speed_test, &RNBRemote::HandlePacket_qSpeedTest, NULL, "qSpeedTest:",
      "Test the maximum speed at which packet can be sent/received."));
  t.push_back(Packet(query_transfer, &RNBRemote::HandlePacket_qXfer, NULL,
                     "qXfer:", "Support the qXfer packet."));
  t.push_back(
      Packet(query_supported_async_json_packets,
             &RNBRemote::HandlePacket_qStructuredDataPlugins, NULL,
             "qStructuredDataPlugins",
             "Query for the structured data plugins supported by the remote."));
  t.push_back(
      Packet(configure_darwin_log, &RNBRemote::HandlePacket_QConfigureDarwinLog,
             NULL, "QConfigureDarwinLog:",
             "Configure the DarwinLog structured data plugin support."));
}

void RNBRemote::FlushSTDIO() {
  if (m_ctx.HasValidProcessID()) {
    nub_process_t pid = m_ctx.ProcessID();
    char buf[256];
    nub_size_t count;
    do {
      count = DNBProcessGetAvailableSTDOUT(pid, buf, sizeof(buf));
      if (count > 0) {
        SendSTDOUTPacket(buf, count);
      }
    } while (count > 0);

    do {
      count = DNBProcessGetAvailableSTDERR(pid, buf, sizeof(buf));
      if (count > 0) {
        SendSTDERRPacket(buf, count);
      }
    } while (count > 0);
  }
}

void RNBRemote::SendAsyncProfileData() {
  if (m_ctx.HasValidProcessID()) {
    nub_process_t pid = m_ctx.ProcessID();
    char buf[1024];
    nub_size_t count;
    do {
      count = DNBProcessGetAvailableProfileData(pid, buf, sizeof(buf));
      if (count > 0) {
        SendAsyncProfileDataPacket(buf, count);
      }
    } while (count > 0);
  }
}

void RNBRemote::SendAsyncDarwinLogData() {
  DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): enter", __FUNCTION__);

  if (!m_ctx.HasValidProcessID()) {
    DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): ignoring due to"
                                     "invalid process id",
                     __FUNCTION__);
    return;
  }

  nub_process_t pid = m_ctx.ProcessID();
  DarwinLogEventVector::size_type entry_count = 0;

  // NOTE: the current looping structure here does nothing
  // to guarantee that we can send off async packets faster
  // than we generate them.  It will keep sending as long
  // as there's data to send.
  do {
    DarwinLogEventVector events = DNBProcessGetAvailableDarwinLogEvents(pid);
    entry_count = events.size();

    DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): outer loop enter",
                     __FUNCTION__);

    for (DarwinLogEventVector::size_type base_entry = 0;
         base_entry < entry_count;
         base_entry += DARWIN_LOG_MAX_EVENTS_PER_PACKET) {
      DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): inner loop enter",
                       __FUNCTION__);

      // We limit the total number of entries we pack
      // into a single JSON async packet just so it
      // doesn't get too large.
      JSONGenerator::Dictionary async_dictionary;

      // Specify the type of the JSON async data we're sending.
      async_dictionary.AddStringItem(JSON_ASYNC_TYPE_KEY_NAME, "DarwinLog");

      // Create an array entry in the dictionary to hold all
      // the events going in this packet.
      JSONGenerator::ArraySP events_array(new JSONGenerator::Array());
      async_dictionary.AddItem(OS_LOG_EVENTS_KEY_NAME, events_array);

      // We bundle up to DARWIN_LOG_MAX_EVENTS_PER_PACKET events in
      // a single packet.
      const auto inner_loop_bound =
          std::min(base_entry + DARWIN_LOG_MAX_EVENTS_PER_PACKET, entry_count);
      for (DarwinLogEventVector::size_type i = base_entry; i < inner_loop_bound;
           ++i) {
        DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): adding "
                                         "entry index %lu to the JSON packet",
                         __FUNCTION__, i);
        events_array->AddItem(events[i]);
      }

      // Send off the packet.
      DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): sending JSON "
                                       "packet, %lu entries remain",
                       __FUNCTION__, entry_count - inner_loop_bound);
      SendAsyncJSONPacket(async_dictionary);
    }

    DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): outer loop exit",
                     __FUNCTION__);

  } while (entry_count > 0);

  DNBLogThreadedIf(LOG_DARWIN_LOG, "RNBRemote::%s(): exit",
                   __PRETTY_FUNCTION__);
}

rnb_err_t RNBRemote::SendHexEncodedBytePacket(const char *header,
                                              const void *buf, size_t buf_len,
                                              const char *footer) {
  std::ostringstream packet_sstrm;
  // Append the header cstr if there was one
  if (header && header[0])
    packet_sstrm << header;
  nub_size_t i;
  const uint8_t *ubuf8 = (const uint8_t *)buf;
  for (i = 0; i < buf_len; i++) {
    packet_sstrm << RAWHEX8(ubuf8[i]);
  }
  // Append the footer cstr if there was one
  if (footer && footer[0])
    packet_sstrm << footer;

  return SendPacket(packet_sstrm.str());
}

rnb_err_t RNBRemote::SendSTDOUTPacket(char *buf, nub_size_t buf_size) {
  if (buf_size == 0)
    return rnb_success;
  return SendHexEncodedBytePacket("O", buf, buf_size, NULL);
}

rnb_err_t RNBRemote::SendSTDERRPacket(char *buf, nub_size_t buf_size) {
  if (buf_size == 0)
    return rnb_success;
  return SendHexEncodedBytePacket("O", buf, buf_size, NULL);
}

// This makes use of asynchronous bit 'A' in the gdb remote protocol.
rnb_err_t RNBRemote::SendAsyncProfileDataPacket(char *buf,
                                                nub_size_t buf_size) {
  if (buf_size == 0)
    return rnb_success;

  std::string packet("A");
  packet.append(buf, buf_size);
  return SendPacket(packet);
}

rnb_err_t
RNBRemote::SendAsyncJSONPacket(const JSONGenerator::Dictionary &dictionary) {
  std::ostringstream stream;
  // We're choosing something that is easy to spot if we somehow get one
  // of these coming out at the wrong time (i.e. when the remote side
  // is not waiting for a process control completion response).
  stream << "JSON-async:";
  dictionary.Dump(stream);
  const std::string payload = binary_encode_string(stream.str());
  return SendPacket(payload);
}

// Given a std::string packet contents to send, possibly encode/compress it.
// If compression is enabled, the returned std::string will be in one of two
// forms:
//
//    N<original packet contents uncompressed>
//    C<size of original decompressed packet>:<packet compressed with the
//    requested compression scheme>
//
// If compression is not requested, the original packet contents are returned

std::string RNBRemote::CompressString(const std::string &orig) {
  std::string compressed;
  compression_types compression_type = GetCompressionType();
  if (compression_type != compression_types::none) {
    bool compress_this_packet = false;

    if (orig.size() > m_compression_minsize) {
      compress_this_packet = true;
    }

    if (compress_this_packet) {
      const size_t encoded_data_buf_size = orig.size() + 128;
      std::vector<uint8_t> encoded_data(encoded_data_buf_size);
      size_t compressed_size = 0;

      // Allocate a scratch buffer for libcompression the first
      // time we see a different compression type; reuse it in 
      // all compression_encode_buffer calls so it doesn't need
      // to allocate / free its own scratch buffer each time.
      // This buffer will only be freed when compression type
      // changes; otherwise it will persist until debugserver
      // exit.

      static compression_types g_libcompress_scratchbuf_type = compression_types::none;
      static void *g_libcompress_scratchbuf = nullptr;

      if (g_libcompress_scratchbuf_type != compression_type) {
        if (g_libcompress_scratchbuf) {
          free (g_libcompress_scratchbuf);
          g_libcompress_scratchbuf = nullptr;
        }
        size_t scratchbuf_size = 0;
        switch (compression_type) {
          case compression_types::lz4: 
            scratchbuf_size = compression_encode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
            break;
          case compression_types::zlib_deflate: 
            scratchbuf_size = compression_encode_scratch_buffer_size (COMPRESSION_ZLIB);
            break;
          case compression_types::lzma: 
            scratchbuf_size = compression_encode_scratch_buffer_size (COMPRESSION_LZMA);
            break;
          case compression_types::lzfse: 
            scratchbuf_size = compression_encode_scratch_buffer_size (COMPRESSION_LZFSE);
            break;
          default:
            break;
        }
        if (scratchbuf_size > 0) {
          g_libcompress_scratchbuf = (void*) malloc (scratchbuf_size);
          g_libcompress_scratchbuf_type = compression_type;
        }
      }

      if (compression_type == compression_types::lz4) {
        compressed_size = compression_encode_buffer(
            encoded_data.data(), encoded_data_buf_size,
            (const uint8_t *)orig.c_str(), orig.size(), 
            g_libcompress_scratchbuf,
            COMPRESSION_LZ4_RAW);
      }
      if (compression_type == compression_types::zlib_deflate) {
        compressed_size = compression_encode_buffer(
            encoded_data.data(), encoded_data_buf_size,
            (const uint8_t *)orig.c_str(), orig.size(), 
            g_libcompress_scratchbuf,
            COMPRESSION_ZLIB);
      }
      if (compression_type == compression_types::lzma) {
        compressed_size = compression_encode_buffer(
            encoded_data.data(), encoded_data_buf_size,
            (const uint8_t *)orig.c_str(), orig.size(), 
            g_libcompress_scratchbuf,
            COMPRESSION_LZMA);
      }
      if (compression_type == compression_types::lzfse) {
        compressed_size = compression_encode_buffer(
            encoded_data.data(), encoded_data_buf_size,
            (const uint8_t *)orig.c_str(), orig.size(), 
            g_libcompress_scratchbuf,
            COMPRESSION_LZFSE);
      }

      if (compressed_size > 0) {
        compressed.clear();
        compressed.reserve(compressed_size);
        compressed = "C";
        char numbuf[16];
        snprintf(numbuf, sizeof(numbuf), "%zu:", orig.size());
        numbuf[sizeof(numbuf) - 1] = '\0';
        compressed.append(numbuf);

        for (size_t i = 0; i < compressed_size; i++) {
          uint8_t byte = encoded_data[i];
          if (byte == '#' || byte == '$' || byte == '}' || byte == '*' ||
              byte == '\0') {
            compressed.push_back(0x7d);
            compressed.push_back(byte ^ 0x20);
          } else {
            compressed.push_back(byte);
          }
        }
      } else {
        compressed = "N" + orig;
      }
    } else {
      compressed = "N" + orig;
    }
  } else {
    compressed = orig;
  }

  return compressed;
}

rnb_err_t RNBRemote::SendPacket(const std::string &s) {
  DNBLogThreadedIf(LOG_RNB_MAX, "%8d RNBRemote::%s (%s) called",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__, s.c_str());

  std::string s_compressed = CompressString(s);

  std::string sendpacket = "$" + s_compressed + "#";
  int cksum = 0;
  char hexbuf[5];

  if (m_noack_mode) {
    sendpacket += "00";
  } else {
    for (size_t i = 0; i != s_compressed.size(); ++i)
      cksum += s_compressed[i];
    snprintf(hexbuf, sizeof hexbuf, "%02x", cksum & 0xff);
    sendpacket += hexbuf;
  }

  rnb_err_t err = m_comm.Write(sendpacket.c_str(), sendpacket.size());
  if (err != rnb_success)
    return err;

  if (m_noack_mode)
    return rnb_success;

  std::string reply;
  RNBRemote::Packet packet;
  err = GetPacket(reply, packet, true);

  if (err != rnb_success) {
    DNBLogThreadedIf(LOG_RNB_REMOTE,
                     "%8d RNBRemote::%s (%s) got error trying to get reply...",
                     (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                     __FUNCTION__, sendpacket.c_str());
    return err;
  }

  DNBLogThreadedIf(LOG_RNB_MAX, "%8d RNBRemote::%s (%s) got reply: '%s'",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__, sendpacket.c_str(), reply.c_str());

  if (packet.type == ack)
    return rnb_success;

  // Should we try to resend the packet at this layer?
  //  if (packet.command == nack)
  return rnb_err;
}

/* Get a packet via gdb remote protocol.
 Strip off the prefix/suffix, verify the checksum to make sure
 a valid packet was received, send an ACK if they match.  */

rnb_err_t RNBRemote::GetPacketPayload(std::string &return_packet) {
  // DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s called",
  // (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);

  PThreadMutex::Locker locker(m_mutex);
  if (m_rx_packets.empty()) {
    // Only reset the remote command available event if we have no more packets
    m_ctx.Events().ResetEvents(RNBContext::event_read_packet_available);
    // DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s error: no packets
    // available...", (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
    // __FUNCTION__);
    return rnb_err;
  }

  // DNBLogThreadedIf (LOG_RNB_MAX, "%8u RNBRemote::%s has %u queued packets",
  // (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
  // m_rx_packets.size());
  return_packet.swap(m_rx_packets.front());
  m_rx_packets.pop_front();
  locker.Reset(); // Release our lock on the mutex

  if (m_rx_packets.empty()) {
    // Reset the remote command available event if we have no more packets
    m_ctx.Events().ResetEvents(RNBContext::event_read_packet_available);
  }

  // DNBLogThreadedIf (LOG_RNB_MEDIUM, "%8u RNBRemote::%s: '%s'",
  // (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
  // return_packet.c_str());

  switch (return_packet[0]) {
  case '+':
  case '-':
  case '\x03':
    break;

  case '$': {
    long packet_checksum = 0;
    if (!m_noack_mode) {
      for (size_t i = return_packet.size() - 2; i < return_packet.size(); ++i) {
        char checksum_char = tolower(return_packet[i]);
        if (!isxdigit(checksum_char)) {
          m_comm.Write("-", 1);
          DNBLogThreadedIf(LOG_RNB_REMOTE, "%8u RNBRemote::%s error: packet "
                                           "with invalid checksum characters: "
                                           "%s",
                           (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                           __FUNCTION__, return_packet.c_str());
          return rnb_err;
        }
      }
      packet_checksum =
          strtol(&return_packet[return_packet.size() - 2], NULL, 16);
    }

    return_packet.erase(0, 1);                     // Strip the leading '$'
    return_packet.erase(return_packet.size() - 3); // Strip the #XX checksum

    if (!m_noack_mode) {
      // Compute the checksum
      int computed_checksum = 0;
      for (std::string::iterator it = return_packet.begin();
           it != return_packet.end(); ++it) {
        computed_checksum += *it;
      }

      if (packet_checksum == (computed_checksum & 0xff)) {
        // DNBLogThreadedIf (LOG_RNB_MEDIUM, "%8u RNBRemote::%s sending ACK for
        // '%s'", (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
        // __FUNCTION__, return_packet.c_str());
        m_comm.Write("+", 1);
      } else {
        DNBLogThreadedIf(
            LOG_RNB_MEDIUM, "%8u RNBRemote::%s sending ACK for '%s' (error: "
                            "packet checksum mismatch  (0x%2.2lx != 0x%2.2x))",
            (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
            return_packet.c_str(), packet_checksum, computed_checksum);
        m_comm.Write("-", 1);
        return rnb_err;
      }
    }
  } break;

  default:
    DNBLogThreadedIf(LOG_RNB_REMOTE,
                     "%8u RNBRemote::%s tossing unexpected packet???? %s",
                     (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                     __FUNCTION__, return_packet.c_str());
    if (!m_noack_mode)
      m_comm.Write("-", 1);
    return rnb_err;
  }

  return rnb_success;
}

rnb_err_t RNBRemote::HandlePacket_UNIMPLEMENTED(const char *p) {
  DNBLogThreadedIf(LOG_RNB_MAX, "%8u RNBRemote::%s(\"%s\")",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__, p ? p : "NULL");
  return SendPacket("");
}

rnb_err_t RNBRemote::HandlePacket_ILLFORMED(const char *file, int line,
                                            const char *p,
                                            const char *description) {
  DNBLogThreadedIf(LOG_RNB_PACKETS, "%8u %s:%i ILLFORMED: '%s' (%s)",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), file,
                   line, __FUNCTION__, p);
  return SendPacket("E03");
}

rnb_err_t RNBRemote::GetPacket(std::string &packet_payload,
                               RNBRemote::Packet &packet_info, bool wait) {
  std::string payload;
  rnb_err_t err = GetPacketPayload(payload);
  if (err != rnb_success) {
    PThreadEvent &events = m_ctx.Events();
    nub_event_t set_events = events.GetEventBits();
    // TODO: add timeout version of GetPacket?? We would then need to pass
    // that timeout value along to DNBProcessTimedWaitForEvent.
    if (!wait || ((set_events & RNBContext::event_read_thread_running) == 0))
      return err;

    const nub_event_t events_to_wait_for =
        RNBContext::event_read_packet_available |
        RNBContext::event_read_thread_exiting;

    while ((set_events = events.WaitForSetEvents(events_to_wait_for)) != 0) {
      if (set_events & RNBContext::event_read_packet_available) {
        // Try the queue again now that we got an event
        err = GetPacketPayload(payload);
        if (err == rnb_success)
          break;
      }

      if (set_events & RNBContext::event_read_thread_exiting)
        err = rnb_not_connected;

      if (err == rnb_not_connected)
        return err;
    }
    while (err == rnb_err)
      ;

    if (set_events == 0)
      err = rnb_not_connected;
  }

  if (err == rnb_success) {
    Packet::iterator it;
    for (it = m_packets.begin(); it != m_packets.end(); ++it) {
      if (payload.compare(0, it->abbrev.size(), it->abbrev) == 0)
        break;
    }

    // A packet we don't have an entry for. This can happen when we
    // get a packet that we don't know about or support. We just reply
    // accordingly and go on.
    if (it == m_packets.end()) {
      DNBLogThreadedIf(LOG_RNB_PACKETS, "unimplemented packet: '%s'",
                       payload.c_str());
      HandlePacket_UNIMPLEMENTED(payload.c_str());
      return rnb_err;
    } else {
      packet_info = *it;
      packet_payload = payload;
    }
  }
  return err;
}

rnb_err_t RNBRemote::HandleAsyncPacket(PacketEnum *type) {
  DNBLogThreadedIf(LOG_RNB_REMOTE, "%8u RNBRemote::%s",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__);
  static DNBTimer g_packetTimer(true);
  rnb_err_t err = rnb_err;
  std::string packet_data;
  RNBRemote::Packet packet_info;
  err = GetPacket(packet_data, packet_info, false);

  if (err == rnb_success) {
    if (!packet_data.empty() && isprint(packet_data[0]))
      DNBLogThreadedIf(LOG_RNB_REMOTE | LOG_RNB_PACKETS,
                       "HandleAsyncPacket (\"%s\");", packet_data.c_str());
    else
      DNBLogThreadedIf(LOG_RNB_REMOTE | LOG_RNB_PACKETS,
                       "HandleAsyncPacket (%s);",
                       packet_info.printable_name.c_str());

    HandlePacketCallback packet_callback = packet_info.async;
    if (packet_callback != NULL) {
      if (type != NULL)
        *type = packet_info.type;
      return (this->*packet_callback)(packet_data.c_str());
    }
  }

  return err;
}

rnb_err_t RNBRemote::HandleReceivedPacket(PacketEnum *type) {
  static DNBTimer g_packetTimer(true);

  //  DNBLogThreadedIf (LOG_RNB_REMOTE, "%8u RNBRemote::%s",
  //  (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);
  rnb_err_t err = rnb_err;
  std::string packet_data;
  RNBRemote::Packet packet_info;
  err = GetPacket(packet_data, packet_info, false);

  if (err == rnb_success) {
    DNBLogThreadedIf(LOG_RNB_REMOTE, "HandleReceivedPacket (\"%s\");",
                     packet_data.c_str());
    HandlePacketCallback packet_callback = packet_info.normal;
    if (packet_callback != NULL) {
      if (type != NULL)
        *type = packet_info.type;
      return (this->*packet_callback)(packet_data.c_str());
    } else {
      // Do not fall through to end of this function, if we have valid
      // packet_info and it has a NULL callback, then we need to respect
      // that it may not want any response or anything to be done.
      return err;
    }
  }
  return rnb_err;
}

void RNBRemote::CommDataReceived(const std::string &new_data) {
  //  DNBLogThreadedIf (LOG_RNB_REMOTE, "%8d RNBRemote::%s called",
  //  (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);
  {
    // Put the packet data into the buffer in a thread safe fashion
    PThreadMutex::Locker locker(m_mutex);

    std::string data;
    // See if we have any left over data from a previous call to this
    // function?
    if (!m_rx_partial_data.empty()) {
      // We do, so lets start with that data
      data.swap(m_rx_partial_data);
    }
    // Append the new incoming data
    data += new_data;

    // Parse up the packets into gdb remote packets
    size_t idx = 0;
    const size_t data_size = data.size();

    while (idx < data_size) {
      // end_idx must be one past the last valid packet byte. Start
      // it off with an invalid value that is the same as the current
      // index.
      size_t end_idx = idx;

      switch (data[idx]) {
      case '+':            // Look for ack
      case '-':            // Look for cancel
      case '\x03':         // ^C to halt target
        end_idx = idx + 1; // The command is one byte long...
        break;

      case '$':
        // Look for a standard gdb packet?
        end_idx = data.find('#', idx + 1);
        if (end_idx == std::string::npos || end_idx + 3 > data_size) {
          end_idx = std::string::npos;
        } else {
          // Add two for the checksum bytes and 1 to point to the
          // byte just past the end of this packet
          end_idx += 3;
        }
        break;

      default:
        break;
      }

      if (end_idx == std::string::npos) {
        // Not all data may be here for the packet yet, save it for
        // next time through this function.
        m_rx_partial_data += data.substr(idx);
        // DNBLogThreadedIf (LOG_RNB_MAX, "%8d RNBRemote::%s saving data for
        // later[%u, npos):
        // '%s'",(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
        // __FUNCTION__, idx, m_rx_partial_data.c_str());
        idx = end_idx;
      } else if (idx < end_idx) {
        m_packets_recvd++;
        // Hack to get rid of initial '+' ACK???
        if (m_packets_recvd == 1 && (end_idx == idx + 1) && data[idx] == '+') {
          // DNBLogThreadedIf (LOG_RNB_REMOTE, "%8d RNBRemote::%s throwing first
          // ACK away....[%u, npos):
          // '+'",(uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
          // __FUNCTION__, idx);
        } else {
          // We have a valid packet...
          m_rx_packets.push_back(data.substr(idx, end_idx - idx));
          DNBLogThreadedIf(LOG_RNB_PACKETS, "getpkt: %s",
                           m_rx_packets.back().c_str());
        }
        idx = end_idx;
      } else {
        DNBLogThreadedIf(LOG_RNB_MAX,
                         "%8d RNBRemote::%s tossing junk byte at %c",
                         (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                         __FUNCTION__, data[idx]);
        idx = idx + 1;
      }
    }
  }

  if (!m_rx_packets.empty()) {
    // Let the main thread know we have received a packet

    // DNBLogThreadedIf (LOG_RNB_EVENTS, "%8d RNBRemote::%s   called
    // events.SetEvent(RNBContext::event_read_packet_available)",
    // (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);
    PThreadEvent &events = m_ctx.Events();
    events.SetEvents(RNBContext::event_read_packet_available);
  }
}

rnb_err_t RNBRemote::GetCommData() {
  //  DNBLogThreadedIf (LOG_RNB_REMOTE, "%8d RNBRemote::%s called",
  //  (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__);
  std::string comm_data;
  rnb_err_t err = m_comm.Read(comm_data);
  if (err == rnb_success) {
    if (!comm_data.empty())
      CommDataReceived(comm_data);
  }
  return err;
}

void RNBRemote::StartReadRemoteDataThread() {
  DNBLogThreadedIf(LOG_RNB_REMOTE, "%8u RNBRemote::%s called",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__);
  PThreadEvent &events = m_ctx.Events();
  if ((events.GetEventBits() & RNBContext::event_read_thread_running) == 0) {
    events.ResetEvents(RNBContext::event_read_thread_exiting);
    int err = ::pthread_create(&m_rx_pthread, NULL,
                               ThreadFunctionReadRemoteData, this);
    if (err == 0) {
      // Our thread was successfully kicked off, wait for it to
      // set the started event so we can safely continue
      events.WaitForSetEvents(RNBContext::event_read_thread_running);
    } else {
      events.ResetEvents(RNBContext::event_read_thread_running);
      events.SetEvents(RNBContext::event_read_thread_exiting);
    }
  }
}

void RNBRemote::StopReadRemoteDataThread() {
  DNBLogThreadedIf(LOG_RNB_REMOTE, "%8u RNBRemote::%s called",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__);
  PThreadEvent &events = m_ctx.Events();
  if ((events.GetEventBits() & RNBContext::event_read_thread_running) ==
      RNBContext::event_read_thread_running) {
    m_comm.Disconnect(true);
    struct timespec timeout_abstime;
    DNBTimer::OffsetTimeOfDay(&timeout_abstime, 2, 0);

    // Wait for 2 seconds for the remote data thread to exit
    if (events.WaitForSetEvents(RNBContext::event_read_thread_exiting,
                                &timeout_abstime) == 0) {
      // Kill the remote data thread???
    }
  }
}

void *RNBRemote::ThreadFunctionReadRemoteData(void *arg) {
  // Keep a shared pointer reference so this doesn't go away on us before the
  // thread is killed.
  DNBLogThreadedIf(LOG_RNB_REMOTE, "RNBRemote::%s (%p): thread starting...",
                   __FUNCTION__, arg);
  RNBRemoteSP remoteSP(g_remoteSP);
  if (remoteSP.get() != NULL) {

#if defined(__APPLE__)
    pthread_setname_np("read gdb-remote packets thread");
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
    struct sched_param thread_param;
    int thread_sched_policy;
    if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
                              &thread_param) == 0) {
      thread_param.sched_priority = 47;
      pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
    }
#endif
#endif

    RNBRemote *remote = remoteSP.get();
    PThreadEvent &events = remote->Context().Events();
    events.SetEvents(RNBContext::event_read_thread_running);
    // START: main receive remote command thread loop
    bool done = false;
    while (!done) {
      rnb_err_t err = remote->GetCommData();

      switch (err) {
      case rnb_success:
        break;

      case rnb_err:
        DNBLogThreadedIf(LOG_RNB_REMOTE,
                         "RNBSocket::GetCommData returned error %u", err);
        done = true;
        break;

      case rnb_not_connected:
        DNBLogThreadedIf(LOG_RNB_REMOTE,
                         "RNBSocket::GetCommData returned not connected...");
        done = true;
        break;
      }
    }
    // START: main receive remote command thread loop
    events.ResetEvents(RNBContext::event_read_thread_running);
    events.SetEvents(RNBContext::event_read_thread_exiting);
  }
  DNBLogThreadedIf(LOG_RNB_REMOTE, "RNBRemote::%s (%p): thread exiting...",
                   __FUNCTION__, arg);
  return NULL;
}

// If we fail to get back a valid CPU type for the remote process,
// make a best guess for the CPU type based on the currently running
// debugserver binary -- the debugger may not handle the case of an
// un-specified process CPU type correctly.

static cpu_type_t best_guess_cpu_type() {
#if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
  if (sizeof(char *) == 8) {
    return CPU_TYPE_ARM64;
  } else {
#if defined (__ARM64_ARCH_8_32__)
    return CPU_TYPE_ARM64_32;
#endif
    return CPU_TYPE_ARM;
  }
#elif defined(__i386__) || defined(__x86_64__)
  if (sizeof(char *) == 8) {
    return CPU_TYPE_X86_64;
  } else {
    return CPU_TYPE_I386;
  }
#endif
  return 0;
}

/* Read the bytes in STR which are GDB Remote Protocol binary encoded bytes
 (8-bit bytes).
 This encoding uses 0x7d ('}') as an escape character for
 0x7d ('}'), 0x23 ('#'), 0x24 ('$'), 0x2a ('*').
 LEN is the number of bytes to be processed.  If a character is escaped,
 it is 2 characters for LEN.  A LEN of -1 means decode-until-nul-byte
 (end of string).  */

std::vector<uint8_t> decode_binary_data(const char *str, size_t len) {
  std::vector<uint8_t> bytes;
  if (len == 0) {
    return bytes;
  }
  if (len == (size_t)-1)
    len = strlen(str);

  while (len--) {
    unsigned char c = *str++;
    if (c == 0x7d && len > 0) {
      len--;
      c = *str++ ^ 0x20;
    }
    bytes.push_back(c);
  }
  return bytes;
}

// Quote any meta characters in a std::string as per the binary
// packet convention in the gdb-remote protocol.

static std::string binary_encode_string(const std::string &s) {
  std::string output;
  const size_t s_size = s.size();
  const char *s_chars = s.c_str();

  for (size_t i = 0; i < s_size; i++) {
    unsigned char ch = *(s_chars + i);
    if (ch == '#' || ch == '$' || ch == '}' || ch == '*') {
      output.push_back('}'); // 0x7d
      output.push_back(ch ^ 0x20);
    } else {
      output.push_back(ch);
    }
  }
  return output;
}

// If the value side of a key-value pair in JSON is a string,
// and that string has a " character in it, the " character must
// be escaped.

std::string json_string_quote_metachars(const std::string &s) {
  if (s.find('"') == std::string::npos)
    return s;

  std::string output;
  const size_t s_size = s.size();
  const char *s_chars = s.c_str();
  for (size_t i = 0; i < s_size; i++) {
    unsigned char ch = *(s_chars + i);
    if (ch == '"') {
      output.push_back('\\');
    }
    output.push_back(ch);
  }
  return output;
}

typedef struct register_map_entry {
  uint32_t debugserver_regnum; // debugserver register number
  uint32_t offset; // Offset in bytes into the register context data with no
                   // padding between register values
  DNBRegisterInfo nub_info; // debugnub register info
  std::vector<uint32_t> value_regnums;
  std::vector<uint32_t> invalidate_regnums;
} register_map_entry_t;

// If the notion of registers differs from what is handed out by the
// architecture, then flavors can be defined here.

static std::vector<register_map_entry_t> g_dynamic_register_map;
static register_map_entry_t *g_reg_entries = NULL;
static size_t g_num_reg_entries = 0;

void RNBRemote::Initialize() { DNBInitialize(); }

bool RNBRemote::InitializeRegisters(bool force) {
  pid_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return false;

  DNBLogThreadedIf(
      LOG_RNB_PROC,
      "RNBRemote::%s() getting native registers from DNB interface",
      __FUNCTION__);
  // Discover the registers by querying the DNB interface and letting it
  // state the registers that it would like to export. This allows the
  // registers to be discovered using multiple qRegisterInfo calls to get
  // all register information after the architecture for the process is
  // determined.
  if (force) {
    g_dynamic_register_map.clear();
    g_reg_entries = NULL;
    g_num_reg_entries = 0;
  }

  if (g_dynamic_register_map.empty()) {
    nub_size_t num_reg_sets = 0;
    const DNBRegisterSetInfo *reg_sets = DNBGetRegisterSetInfo(&num_reg_sets);

    assert(num_reg_sets > 0 && reg_sets != NULL);

    uint32_t regnum = 0;
    uint32_t reg_data_offset = 0;
    typedef std::map<std::string, uint32_t> NameToRegNum;
    NameToRegNum name_to_regnum;
    for (nub_size_t set = 0; set < num_reg_sets; ++set) {
      if (reg_sets[set].registers == NULL)
        continue;

      for (uint32_t reg = 0; reg < reg_sets[set].num_registers; ++reg) {
        register_map_entry_t reg_entry = {
            regnum++, // register number starts at zero and goes up with no gaps
            reg_data_offset, // Offset into register context data, no gaps
                             // between registers
            reg_sets[set].registers[reg], // DNBRegisterInfo
            {},
            {},
        };

        name_to_regnum[reg_entry.nub_info.name] = reg_entry.debugserver_regnum;

        if (reg_entry.nub_info.value_regs == NULL) {
          reg_data_offset += reg_entry.nub_info.size;
        }

        g_dynamic_register_map.push_back(reg_entry);
      }
    }

    // Now we must find any registers whose values are in other registers and
    // fix up
    // the offsets since we removed all gaps...
    for (auto &reg_entry : g_dynamic_register_map) {
      if (reg_entry.nub_info.value_regs) {
        uint32_t new_offset = UINT32_MAX;
        for (size_t i = 0; reg_entry.nub_info.value_regs[i] != NULL; ++i) {
          const char *name = reg_entry.nub_info.value_regs[i];
          auto pos = name_to_regnum.find(name);
          if (pos != name_to_regnum.end()) {
            regnum = pos->second;
            reg_entry.value_regnums.push_back(regnum);
            if (regnum < g_dynamic_register_map.size()) {
              // The offset for value_regs registers is the offset within the
              // register with the lowest offset
              const uint32_t reg_offset =
                  g_dynamic_register_map[regnum].offset +
                  reg_entry.nub_info.offset;
              if (new_offset > reg_offset)
                new_offset = reg_offset;
            }
          }
        }

        if (new_offset != UINT32_MAX) {
          reg_entry.offset = new_offset;
        } else {
          DNBLogThreaded("no offset was calculated entry for register %s",
                         reg_entry.nub_info.name);
          reg_entry.offset = UINT32_MAX;
        }
      }

      if (reg_entry.nub_info.update_regs) {
        for (size_t i = 0; reg_entry.nub_info.update_regs[i] != NULL; ++i) {
          const char *name = reg_entry.nub_info.update_regs[i];
          auto pos = name_to_regnum.find(name);
          if (pos != name_to_regnum.end()) {
            regnum = pos->second;
            reg_entry.invalidate_regnums.push_back(regnum);
          }
        }
      }
    }

    //        for (auto &reg_entry: g_dynamic_register_map)
    //        {
    //            DNBLogThreaded("%4i: size = %3u, pseudo = %i, name = %s",
    //                           reg_entry.offset,
    //                           reg_entry.nub_info.size,
    //                           reg_entry.nub_info.value_regs != NULL,
    //                           reg_entry.nub_info.name);
    //        }

    g_reg_entries = g_dynamic_register_map.data();
    g_num_reg_entries = g_dynamic_register_map.size();
  }
  return true;
}

/* The inferior has stopped executing; send a packet
 to gdb to let it know.  */

void RNBRemote::NotifyThatProcessStopped(void) {
  RNBRemote::HandlePacket_last_signal(NULL);
  return;
}

/* 'A arglen,argnum,arg,...'
 Update the inferior context CTX with the program name and arg
 list.
 The documentation for this packet is underwhelming but my best reading
 of this is that it is a series of (len, position #, arg)'s, one for
 each argument with "arg" hex encoded (two 0-9a-f chars?).
 Why we need BOTH a "len" and a hex encoded "arg" is beyond me - either
 is sufficient to get around the "," position separator escape issue.

 e.g. our best guess for a valid 'A' packet for "gdb -q a.out" is

 6,0,676462,4,1,2d71,10,2,612e6f7574

 Note that "argnum" and "arglen" are numbers in base 10.  Again, that's
 not documented either way but I'm assuming it's so.  */

rnb_err_t RNBRemote::HandlePacket_A(const char *p) {
  if (p == NULL || *p == '\0') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Null packet for 'A' pkt");
  }
  p++;
  if (*p == '\0' || !isdigit(*p)) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "arglen not specified on 'A' pkt");
  }

  /* I promise I don't modify it anywhere in this function.  strtoul()'s
   2nd arg has to be non-const which makes it problematic to step
   through the string easily.  */
  char *buf = const_cast<char *>(p);

  RNBContext &ctx = Context();

  while (*buf != '\0') {
    unsigned long arglen, argnum;
    std::string arg;
    char *c;

    errno = 0;
    arglen = strtoul(buf, &c, 10);
    if (errno != 0 && arglen == 0) {
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "arglen not a number on 'A' pkt");
    }
    if (*c != ',') {
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "arglen not followed by comma on 'A' pkt");
    }
    buf = c + 1;

    errno = 0;
    argnum = strtoul(buf, &c, 10);
    if (errno != 0 && argnum == 0) {
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "argnum not a number on 'A' pkt");
    }
    if (*c != ',') {
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "arglen not followed by comma on 'A' pkt");
    }
    buf = c + 1;

    c = buf;
    buf = buf + arglen;
    while (c < buf && *c != '\0' && c + 1 < buf && *(c + 1) != '\0') {
      char smallbuf[3];
      smallbuf[0] = *c;
      smallbuf[1] = *(c + 1);
      smallbuf[2] = '\0';

      errno = 0;
      int ch = static_cast<int>(strtoul(smallbuf, NULL, 16));
      if (errno != 0 && ch == 0) {
        return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                      "non-hex char in arg on 'A' pkt");
      }

      arg.push_back(ch);
      c += 2;
    }

    ctx.PushArgument(arg.c_str());
    if (*buf == ',')
      buf++;
  }
  SendPacket("OK");

  return rnb_success;
}

/* 'H c t'
 Set the thread for subsequent actions; 'c' for step/continue ops,
 'g' for other ops.  -1 means all threads, 0 means any thread.  */

rnb_err_t RNBRemote::HandlePacket_H(const char *p) {
  p++; // skip 'H'
  if (*p != 'c' && *p != 'g') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Missing 'c' or 'g' type in H packet");
  }

  if (!m_ctx.HasValidProcessID()) {
    // We allow gdb to connect to a server that hasn't started running
    // the target yet.  gdb still wants to ask questions about it and
    // freaks out if it gets an error.  So just return OK here.
  }

  errno = 0;
  nub_thread_t tid = strtoul(p + 1, NULL, 16);
  if (errno != 0 && tid == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid thread number in H packet");
  }
  if (*p == 'c')
    SetContinueThread(tid);
  if (*p == 'g')
    SetCurrentThread(tid);

  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_qLaunchSuccess(const char *p) {
  if (m_ctx.HasValidProcessID() || m_ctx.LaunchStatus().Status() == 0)
    return SendPacket("OK");
  std::ostringstream ret_str;
  std::string status_str;
  ret_str << "E" << m_ctx.LaunchStatusAsString(status_str);

  return SendPacket(ret_str.str());
}

rnb_err_t RNBRemote::HandlePacket_qShlibInfoAddr(const char *p) {
  if (m_ctx.HasValidProcessID()) {
    nub_addr_t shlib_info_addr =
        DNBProcessGetSharedLibraryInfoAddress(m_ctx.ProcessID());
    if (shlib_info_addr != INVALID_NUB_ADDRESS) {
      std::ostringstream ostrm;
      ostrm << RAW_HEXBASE << shlib_info_addr;
      return SendPacket(ostrm.str());
    }
  }
  return SendPacket("E44");
}

rnb_err_t RNBRemote::HandlePacket_qStepPacketSupported(const char *p) {
  // Normally the "s" packet is mandatory, yet in gdb when using ARM, they
  // get around the need for this packet by implementing software single
  // stepping from gdb. Current versions of debugserver do support the "s"
  // packet, yet some older versions do not. We need a way to tell if this
  // packet is supported so we can disable software single stepping in gdb
  // for remote targets (so the "s" packet will get used).
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_qSyncThreadStateSupported(const char *p) {
  // We support attachOrWait meaning attach if the process exists, otherwise
  // wait to attach.
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_qVAttachOrWaitSupported(const char *p) {
  // We support attachOrWait meaning attach if the process exists, otherwise
  // wait to attach.
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_qThreadStopInfo(const char *p) {
  p += strlen("qThreadStopInfo");
  nub_thread_t tid = strtoul(p, 0, 16);
  return SendStopReplyPacketForThread(tid);
}

rnb_err_t RNBRemote::HandlePacket_qThreadInfo(const char *p) {
  // We allow gdb to connect to a server that hasn't started running
  // the target yet.  gdb still wants to ask questions about it and
  // freaks out if it gets an error.  So just return OK here.
  nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("OK");

  // Only "qfThreadInfo" and "qsThreadInfo" get into this function so
  // we only need to check the second byte to tell which is which
  if (p[1] == 'f') {
    nub_size_t numthreads = DNBProcessGetNumThreads(pid);
    std::ostringstream ostrm;
    ostrm << "m";
    bool first = true;
    for (nub_size_t i = 0; i < numthreads; ++i) {
      if (first)
        first = false;
      else
        ostrm << ",";
      nub_thread_t th = DNBProcessGetThreadAtIndex(pid, i);
      ostrm << std::hex << th;
    }
    return SendPacket(ostrm.str());
  } else {
    return SendPacket("l");
  }
}

rnb_err_t RNBRemote::HandlePacket_qThreadExtraInfo(const char *p) {
  // We allow gdb to connect to a server that hasn't started running
  // the target yet.  gdb still wants to ask questions about it and
  // freaks out if it gets an error.  So just return OK here.
  nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("OK");

  /* This is supposed to return a string like 'Runnable' or
   'Blocked on Mutex'.
   The returned string is formatted like the "A" packet - a
   sequence of letters encoded in as 2-hex-chars-per-letter.  */
  p += strlen("qThreadExtraInfo");
  if (*p++ != ',')
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Illformed qThreadExtraInfo packet");
  errno = 0;
  nub_thread_t tid = strtoul(p, NULL, 16);
  if (errno != 0 && tid == 0) {
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p,
        "Invalid thread number in qThreadExtraInfo packet");
  }

  const char *threadInfo = DNBThreadGetInfo(pid, tid);
  if (threadInfo != NULL && threadInfo[0]) {
    return SendHexEncodedBytePacket(NULL, threadInfo, strlen(threadInfo), NULL);
  } else {
    // "OK" == 4f6b
    // Return "OK" as a ASCII hex byte stream if things go wrong
    return SendPacket("4f6b");
  }

  return SendPacket("");
}

const char *k_space_delimiters = " \t";
static void skip_spaces(std::string &line) {
  if (!line.empty()) {
    size_t space_pos = line.find_first_not_of(k_space_delimiters);
    if (space_pos > 0)
      line.erase(0, space_pos);
  }
}

static std::string get_identifier(std::string &line) {
  std::string word;
  skip_spaces(line);
  const size_t line_size = line.size();
  size_t end_pos;
  for (end_pos = 0; end_pos < line_size; ++end_pos) {
    if (end_pos == 0) {
      if (isalpha(line[end_pos]) || line[end_pos] == '_')
        continue;
    } else if (isalnum(line[end_pos]) || line[end_pos] == '_')
      continue;
    break;
  }
  word.assign(line, 0, end_pos);
  line.erase(0, end_pos);
  return word;
}

static std::string get_operator(std::string &line) {
  std::string op;
  skip_spaces(line);
  if (!line.empty()) {
    if (line[0] == '=') {
      op = '=';
      line.erase(0, 1);
    }
  }
  return op;
}

static std::string get_value(std::string &line) {
  std::string value;
  skip_spaces(line);
  if (!line.empty()) {
    value.swap(line);
  }
  return value;
}

extern void FileLogCallback(void *baton, uint32_t flags, const char *format,
                            va_list args);
extern void ASLLogCallback(void *baton, uint32_t flags, const char *format,
                           va_list args);

rnb_err_t RNBRemote::HandlePacket_qRcmd(const char *p) {
  const char *c = p + strlen("qRcmd,");
  std::string line;
  while (c[0] && c[1]) {
    char smallbuf[3] = {c[0], c[1], '\0'};
    errno = 0;
    int ch = static_cast<int>(strtoul(smallbuf, NULL, 16));
    if (errno != 0 && ch == 0)
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "non-hex char in payload of qRcmd packet");
    line.push_back(ch);
    c += 2;
  }
  if (*c == '\0') {
    std::string command = get_identifier(line);
    if (command == "set") {
      std::string variable = get_identifier(line);
      std::string op = get_operator(line);
      std::string value = get_value(line);
      if (variable == "logfile") {
        FILE *log_file = fopen(value.c_str(), "w");
        if (log_file) {
          DNBLogSetLogCallback(FileLogCallback, log_file);
          return SendPacket("OK");
        }
        return SendPacket("E71");
      } else if (variable == "logmask") {
        char *end;
        errno = 0;
        uint32_t logmask =
            static_cast<uint32_t>(strtoul(value.c_str(), &end, 0));
        if (errno == 0 && end && *end == '\0') {
          DNBLogSetLogMask(logmask);
          if (!DNBLogGetLogCallback())
            DNBLogSetLogCallback(ASLLogCallback, NULL);
          return SendPacket("OK");
        }
        errno = 0;
        logmask = static_cast<uint32_t>(strtoul(value.c_str(), &end, 16));
        if (errno == 0 && end && *end == '\0') {
          DNBLogSetLogMask(logmask);
          return SendPacket("OK");
        }
        return SendPacket("E72");
      }
      return SendPacket("E70");
    }
    return SendPacket("E69");
  }
  return SendPacket("E73");
}

rnb_err_t RNBRemote::HandlePacket_qC(const char *p) {
  nub_thread_t tid;
  std::ostringstream rep;
  // If we haven't run the process yet, we tell the debugger the
  // pid is 0.  That way it can know to tell use to run later on.
  if (!m_ctx.HasValidProcessID())
    tid = 0;
  else {
    // Grab the current thread.
    tid = DNBProcessGetCurrentThread(m_ctx.ProcessID());
    // Make sure we set the current thread so g and p packets return
    // the data the gdb will expect.
    SetCurrentThread(tid);
  }
  rep << "QC" << std::hex << tid;
  return SendPacket(rep.str());
}

rnb_err_t RNBRemote::HandlePacket_qEcho(const char *p) {
  // Just send the exact same packet back that we received to
  // synchronize the response packets after a previous packet
  // timed out. This allows the debugger to get back on track
  // with responses after a packet timeout.
  return SendPacket(p);
}

rnb_err_t RNBRemote::HandlePacket_qGetPid(const char *p) {
  nub_process_t pid;
  std::ostringstream rep;
  // If we haven't run the process yet, we tell the debugger the
  // pid is 0.  That way it can know to tell use to run later on.
  if (m_ctx.HasValidProcessID())
    pid = m_ctx.ProcessID();
  else
    pid = 0;
  rep << std::hex << pid;
  return SendPacket(rep.str());
}

rnb_err_t RNBRemote::HandlePacket_qRegisterInfo(const char *p) {
  if (g_num_reg_entries == 0)
    InitializeRegisters();

  p += strlen("qRegisterInfo");

  nub_size_t num_reg_sets = 0;
  const DNBRegisterSetInfo *reg_set_info = DNBGetRegisterSetInfo(&num_reg_sets);
  uint32_t reg_num = static_cast<uint32_t>(strtoul(p, 0, 16));

  if (reg_num < g_num_reg_entries) {
    const register_map_entry_t *reg_entry = &g_reg_entries[reg_num];
    std::ostringstream ostrm;
    if (reg_entry->nub_info.name)
      ostrm << "name:" << reg_entry->nub_info.name << ';';
    if (reg_entry->nub_info.alt)
      ostrm << "alt-name:" << reg_entry->nub_info.alt << ';';

    ostrm << "bitsize:" << std::dec << reg_entry->nub_info.size * 8 << ';';
    ostrm << "offset:" << std::dec << reg_entry->offset << ';';

    switch (reg_entry->nub_info.type) {
    case Uint:
      ostrm << "encoding:uint;";
      break;
    case Sint:
      ostrm << "encoding:sint;";
      break;
    case IEEE754:
      ostrm << "encoding:ieee754;";
      break;
    case Vector:
      ostrm << "encoding:vector;";
      break;
    }

    switch (reg_entry->nub_info.format) {
    case Binary:
      ostrm << "format:binary;";
      break;
    case Decimal:
      ostrm << "format:decimal;";
      break;
    case Hex:
      ostrm << "format:hex;";
      break;
    case Float:
      ostrm << "format:float;";
      break;
    case VectorOfSInt8:
      ostrm << "format:vector-sint8;";
      break;
    case VectorOfUInt8:
      ostrm << "format:vector-uint8;";
      break;
    case VectorOfSInt16:
      ostrm << "format:vector-sint16;";
      break;
    case VectorOfUInt16:
      ostrm << "format:vector-uint16;";
      break;
    case VectorOfSInt32:
      ostrm << "format:vector-sint32;";
      break;
    case VectorOfUInt32:
      ostrm << "format:vector-uint32;";
      break;
    case VectorOfFloat32:
      ostrm << "format:vector-float32;";
      break;
    case VectorOfUInt128:
      ostrm << "format:vector-uint128;";
      break;
    };

    if (reg_set_info && reg_entry->nub_info.set < num_reg_sets)
      ostrm << "set:" << reg_set_info[reg_entry->nub_info.set].name << ';';

    if (reg_entry->nub_info.reg_ehframe != INVALID_NUB_REGNUM)
      ostrm << "ehframe:" << std::dec << reg_entry->nub_info.reg_ehframe << ';';

    if (reg_entry->nub_info.reg_dwarf != INVALID_NUB_REGNUM)
      ostrm << "dwarf:" << std::dec << reg_entry->nub_info.reg_dwarf << ';';

    switch (reg_entry->nub_info.reg_generic) {
    case GENERIC_REGNUM_FP:
      ostrm << "generic:fp;";
      break;
    case GENERIC_REGNUM_PC:
      ostrm << "generic:pc;";
      break;
    case GENERIC_REGNUM_SP:
      ostrm << "generic:sp;";
      break;
    case GENERIC_REGNUM_RA:
      ostrm << "generic:ra;";
      break;
    case GENERIC_REGNUM_FLAGS:
      ostrm << "generic:flags;";
      break;
    case GENERIC_REGNUM_ARG1:
      ostrm << "generic:arg1;";
      break;
    case GENERIC_REGNUM_ARG2:
      ostrm << "generic:arg2;";
      break;
    case GENERIC_REGNUM_ARG3:
      ostrm << "generic:arg3;";
      break;
    case GENERIC_REGNUM_ARG4:
      ostrm << "generic:arg4;";
      break;
    case GENERIC_REGNUM_ARG5:
      ostrm << "generic:arg5;";
      break;
    case GENERIC_REGNUM_ARG6:
      ostrm << "generic:arg6;";
      break;
    case GENERIC_REGNUM_ARG7:
      ostrm << "generic:arg7;";
      break;
    case GENERIC_REGNUM_ARG8:
      ostrm << "generic:arg8;";
      break;
    default:
      break;
    }

    if (!reg_entry->value_regnums.empty()) {
      ostrm << "container-regs:";
      for (size_t i = 0, n = reg_entry->value_regnums.size(); i < n; ++i) {
        if (i > 0)
          ostrm << ',';
        ostrm << RAW_HEXBASE << reg_entry->value_regnums[i];
      }
      ostrm << ';';
    }

    if (!reg_entry->invalidate_regnums.empty()) {
      ostrm << "invalidate-regs:";
      for (size_t i = 0, n = reg_entry->invalidate_regnums.size(); i < n; ++i) {
        if (i > 0)
          ostrm << ',';
        ostrm << RAW_HEXBASE << reg_entry->invalidate_regnums[i];
      }
      ostrm << ';';
    }

    return SendPacket(ostrm.str());
  }
  return SendPacket("E45");
}

/* This expects a packet formatted like

 QSetLogging:bitmask=LOG_ALL|LOG_RNB_REMOTE;

 with the "QSetLogging:" already removed from the start.  Maybe in the
 future this packet will include other keyvalue pairs like

 QSetLogging:bitmask=LOG_ALL;mode=asl;
 */

rnb_err_t set_logging(const char *p) {
  int bitmask = 0;
  while (p && *p != '\0') {
    if (strncmp(p, "bitmask=", sizeof("bitmask=") - 1) == 0) {
      p += sizeof("bitmask=") - 1;
      while (p && *p != '\0' && *p != ';') {
        if (*p == '|')
          p++;

        // to regenerate the LOG_ entries (not including the LOG_RNB entries)
        // $ for logname in `grep '^#define LOG_' DNBDefs.h | egrep -v
        // 'LOG_HI|LOG_LO' | awk '{print $2}'`
        // do
        //   echo "                else if (strncmp (p, \"$logname\", sizeof
        //   (\"$logname\") - 1) == 0)"
        //   echo "                {"
        //   echo "                    p += sizeof (\"$logname\") - 1;"
        //   echo "                    bitmask |= $logname;"
        //   echo "                }"
        // done
        if (strncmp(p, "LOG_VERBOSE", sizeof("LOG_VERBOSE") - 1) == 0) {
          p += sizeof("LOG_VERBOSE") - 1;
          bitmask |= LOG_VERBOSE;
        } else if (strncmp(p, "LOG_PROCESS", sizeof("LOG_PROCESS") - 1) == 0) {
          p += sizeof("LOG_PROCESS") - 1;
          bitmask |= LOG_PROCESS;
        } else if (strncmp(p, "LOG_THREAD", sizeof("LOG_THREAD") - 1) == 0) {
          p += sizeof("LOG_THREAD") - 1;
          bitmask |= LOG_THREAD;
        } else if (strncmp(p, "LOG_EXCEPTIONS", sizeof("LOG_EXCEPTIONS") - 1) ==
                   0) {
          p += sizeof("LOG_EXCEPTIONS") - 1;
          bitmask |= LOG_EXCEPTIONS;
        } else if (strncmp(p, "LOG_SHLIB", sizeof("LOG_SHLIB") - 1) == 0) {
          p += sizeof("LOG_SHLIB") - 1;
          bitmask |= LOG_SHLIB;
        } else if (strncmp(p, "LOG_MEMORY_DATA_SHORT",
                           sizeof("LOG_MEMORY_DATA_SHORT") - 1) == 0) {
          p += sizeof("LOG_MEMORY_DATA_SHORT") - 1;
          bitmask |= LOG_MEMORY_DATA_SHORT;
        } else if (strncmp(p, "LOG_MEMORY_DATA_LONG",
                           sizeof("LOG_MEMORY_DATA_LONG") - 1) == 0) {
          p += sizeof("LOG_MEMORY_DATA_LONG") - 1;
          bitmask |= LOG_MEMORY_DATA_LONG;
        } else if (strncmp(p, "LOG_MEMORY_PROTECTIONS",
                           sizeof("LOG_MEMORY_PROTECTIONS") - 1) == 0) {
          p += sizeof("LOG_MEMORY_PROTECTIONS") - 1;
          bitmask |= LOG_MEMORY_PROTECTIONS;
        } else if (strncmp(p, "LOG_MEMORY", sizeof("LOG_MEMORY") - 1) == 0) {
          p += sizeof("LOG_MEMORY") - 1;
          bitmask |= LOG_MEMORY;
        } else if (strncmp(p, "LOG_BREAKPOINTS",
                           sizeof("LOG_BREAKPOINTS") - 1) == 0) {
          p += sizeof("LOG_BREAKPOINTS") - 1;
          bitmask |= LOG_BREAKPOINTS;
        } else if (strncmp(p, "LOG_EVENTS", sizeof("LOG_EVENTS") - 1) == 0) {
          p += sizeof("LOG_EVENTS") - 1;
          bitmask |= LOG_EVENTS;
        } else if (strncmp(p, "LOG_WATCHPOINTS",
                           sizeof("LOG_WATCHPOINTS") - 1) == 0) {
          p += sizeof("LOG_WATCHPOINTS") - 1;
          bitmask |= LOG_WATCHPOINTS;
        } else if (strncmp(p, "LOG_STEP", sizeof("LOG_STEP") - 1) == 0) {
          p += sizeof("LOG_STEP") - 1;
          bitmask |= LOG_STEP;
        } else if (strncmp(p, "LOG_TASK", sizeof("LOG_TASK") - 1) == 0) {
          p += sizeof("LOG_TASK") - 1;
          bitmask |= LOG_TASK;
        } else if (strncmp(p, "LOG_ALL", sizeof("LOG_ALL") - 1) == 0) {
          p += sizeof("LOG_ALL") - 1;
          bitmask |= LOG_ALL;
        } else if (strncmp(p, "LOG_DEFAULT", sizeof("LOG_DEFAULT") - 1) == 0) {
          p += sizeof("LOG_DEFAULT") - 1;
          bitmask |= LOG_DEFAULT;
        }
        // end of auto-generated entries

        else if (strncmp(p, "LOG_NONE", sizeof("LOG_NONE") - 1) == 0) {
          p += sizeof("LOG_NONE") - 1;
          bitmask = 0;
        } else if (strncmp(p, "LOG_RNB_MINIMAL",
                           sizeof("LOG_RNB_MINIMAL") - 1) == 0) {
          p += sizeof("LOG_RNB_MINIMAL") - 1;
          bitmask |= LOG_RNB_MINIMAL;
        } else if (strncmp(p, "LOG_RNB_MEDIUM", sizeof("LOG_RNB_MEDIUM") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_MEDIUM") - 1;
          bitmask |= LOG_RNB_MEDIUM;
        } else if (strncmp(p, "LOG_RNB_MAX", sizeof("LOG_RNB_MAX") - 1) == 0) {
          p += sizeof("LOG_RNB_MAX") - 1;
          bitmask |= LOG_RNB_MAX;
        } else if (strncmp(p, "LOG_RNB_COMM", sizeof("LOG_RNB_COMM") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_COMM") - 1;
          bitmask |= LOG_RNB_COMM;
        } else if (strncmp(p, "LOG_RNB_REMOTE", sizeof("LOG_RNB_REMOTE") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_REMOTE") - 1;
          bitmask |= LOG_RNB_REMOTE;
        } else if (strncmp(p, "LOG_RNB_EVENTS", sizeof("LOG_RNB_EVENTS") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_EVENTS") - 1;
          bitmask |= LOG_RNB_EVENTS;
        } else if (strncmp(p, "LOG_RNB_PROC", sizeof("LOG_RNB_PROC") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_PROC") - 1;
          bitmask |= LOG_RNB_PROC;
        } else if (strncmp(p, "LOG_RNB_PACKETS",
                           sizeof("LOG_RNB_PACKETS") - 1) == 0) {
          p += sizeof("LOG_RNB_PACKETS") - 1;
          bitmask |= LOG_RNB_PACKETS;
        } else if (strncmp(p, "LOG_RNB_ALL", sizeof("LOG_RNB_ALL") - 1) == 0) {
          p += sizeof("LOG_RNB_ALL") - 1;
          bitmask |= LOG_RNB_ALL;
        } else if (strncmp(p, "LOG_RNB_DEFAULT",
                           sizeof("LOG_RNB_DEFAULT") - 1) == 0) {
          p += sizeof("LOG_RNB_DEFAULT") - 1;
          bitmask |= LOG_RNB_DEFAULT;
        } else if (strncmp(p, "LOG_DARWIN_LOG", sizeof("LOG_DARWIN_LOG") - 1) ==
                   0) {
          p += sizeof("LOG_DARWIN_LOG") - 1;
          bitmask |= LOG_DARWIN_LOG;
        } else if (strncmp(p, "LOG_RNB_NONE", sizeof("LOG_RNB_NONE") - 1) ==
                   0) {
          p += sizeof("LOG_RNB_NONE") - 1;
          bitmask = 0;
        } else {
          /* Unrecognized logging bit; ignore it.  */
          const char *c = strchr(p, '|');
          if (c) {
            p = c;
          } else {
            c = strchr(p, ';');
            if (c) {
              p = c;
            } else {
              // Improperly terminated word; just go to end of str
              p = strchr(p, '\0');
            }
          }
        }
      }
      // Did we get a properly formatted logging bitmask?
      if (p && *p == ';') {
        // Enable DNB logging.
        // Use the existing log callback if one was already configured.
        if (!DNBLogGetLogCallback()) {
          // Use the os_log()-based logger if available; otherwise,
          // fallback to ASL.
          auto log_callback = OsLogger::GetLogFunction();
          if (log_callback)
            DNBLogSetLogCallback(log_callback, nullptr);
          else
            DNBLogSetLogCallback(ASLLogCallback, nullptr);
        }

        // Update logging to use the configured log channel bitmask.
        DNBLogSetLogMask(bitmask);
        p++;
      }
    }
// We're not going to support logging to a file for now.  All logging
// goes through ASL or the previously arranged log callback.
#if 0
        else if (strncmp (p, "mode=", sizeof ("mode=") - 1) == 0)
        {
            p += sizeof ("mode=") - 1;
            if (strncmp (p, "asl;", sizeof ("asl;") - 1) == 0)
            {
                DNBLogToASL ();
                p += sizeof ("asl;") - 1;
            }
            else if (strncmp (p, "file;", sizeof ("file;") - 1) == 0)
            {
                DNBLogToFile ();
                p += sizeof ("file;") - 1;
            }
            else
            {
                // Ignore unknown argument
                const char *c = strchr (p, ';');
                if (c)
                    p = c + 1;
                else
                    p = strchr (p, '\0');
            }
        }
        else if (strncmp (p, "filename=", sizeof ("filename=") - 1) == 0)
        {
            p += sizeof ("filename=") - 1;
            const char *c = strchr (p, ';');
            if (c == NULL)
            {
                c = strchr (p, '\0');
                continue;
            }
            char *fn = (char *) alloca (c - p + 1);
            strlcpy (fn, p, c - p);
            fn[c - p] = '\0';

            // A file name of "asl" is special and is another way to indicate
            // that logging should be done via ASL, not by file.
            if (strcmp (fn, "asl") == 0)
            {
                DNBLogToASL ();
            }
            else
            {
                FILE *f = fopen (fn, "w");
                if (f)
                {
                    DNBLogSetLogFile (f);
                    DNBEnableLogging (f, DNBLogGetLogMask ());
                    DNBLogToFile ();
                }
            }
            p = c + 1;
        }
#endif /* #if 0 to enforce ASL logging only.  */
    else {
      // Ignore unknown argument
      const char *c = strchr(p, ';');
      if (c)
        p = c + 1;
      else
        p = strchr(p, '\0');
    }
  }

  return rnb_success;
}

rnb_err_t RNBRemote::HandlePacket_QThreadSuffixSupported(const char *p) {
  m_thread_suffix_supported = true;
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QStartNoAckMode(const char *p) {
  // Send the OK packet first so the correct checksum is appended...
  rnb_err_t result = SendPacket("OK");
  m_noack_mode = true;
  return result;
}

rnb_err_t RNBRemote::HandlePacket_QSetLogging(const char *p) {
  p += sizeof("QSetLogging:") - 1;
  rnb_err_t result = set_logging(p);
  if (result == rnb_success)
    return SendPacket("OK");
  else
    return SendPacket("E35");
}

rnb_err_t RNBRemote::HandlePacket_QSetDisableASLR(const char *p) {
  extern int g_disable_aslr;
  p += sizeof("QSetDisableASLR:") - 1;
  switch (*p) {
  case '0':
    g_disable_aslr = 0;
    break;
  case '1':
    g_disable_aslr = 1;
    break;
  default:
    return SendPacket("E56");
  }
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QSetSTDIO(const char *p) {
  // Only set stdin/out/err if we don't already have a process
  if (!m_ctx.HasValidProcessID()) {
    bool success = false;
    // Check the seventh character since the packet will be one of:
    // QSetSTDIN
    // QSetSTDOUT
    // QSetSTDERR
    StdStringExtractor packet(p);
    packet.SetFilePos(7);
    char ch = packet.GetChar();
    while (packet.GetChar() != ':')
      /* Do nothing. */;

    switch (ch) {
    case 'I': // STDIN
      packet.GetHexByteString(m_ctx.GetSTDIN());
      success = !m_ctx.GetSTDIN().empty();
      break;

    case 'O': // STDOUT
      packet.GetHexByteString(m_ctx.GetSTDOUT());
      success = !m_ctx.GetSTDOUT().empty();
      break;

    case 'E': // STDERR
      packet.GetHexByteString(m_ctx.GetSTDERR());
      success = !m_ctx.GetSTDERR().empty();
      break;

    default:
      break;
    }
    if (success)
      return SendPacket("OK");
    return SendPacket("E57");
  }
  return SendPacket("E58");
}

rnb_err_t RNBRemote::HandlePacket_QSetWorkingDir(const char *p) {
  // Only set the working directory if we don't already have a process
  if (!m_ctx.HasValidProcessID()) {
    StdStringExtractor packet(p += sizeof("QSetWorkingDir:") - 1);
    if (packet.GetHexByteString(m_ctx.GetWorkingDir())) {
      struct stat working_dir_stat;
      if (::stat(m_ctx.GetWorkingDirPath(), &working_dir_stat) == -1) {
        m_ctx.GetWorkingDir().clear();
        return SendPacket("E61"); // Working directory doesn't exist...
      } else if ((working_dir_stat.st_mode & S_IFMT) == S_IFDIR) {
        return SendPacket("OK");
      } else {
        m_ctx.GetWorkingDir().clear();
        return SendPacket("E62"); // Working directory isn't a directory...
      }
    }
    return SendPacket("E59"); // Invalid path
  }
  return SendPacket(
      "E60"); // Already had a process, too late to set working dir
}

rnb_err_t RNBRemote::HandlePacket_QSyncThreadState(const char *p) {
  if (!m_ctx.HasValidProcessID()) {
    // We allow gdb to connect to a server that hasn't started running
    // the target yet.  gdb still wants to ask questions about it and
    // freaks out if it gets an error.  So just return OK here.
    return SendPacket("OK");
  }

  errno = 0;
  p += strlen("QSyncThreadState:");
  nub_thread_t tid = strtoul(p, NULL, 16);
  if (errno != 0 && tid == 0) {
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p,
        "Invalid thread number in QSyncThreadState packet");
  }
  if (DNBProcessSyncThreadState(m_ctx.ProcessID(), tid))
    return SendPacket("OK");
  else
    return SendPacket("E61");
}

rnb_err_t RNBRemote::HandlePacket_QSetDetachOnError(const char *p) {
  p += sizeof("QSetDetachOnError:") - 1;
  bool should_detach = true;
  switch (*p) {
  case '0':
    should_detach = false;
    break;
  case '1':
    should_detach = true;
    break;
  default:
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p,
        "Invalid value for QSetDetachOnError - should be 0 or 1");
    break;
  }

  m_ctx.SetDetachOnError(should_detach);
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_qStructuredDataPlugins(const char *p) {
  // We'll return a JSON array of supported packet types.
  // The type is significant.  For each of the supported
  // packet types that have been enabled, there will be a
  // 'J' async packet sent to the client with payload data.
  // This payload data will be a JSON dictionary, and the
  // top level dictionary will contain a string field with
  // its value set to the relevant packet type from this list.
  JSONGenerator::Array supported_json_packets;

  // Check for DarwinLog (libtrace os_log/activity support).
  if (DarwinLogCollector::IsSupported())
    supported_json_packets.AddItem(
        JSONGenerator::StringSP(new JSONGenerator::String("DarwinLog")));

  // Send back the array.
  std::ostringstream stream;
  supported_json_packets.Dump(stream);
  return SendPacket(stream.str());
}

rnb_err_t RNBRemote::HandlePacket_QConfigureDarwinLog(const char *p) {
  if (!DarwinLogCollector::IsSupported()) {
    // We should never have been given this request.
    return SendPacket("E89");
  }

  // Ensure we have a process.  We expect a separate configure request for
  // each process launched/attached.
  const nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E94");

  // Get the configuration dictionary.
  p += strlen("QConfigureDarwinLog:");

  // The configuration dictionary is binary encoded.
  std::vector<uint8_t> unescaped_config_data = decode_binary_data(p, -1);
  std::string unescaped_config_string((const char *)&unescaped_config_data[0],
                                      unescaped_config_data.size());
  DNBLogThreadedIf(LOG_DARWIN_LOG, "DarwinLog: received config data: \"%s\"",
                   unescaped_config_string.c_str());
  auto configuration_sp =
      JSONParser(unescaped_config_string.c_str()).ParseJSONValue();
  if (!configuration_sp) {
    // Malformed request - we require configuration data
    // indicating whether we're enabling or disabling.
    return SendPacket("E90");
  }

  if (!JSONObject::classof(configuration_sp.get())) {
    // Configuration data is not of the right type.
    return SendPacket("E91");
  }
  JSONObject &config_dict = *static_cast<JSONObject *>(configuration_sp.get());

  // Check if we're enabling or disabling.
  auto enabled_sp = config_dict.GetObject("enabled");
  if (!enabled_sp) {
    // Missing required "enabled" field.
    return SendPacket("E92");
  }
  if (!JSONTrue::classof(enabled_sp.get()) &&
      !JSONFalse::classof(enabled_sp.get())) {
    // Should be a boolean type, but wasn't.
    return SendPacket("E93");
  }
  const bool enabling = JSONTrue::classof(enabled_sp.get());

  // TODO - handle other configuration parameters here.

  // Shut down any active activity stream for the process.
  DarwinLogCollector::CancelStreamForProcess(pid);

  if (enabling) {
    // Look up the procecess.
    if (!DarwinLogCollector::StartCollectingForProcess(pid, config_dict))
      return SendPacket("E95");
  }

  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QListThreadsInStopReply(const char *p) {
  // If this packet is received, it allows us to send an extra key/value
  // pair in the stop reply packets where we will list all of the thread IDs
  // separated by commas:
  //
  //  "threads:10a,10b,10c;"
  //
  // This will get included in the stop reply packet as something like:
  //
  //  "T11thread:10a;00:00000000;01:00010203:threads:10a,10b,10c;"
  //
  // This can save two packets on each stop: qfThreadInfo/qsThreadInfo and
  // speed things up a bit.
  //
  // Send the OK packet first so the correct checksum is appended...
  rnb_err_t result = SendPacket("OK");
  m_list_threads_in_stop_reply = true;

  return result;
}

rnb_err_t RNBRemote::HandlePacket_QSetMaxPayloadSize(const char *p) {
  /* The number of characters in a packet payload that gdb is
   prepared to accept.  The packet-start char, packet-end char,
   2 checksum chars and terminating null character are not included
   in this size.  */
  p += sizeof("QSetMaxPayloadSize:") - 1;
  errno = 0;
  uint32_t size = static_cast<uint32_t>(strtoul(p, NULL, 16));
  if (errno != 0 && size == 0) {
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p, "Invalid length in QSetMaxPayloadSize packet");
  }
  m_max_payload_size = size;
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QSetMaxPacketSize(const char *p) {
  /* This tells us the largest packet that gdb can handle.
   i.e. the size of gdb's packet-reading buffer.
   QSetMaxPayloadSize is preferred because it is less ambiguous.  */
  p += sizeof("QSetMaxPacketSize:") - 1;
  errno = 0;
  uint32_t size = static_cast<uint32_t>(strtoul(p, NULL, 16));
  if (errno != 0 && size == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in QSetMaxPacketSize packet");
  }
  m_max_payload_size = size - 5;
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QEnvironment(const char *p) {
  /* This sets the environment for the target program.  The packet is of the
   form:

   QEnvironment:VARIABLE=VALUE

   */

  DNBLogThreadedIf(
      LOG_RNB_REMOTE, "%8u RNBRemote::%s Handling QEnvironment: \"%s\"",
      (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__, p);

  p += sizeof("QEnvironment:") - 1;
  RNBContext &ctx = Context();

  ctx.PushEnvironment(p);
  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QEnvironmentHexEncoded(const char *p) {
  /* This sets the environment for the target program.  The packet is of the
     form:

      QEnvironmentHexEncoded:VARIABLE=VALUE

      The VARIABLE=VALUE part is sent hex-encoded so characters like '#' with
     special
      meaning in the remote protocol won't break it.
  */

  DNBLogThreadedIf(LOG_RNB_REMOTE,
                   "%8u RNBRemote::%s Handling QEnvironmentHexEncoded: \"%s\"",
                   (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true),
                   __FUNCTION__, p);

  p += sizeof("QEnvironmentHexEncoded:") - 1;

  std::string arg;
  const char *c;
  c = p;
  while (*c != '\0') {
    if (*(c + 1) == '\0') {
      return HandlePacket_ILLFORMED(
          __FILE__, __LINE__, p,
          "non-hex char in arg on 'QEnvironmentHexEncoded' pkt");
    }
    char smallbuf[3];
    smallbuf[0] = *c;
    smallbuf[1] = *(c + 1);
    smallbuf[2] = '\0';
    errno = 0;
    int ch = static_cast<int>(strtoul(smallbuf, NULL, 16));
    if (errno != 0 && ch == 0) {
      return HandlePacket_ILLFORMED(
          __FILE__, __LINE__, p,
          "non-hex char in arg on 'QEnvironmentHexEncoded' pkt");
    }
    arg.push_back(ch);
    c += 2;
  }

  RNBContext &ctx = Context();
  if (arg.length() > 0)
    ctx.PushEnvironment(arg.c_str());

  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_QLaunchArch(const char *p) {
  p += sizeof("QLaunchArch:") - 1;
  if (DNBSetArchitecture(p))
    return SendPacket("OK");
  return SendPacket("E63");
}

rnb_err_t RNBRemote::HandlePacket_QSetProcessEvent(const char *p) {
  p += sizeof("QSetProcessEvent:") - 1;
  // If the process is running, then send the event to the process, otherwise
  // store it in the context.
  if (Context().HasValidProcessID()) {
    if (DNBProcessSendEvent(Context().ProcessID(), p))
      return SendPacket("OK");
    else
      return SendPacket("E80");
  } else {
    Context().PushProcessEvent(p);
  }
  return SendPacket("OK");
}

void append_hex_value(std::ostream &ostrm, const void *buf, size_t buf_size,
                      bool swap) {
  int i;
  const uint8_t *p = (const uint8_t *)buf;
  if (swap) {
    for (i = static_cast<int>(buf_size) - 1; i >= 0; i--)
      ostrm << RAWHEX8(p[i]);
  } else {
    for (size_t i = 0; i < buf_size; i++)
      ostrm << RAWHEX8(p[i]);
  }
}

std::string cstring_to_asciihex_string(const char *str) {
  std::string hex_str;
  hex_str.reserve (strlen (str) * 2);
  while (str && *str) {
    char hexbuf[5];
    snprintf (hexbuf, sizeof(hexbuf), "%02x", *str++);
    hex_str += hexbuf;
  }
  return hex_str;
}

void append_hexified_string(std::ostream &ostrm, const std::string &string) {
  size_t string_size = string.size();
  const char *string_buf = string.c_str();
  for (size_t i = 0; i < string_size; i++) {
    ostrm << RAWHEX8(*(string_buf + i));
  }
}

void register_value_in_hex_fixed_width(std::ostream &ostrm, nub_process_t pid,
                                       nub_thread_t tid,
                                       const register_map_entry_t *reg,
                                       const DNBRegisterValue *reg_value_ptr) {
  if (reg != NULL) {
    DNBRegisterValue reg_value;
    if (reg_value_ptr == NULL) {
      if (DNBThreadGetRegisterValueByID(pid, tid, reg->nub_info.set,
                                        reg->nub_info.reg, &reg_value))
        reg_value_ptr = &reg_value;
    }

    if (reg_value_ptr) {
      append_hex_value(ostrm, reg_value_ptr->value.v_uint8, reg->nub_info.size,
                       false);
    } else {
      // If we fail to read a register value, check if it has a default
      // fail value. If it does, return this instead in case some of
      // the registers are not available on the current system.
      if (reg->nub_info.size > 0) {
        std::basic_string<uint8_t> zeros(reg->nub_info.size, '\0');
        append_hex_value(ostrm, zeros.data(), zeros.size(), false);
      }
    }
  }
}

void debugserver_regnum_with_fixed_width_hex_register_value(
    std::ostream &ostrm, nub_process_t pid, nub_thread_t tid,
    const register_map_entry_t *reg, const DNBRegisterValue *reg_value_ptr) {
  // Output the register number as 'NN:VVVVVVVV;' where NN is a 2 bytes HEX
  // gdb register number, and VVVVVVVV is the correct number of hex bytes
  // as ASCII for the register value.
  if (reg != NULL) {
    ostrm << RAWHEX8(reg->debugserver_regnum) << ':';
    register_value_in_hex_fixed_width(ostrm, pid, tid, reg, reg_value_ptr);
    ostrm << ';';
  }
}

void RNBRemote::DispatchQueueOffsets::GetThreadQueueInfo(
    nub_process_t pid, nub_addr_t dispatch_qaddr, nub_addr_t &dispatch_queue_t,
    std::string &queue_name, uint64_t &queue_width,
    uint64_t &queue_serialnum) const {
  queue_name.clear();
  queue_width = 0;
  queue_serialnum = 0;

  if (IsValid() && dispatch_qaddr != INVALID_NUB_ADDRESS &&
      dispatch_qaddr != 0) {
    dispatch_queue_t = DNBProcessMemoryReadPointer(pid, dispatch_qaddr);
    if (dispatch_queue_t) {
      queue_width = DNBProcessMemoryReadInteger(
          pid, dispatch_queue_t + dqo_width, dqo_width_size, 0);
      queue_serialnum = DNBProcessMemoryReadInteger(
          pid, dispatch_queue_t + dqo_serialnum, dqo_serialnum_size, 0);

      if (dqo_version >= 4) {
        // libdispatch versions 4+, pointer to dispatch name is in the
        // queue structure.
        nub_addr_t pointer_to_label_address = dispatch_queue_t + dqo_label;
        nub_addr_t label_addr =
            DNBProcessMemoryReadPointer(pid, pointer_to_label_address);
        if (label_addr)
          queue_name = DNBProcessMemoryReadCString(pid, label_addr);
      } else {
        // libdispatch versions 1-3, dispatch name is a fixed width char array
        // in the queue structure.
        queue_name = DNBProcessMemoryReadCStringFixed(
            pid, dispatch_queue_t + dqo_label, dqo_label_size);
      }
    }
  }
}

struct StackMemory {
  uint8_t bytes[2 * sizeof(nub_addr_t)];
  nub_size_t length;
};
typedef std::map<nub_addr_t, StackMemory> StackMemoryMap;

static void ReadStackMemory(nub_process_t pid, nub_thread_t tid,
                            StackMemoryMap &stack_mmap,
                            uint32_t backtrace_limit = 256) {
  DNBRegisterValue reg_value;
  if (DNBThreadGetRegisterValueByID(pid, tid, REGISTER_SET_GENERIC,
                                    GENERIC_REGNUM_FP, &reg_value)) {
    uint32_t frame_count = 0;
    uint64_t fp = 0;
    if (reg_value.info.size == 4)
      fp = reg_value.value.uint32;
    else
      fp = reg_value.value.uint64;
    while (fp != 0) {
      // Make sure we never recurse more than 256 times so we don't recurse too
      // far or
      // store up too much memory in the expedited cache
      if (++frame_count > backtrace_limit)
        break;

      const nub_size_t read_size = reg_value.info.size * 2;
      StackMemory stack_memory;
      stack_memory.length = read_size;
      if (DNBProcessMemoryRead(pid, fp, read_size, stack_memory.bytes) !=
          read_size)
        break;
      // Make sure we don't try to put the same stack memory in more than once
      if (stack_mmap.find(fp) != stack_mmap.end())
        break;
      // Put the entry into the cache
      stack_mmap[fp] = stack_memory;
      // Dereference the frame pointer to get to the previous frame pointer
      if (reg_value.info.size == 4)
        fp = ((uint32_t *)stack_memory.bytes)[0];
      else
        fp = ((uint64_t *)stack_memory.bytes)[0];
    }
  }
}

rnb_err_t RNBRemote::SendStopReplyPacketForThread(nub_thread_t tid) {
  const nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E50");

  struct DNBThreadStopInfo tid_stop_info;

  /* Fill the remaining space in this packet with as many registers
   as we can stuff in there.  */

  if (DNBThreadGetStopReason(pid, tid, &tid_stop_info)) {
    const bool did_exec = tid_stop_info.reason == eStopTypeExec;
    if (did_exec) {
      RNBRemote::InitializeRegisters(true);

      // Reset any symbols that need resetting when we exec
      m_dispatch_queue_offsets_addr = INVALID_NUB_ADDRESS;
      m_dispatch_queue_offsets.Clear();
    }

    std::ostringstream ostrm;
    // Output the T packet with the thread
    ostrm << 'T';
    int signum = tid_stop_info.details.signal.signo;
    DNBLogThreadedIf(
        LOG_RNB_PROC, "%8d %s got signal signo = %u, exc_type = %u",
        (uint32_t)m_comm.Timer().ElapsedMicroSeconds(true), __FUNCTION__,
        signum, tid_stop_info.details.exception.type);

    // Translate any mach exceptions to gdb versions, unless they are
    // common exceptions like a breakpoint or a soft signal.
    switch (tid_stop_info.details.exception.type) {
    default:
      signum = 0;
      break;
    case EXC_BREAKPOINT:
      signum = SIGTRAP;
      break;
    case EXC_BAD_ACCESS:
      signum = TARGET_EXC_BAD_ACCESS;
      break;
    case EXC_BAD_INSTRUCTION:
      signum = TARGET_EXC_BAD_INSTRUCTION;
      break;
    case EXC_ARITHMETIC:
      signum = TARGET_EXC_ARITHMETIC;
      break;
    case EXC_EMULATION:
      signum = TARGET_EXC_EMULATION;
      break;
    case EXC_SOFTWARE:
      if (tid_stop_info.details.exception.data_count == 2 &&
          tid_stop_info.details.exception.data[0] == EXC_SOFT_SIGNAL)
        signum = static_cast<int>(tid_stop_info.details.exception.data[1]);
      else
        signum = TARGET_EXC_SOFTWARE;
      break;
    }

    ostrm << RAWHEX8(signum & 0xff);

    ostrm << std::hex << "thread:" << tid << ';';

    const char *thread_name = DNBThreadGetName(pid, tid);
    if (thread_name && thread_name[0]) {
      size_t thread_name_len = strlen(thread_name);

      if (::strcspn(thread_name, "$#+-;:") == thread_name_len)
        ostrm << std::hex << "name:" << thread_name << ';';
      else {
        // the thread name contains special chars, send as hex bytes
        ostrm << std::hex << "hexname:";
        const uint8_t *u_thread_name = (const uint8_t *)thread_name;
        for (size_t i = 0; i < thread_name_len; i++)
          ostrm << RAWHEX8(u_thread_name[i]);
        ostrm << ';';
      }
    }

    // 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) {
      const nub_size_t numthreads = DNBProcessGetNumThreads(pid);
      if (numthreads > 0) {
        std::vector<uint64_t> pc_values;
        ostrm << std::hex << "threads:";
        for (nub_size_t i = 0; i < numthreads; ++i) {
          nub_thread_t th = DNBProcessGetThreadAtIndex(pid, i);
          if (i > 0)
            ostrm << ',';
          ostrm << std::hex << th;
          DNBRegisterValue pc_regval;
          if (DNBThreadGetRegisterValueByID(pid, th, REGISTER_SET_GENERIC,
                                            GENERIC_REGNUM_PC, &pc_regval)) {
            uint64_t pc = INVALID_NUB_ADDRESS;
            if (pc_regval.value.uint64 != INVALID_NUB_ADDRESS) {
              if (pc_regval.info.size == 4) {
                pc = pc_regval.value.uint32;
              } else if (pc_regval.info.size == 8) {
                pc = pc_regval.value.uint64;
              }
              if (pc != INVALID_NUB_ADDRESS) {
                pc_values.push_back(pc);
              }
            }
          }
        }
        ostrm << ';';

        // If we failed to get any of the thread pc values, the size of our
        // vector will not
        // be the same as the # of threads.  Don't provide any expedited thread
        // pc values in
        // that case.  This should not happen.
        if (pc_values.size() == numthreads) {
          ostrm << std::hex << "thread-pcs:";
          for (nub_size_t i = 0; i < numthreads; ++i) {
            if (i > 0)
              ostrm << ',';
            ostrm << std::hex << pc_values[i];
          }
          ostrm << ';';
        }
      }

      // 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 (numthreads > 1) {
        const bool threads_with_valid_stop_info_only = true;
        JSONGenerator::ObjectSP threads_info_sp =
            GetJSONThreadsInfo(threads_with_valid_stop_info_only);
        if (threads_info_sp) {
          ostrm << std::hex << "jstopinfo:";
          std::ostringstream json_strm;
          threads_info_sp->Dump(json_strm);
          append_hexified_string(ostrm, json_strm.str());
          ostrm << ';';
        }
      }
    }

    if (g_num_reg_entries == 0)
      InitializeRegisters();

    if (g_reg_entries != NULL) {
      DNBRegisterValue reg_value;
      for (uint32_t reg = 0; reg < g_num_reg_entries; reg++) {
        // Expedite all registers in the first register set that aren't
        // contained in other registers
        if (g_reg_entries[reg].nub_info.set == 1 &&
            g_reg_entries[reg].nub_info.value_regs == NULL) {
          if (!DNBThreadGetRegisterValueByID(
                  pid, tid, g_reg_entries[reg].nub_info.set,
                  g_reg_entries[reg].nub_info.reg, &reg_value))
            continue;

          debugserver_regnum_with_fixed_width_hex_register_value(
              ostrm, pid, tid, &g_reg_entries[reg], &reg_value);
        }
      }
    }

    if (did_exec) {
      ostrm << "reason:exec;";
    } else if (tid_stop_info.details.exception.type) {
      ostrm << "metype:" << std::hex << tid_stop_info.details.exception.type
            << ';';
      ostrm << "mecount:" << std::hex
            << tid_stop_info.details.exception.data_count << ';';
      for (nub_size_t i = 0; i < tid_stop_info.details.exception.data_count;
           ++i)
        ostrm << "medata:" << std::hex
              << tid_stop_info.details.exception.data[i] << ';';
    }

    // Add expedited stack memory so stack backtracing doesn't need to read
    // anything from the
    // frame pointer chain.
    StackMemoryMap stack_mmap;
    ReadStackMemory(pid, tid, stack_mmap, 2);
    if (!stack_mmap.empty()) {
      for (const auto &stack_memory : stack_mmap) {
        ostrm << "memory:" << HEXBASE << stack_memory.first << '=';
        append_hex_value(ostrm, stack_memory.second.bytes,
                         stack_memory.second.length, false);
        ostrm << ';';
      }
    }

    return SendPacket(ostrm.str());
  }
  return SendPacket("E51");
}

/* '?'
 The stop reply packet - tell gdb what the status of the inferior is.
 Often called the questionmark_packet.  */

rnb_err_t RNBRemote::HandlePacket_last_signal(const char *unused) {
  if (!m_ctx.HasValidProcessID()) {
    // Inferior is not yet specified/running
    return SendPacket("E02");
  }

  nub_process_t pid = m_ctx.ProcessID();
  nub_state_t pid_state = DNBProcessGetState(pid);

  switch (pid_state) {
  case eStateAttaching:
  case eStateLaunching:
  case eStateRunning:
  case eStateStepping:
  case eStateDetached:
    return rnb_success; // Ignore

  case eStateSuspended:
  case eStateStopped:
  case eStateCrashed: {
    nub_thread_t tid = DNBProcessGetCurrentThread(pid);
    // Make sure we set the current thread so g and p packets return
    // the data the gdb will expect.
    SetCurrentThread(tid);

    SendStopReplyPacketForThread(tid);
  } break;

  case eStateInvalid:
  case eStateUnloaded:
  case eStateExited: {
    char pid_exited_packet[16] = "";
    int pid_status = 0;
    // Process exited with exit status
    if (!DNBProcessGetExitStatus(pid, &pid_status))
      pid_status = 0;

    if (pid_status) {
      if (WIFEXITED(pid_status))
        snprintf(pid_exited_packet, sizeof(pid_exited_packet), "W%02x",
                 WEXITSTATUS(pid_status));
      else if (WIFSIGNALED(pid_status))
        snprintf(pid_exited_packet, sizeof(pid_exited_packet), "X%02x",
                 WEXITSTATUS(pid_status));
      else if (WIFSTOPPED(pid_status))
        snprintf(pid_exited_packet, sizeof(pid_exited_packet), "S%02x",
                 WSTOPSIG(pid_status));
    }

    // If we have an empty exit packet, lets fill one in to be safe.
    if (!pid_exited_packet[0]) {
      strlcpy(pid_exited_packet, "W00", sizeof(pid_exited_packet) - 1);
      pid_exited_packet[sizeof(pid_exited_packet) - 1] = '\0';
    }

    const char *exit_info = DNBProcessGetExitInfo(pid);
    if (exit_info != NULL && *exit_info != '\0') {
      std::ostringstream exit_packet;
      exit_packet << pid_exited_packet;
      exit_packet << ';';
      exit_packet << RAW_HEXBASE << "description";
      exit_packet << ':';
      for (size_t i = 0; exit_info[i] != '\0'; i++)
        exit_packet << RAWHEX8(exit_info[i]);
      exit_packet << ';';
      return SendPacket(exit_packet.str());
    } else
      return SendPacket(pid_exited_packet);
  } break;
  }
  return rnb_success;
}

rnb_err_t RNBRemote::HandlePacket_M(const char *p) {
  if (p == NULL || p[0] == '\0' || strlen(p) < 3) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p, "Too short M packet");
  }

  char *c;
  p++;
  errno = 0;
  nub_addr_t addr = strtoull(p, &c, 16);
  if (errno != 0 && addr == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid address in M packet");
  }
  if (*c != ',') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma sep missing in M packet");
  }

  /* Advance 'p' to the length part of the packet.  */
  p += (c - p) + 1;

  errno = 0;
  unsigned long length = strtoul(p, &c, 16);
  if (errno != 0 && length == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in M packet");
  }
  if (length == 0) {
    return SendPacket("OK");
  }

  if (*c != ':') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Missing colon in M packet");
  }
  /* Advance 'p' to the data part of the packet.  */
  p += (c - p) + 1;

  size_t datalen = strlen(p);
  if (datalen & 0x1) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Uneven # of hex chars for data in M packet");
  }
  if (datalen == 0) {
    return SendPacket("OK");
  }

  uint8_t *buf = (uint8_t *)alloca(datalen / 2);
  uint8_t *i = buf;

  while (*p != '\0' && *(p + 1) != '\0') {
    char hexbuf[3];
    hexbuf[0] = *p;
    hexbuf[1] = *(p + 1);
    hexbuf[2] = '\0';
    errno = 0;
    uint8_t byte = strtoul(hexbuf, NULL, 16);
    if (errno != 0 && byte == 0) {
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "Invalid hex byte in M packet");
    }
    *i++ = byte;
    p += 2;
  }

  nub_size_t wrote =
      DNBProcessMemoryWrite(m_ctx.ProcessID(), addr, length, buf);
  if (wrote != length)
    return SendPacket("E09");
  else
    return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_m(const char *p) {
  if (p == NULL || p[0] == '\0' || strlen(p) < 3) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p, "Too short m packet");
  }

  char *c;
  p++;
  errno = 0;
  nub_addr_t addr = strtoull(p, &c, 16);
  if (errno != 0 && addr == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid address in m packet");
  }
  if (*c != ',') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma sep missing in m packet");
  }

  /* Advance 'p' to the length part of the packet.  */
  p += (c - p) + 1;

  errno = 0;
  auto length = strtoul(p, NULL, 16);
  if (errno != 0 && length == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in m packet");
  }
  if (length == 0) {
    return SendPacket("");
  }

  std::string buf(length, '\0');
  if (buf.empty()) {
    return SendPacket("E78");
  }
  nub_size_t bytes_read =
      DNBProcessMemoryRead(m_ctx.ProcessID(), addr, buf.size(), &buf[0]);
  if (bytes_read == 0) {
    return SendPacket("E08");
  }

  // "The reply may contain fewer bytes than requested if the server was able
  //  to read only part of the region of memory."
  length = bytes_read;

  std::ostringstream ostrm;
  for (unsigned long i = 0; i < length; i++)
    ostrm << RAWHEX8(buf[i]);
  return SendPacket(ostrm.str());
}

// Read memory, sent it up as binary data.
// Usage:  xADDR,LEN
// ADDR and LEN are both base 16.

// Responds with 'OK' for zero-length request
// or
//
// DATA
//
// where DATA is the binary data payload.

rnb_err_t RNBRemote::HandlePacket_x(const char *p) {
  if (p == NULL || p[0] == '\0' || strlen(p) < 3) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p, "Too short X packet");
  }

  char *c;
  p++;
  errno = 0;
  nub_addr_t addr = strtoull(p, &c, 16);
  if (errno != 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid address in X packet");
  }
  if (*c != ',') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma sep missing in X packet");
  }

  /* Advance 'p' to the number of bytes to be read.  */
  p += (c - p) + 1;

  errno = 0;
  auto length = strtoul(p, NULL, 16);
  if (errno != 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in x packet");
  }

  // zero length read means this is a test of whether that packet is implemented
  // or not.
  if (length == 0) {
    return SendPacket("OK");
  }

  std::vector<uint8_t> buf(length);

  if (buf.capacity() != length) {
    return SendPacket("E79");
  }
  nub_size_t bytes_read =
      DNBProcessMemoryRead(m_ctx.ProcessID(), addr, buf.size(), &buf[0]);
  if (bytes_read == 0) {
    return SendPacket("E80");
  }

  std::vector<uint8_t> buf_quoted;
  buf_quoted.reserve(bytes_read + 30);
  for (nub_size_t i = 0; i < bytes_read; i++) {
    if (buf[i] == '#' || buf[i] == '$' || buf[i] == '}' || buf[i] == '*') {
      buf_quoted.push_back(0x7d);
      buf_quoted.push_back(buf[i] ^ 0x20);
    } else {
      buf_quoted.push_back(buf[i]);
    }
  }
  length = buf_quoted.size();

  std::ostringstream ostrm;
  for (unsigned long i = 0; i < length; i++)
    ostrm << buf_quoted[i];

  return SendPacket(ostrm.str());
}

rnb_err_t RNBRemote::HandlePacket_X(const char *p) {
  if (p == NULL || p[0] == '\0' || strlen(p) < 3) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p, "Too short X packet");
  }

  char *c;
  p++;
  errno = 0;
  nub_addr_t addr = strtoull(p, &c, 16);
  if (errno != 0 && addr == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid address in X packet");
  }
  if (*c != ',') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma sep missing in X packet");
  }

  /* Advance 'p' to the length part of the packet.  NB this is the length of the
     packet
     including any escaped chars.  The data payload may be a little bit smaller
     after
     decoding.  */
  p += (c - p) + 1;

  errno = 0;
  auto length = strtoul(p, NULL, 16);
  if (errno != 0 && length == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in X packet");
  }

  // I think gdb sends a zero length write request to test whether this
  // packet is accepted.
  if (length == 0) {
    return SendPacket("OK");
  }

  std::vector<uint8_t> data = decode_binary_data(c, -1);
  std::vector<uint8_t>::const_iterator it;
  uint8_t *buf = (uint8_t *)alloca(data.size());
  uint8_t *i = buf;
  for (it = data.begin(); it != data.end(); ++it) {
    *i++ = *it;
  }

  nub_size_t wrote =
      DNBProcessMemoryWrite(m_ctx.ProcessID(), addr, data.size(), buf);
  if (wrote != data.size())
    return SendPacket("E08");
  return SendPacket("OK");
}

/* 'g' -- read registers
 Get the contents of the registers for the current thread,
 send them to gdb.
 Should the setting of the Hg packet determine which thread's registers
 are returned?  */

rnb_err_t RNBRemote::HandlePacket_g(const char *p) {
  std::ostringstream ostrm;
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E11");
  }

  if (g_num_reg_entries == 0)
    InitializeRegisters();

  nub_process_t pid = m_ctx.ProcessID();
  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(p + 1);
  if (tid == INVALID_NUB_THREAD)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in p packet");

  // Get the register context size first by calling with NULL buffer
  nub_size_t reg_ctx_size = DNBThreadGetRegisterContext(pid, tid, NULL, 0);
  if (reg_ctx_size) {
    // Now allocate enough space for the entire register context
    std::vector<uint8_t> reg_ctx;
    reg_ctx.resize(reg_ctx_size);
    // Now read the register context
    reg_ctx_size =
        DNBThreadGetRegisterContext(pid, tid, &reg_ctx[0], reg_ctx.size());
    if (reg_ctx_size) {
      append_hex_value(ostrm, reg_ctx.data(), reg_ctx.size(), false);
      return SendPacket(ostrm.str());
    }
  }
  return SendPacket("E74");
}

/* 'G XXX...' -- write registers
 How is the thread for these specified, beyond "the current thread"?
 Does gdb actually use the Hg packet to set this?  */

rnb_err_t RNBRemote::HandlePacket_G(const char *p) {
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E11");
  }

  if (g_num_reg_entries == 0)
    InitializeRegisters();

  StdStringExtractor packet(p);
  packet.SetFilePos(1); // Skip the 'G'

  nub_process_t pid = m_ctx.ProcessID();
  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(p);
  if (tid == INVALID_NUB_THREAD)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in p packet");

  // Get the register context size first by calling with NULL buffer
  nub_size_t reg_ctx_size = DNBThreadGetRegisterContext(pid, tid, NULL, 0);
  if (reg_ctx_size) {
    // Now allocate enough space for the entire register context
    std::vector<uint8_t> reg_ctx;
    reg_ctx.resize(reg_ctx_size);

    const nub_size_t bytes_extracted =
        packet.GetHexBytes(&reg_ctx[0], reg_ctx.size(), 0xcc);
    if (bytes_extracted == reg_ctx.size()) {
      // Now write the register context
      reg_ctx_size =
          DNBThreadSetRegisterContext(pid, tid, reg_ctx.data(), reg_ctx.size());
      if (reg_ctx_size == reg_ctx.size())
        return SendPacket("OK");
      else
        return SendPacket("E55");
    } else {
      DNBLogError("RNBRemote::HandlePacket_G(%s): extracted %llu of %llu "
                  "bytes, size mismatch\n",
                  p, (uint64_t)bytes_extracted, (uint64_t)reg_ctx_size);
      return SendPacket("E64");
    }
  }
  return SendPacket("E65");
}

static bool RNBRemoteShouldCancelCallback(void *not_used) {
  RNBRemoteSP remoteSP(g_remoteSP);
  if (remoteSP.get() != NULL) {
    RNBRemote *remote = remoteSP.get();
    return !remote->Comm().IsConnected();
  }
  return true;
}

// FORMAT: _MXXXXXX,PPP
//      XXXXXX: big endian hex chars
//      PPP: permissions can be any combo of r w x chars
//
// RESPONSE: XXXXXX
//      XXXXXX: hex address of the newly allocated memory
//      EXX: error code
//
// EXAMPLES:
//      _M123000,rw
//      _M123000,rwx
//      _M123000,xw

rnb_err_t RNBRemote::HandlePacket_AllocateMemory(const char *p) {
  StdStringExtractor packet(p);
  packet.SetFilePos(2); // Skip the "_M"

  nub_addr_t size = packet.GetHexMaxU64(StdStringExtractor::BigEndian, 0);
  if (size != 0) {
    if (packet.GetChar() == ',') {
      uint32_t permissions = 0;
      char ch;
      bool success = true;
      while (success && (ch = packet.GetChar()) != '\0') {
        switch (ch) {
        case 'r':
          permissions |= eMemoryPermissionsReadable;
          break;
        case 'w':
          permissions |= eMemoryPermissionsWritable;
          break;
        case 'x':
          permissions |= eMemoryPermissionsExecutable;
          break;
        default:
          success = false;
          break;
        }
      }

      if (success) {
        nub_addr_t addr =
            DNBProcessMemoryAllocate(m_ctx.ProcessID(), size, permissions);
        if (addr != INVALID_NUB_ADDRESS) {
          std::ostringstream ostrm;
          ostrm << RAW_HEXBASE << addr;
          return SendPacket(ostrm.str());
        }
      }
    }
  }
  return SendPacket("E53");
}

// FORMAT: _mXXXXXX
//      XXXXXX: address that was previously allocated
//
// RESPONSE: XXXXXX
//      OK: address was deallocated
//      EXX: error code
//
// EXAMPLES:
//      _m123000

rnb_err_t RNBRemote::HandlePacket_DeallocateMemory(const char *p) {
  StdStringExtractor packet(p);
  packet.SetFilePos(2); // Skip the "_m"
  nub_addr_t addr =
      packet.GetHexMaxU64(StdStringExtractor::BigEndian, INVALID_NUB_ADDRESS);

  if (addr != INVALID_NUB_ADDRESS) {
    if (DNBProcessMemoryDeallocate(m_ctx.ProcessID(), addr))
      return SendPacket("OK");
  }
  return SendPacket("E54");
}

// FORMAT: QSaveRegisterState;thread:TTTT;  (when thread suffix is supported)
// FORMAT: QSaveRegisterState               (when thread suffix is NOT
// supported)
//      TTTT: thread ID in hex
//
// RESPONSE:
//      SAVEID: Where SAVEID is a decimal number that represents the save ID
//              that can be passed back into a "QRestoreRegisterState" packet
//      EXX: error code
//
// EXAMPLES:
//      QSaveRegisterState;thread:1E34;     (when thread suffix is supported)
//      QSaveRegisterState                  (when thread suffix is NOT
//      supported)

rnb_err_t RNBRemote::HandlePacket_SaveRegisterState(const char *p) {
  nub_process_t pid = m_ctx.ProcessID();
  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(p);
  if (tid == INVALID_NUB_THREAD) {
    if (m_thread_suffix_supported)
      return HandlePacket_ILLFORMED(
          __FILE__, __LINE__, p,
          "No thread specified in QSaveRegisterState packet");
    else
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "No thread was is set with the Hg packet");
  }

  // Get the register context size first by calling with NULL buffer
  const uint32_t save_id = DNBThreadSaveRegisterState(pid, tid);
  if (save_id != 0) {
    char response[64];
    snprintf(response, sizeof(response), "%u", save_id);
    return SendPacket(response);
  } else {
    return SendPacket("E75");
  }
}
// FORMAT: QRestoreRegisterState:SAVEID;thread:TTTT;  (when thread suffix is
// supported)
// FORMAT: QRestoreRegisterState:SAVEID               (when thread suffix is NOT
// supported)
//      TTTT: thread ID in hex
//      SAVEID: a decimal number that represents the save ID that was
//              returned from a call to "QSaveRegisterState"
//
// RESPONSE:
//      OK: successfully restored registers for the specified thread
//      EXX: error code
//
// EXAMPLES:
//      QRestoreRegisterState:1;thread:1E34;     (when thread suffix is
//      supported)
//      QRestoreRegisterState:1                  (when thread suffix is NOT
//      supported)

rnb_err_t RNBRemote::HandlePacket_RestoreRegisterState(const char *p) {
  nub_process_t pid = m_ctx.ProcessID();
  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(p);
  if (tid == INVALID_NUB_THREAD) {
    if (m_thread_suffix_supported)
      return HandlePacket_ILLFORMED(
          __FILE__, __LINE__, p,
          "No thread specified in QSaveRegisterState packet");
    else
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "No thread was is set with the Hg packet");
  }

  StdStringExtractor packet(p);
  packet.SetFilePos(
      strlen("QRestoreRegisterState:")); // Skip the "QRestoreRegisterState:"
  const uint32_t save_id = packet.GetU32(0);

  if (save_id != 0) {
    // Get the register context size first by calling with NULL buffer
    if (DNBThreadRestoreRegisterState(pid, tid, save_id))
      return SendPacket("OK");
    else
      return SendPacket("E77");
  }
  return SendPacket("E76");
}

static bool GetProcessNameFrom_vAttach(const char *&p,
                                       std::string &attach_name) {
  bool return_val = true;
  while (*p != '\0') {
    char smallbuf[3];
    smallbuf[0] = *p;
    smallbuf[1] = *(p + 1);
    smallbuf[2] = '\0';

    errno = 0;
    int ch = static_cast<int>(strtoul(smallbuf, NULL, 16));
    if (errno != 0 && ch == 0) {
      return_val = false;
      break;
    }

    attach_name.push_back(ch);
    p += 2;
  }
  return return_val;
}

rnb_err_t RNBRemote::HandlePacket_qSupported(const char *p) {
  uint32_t max_packet_size = 128 * 1024; // 128KBytes is a reasonable max packet
                                         // size--debugger can always use less
  char buf[256];
  snprintf(buf, sizeof(buf), "qXfer:features:read+;PacketSize=%x;qEcho+",
           max_packet_size);

  bool enable_compression = false;
  (void)enable_compression;

#if (defined (TARGET_OS_WATCH) && TARGET_OS_WATCH == 1) \
    || (defined (TARGET_OS_IOS) && TARGET_OS_IOS == 1) \
    || (defined (TARGET_OS_TV) && TARGET_OS_TV == 1) \
    || (defined (TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1)
  enable_compression = true;
#endif

  if (enable_compression) {
    strcat(buf, ";SupportedCompressions=lzfse,zlib-deflate,lz4,lzma;"
                "DefaultCompressionMinSize=");
    char numbuf[16];
    snprintf(numbuf, sizeof(numbuf), "%zu", m_compression_minsize);
    numbuf[sizeof(numbuf) - 1] = '\0';
    strcat(buf, numbuf);
  } 

  return SendPacket(buf);
}

/*
 vAttach;pid

 Attach to a new process with the specified process ID. pid is a hexadecimal
 integer
 identifying the process. If the stub is currently controlling a process, it is
 killed. The attached process is stopped.This packet is only available in
 extended
 mode (see extended mode).

 Reply:
 "ENN"                      for an error
 "Any Stop Reply Packet"     for success
 */

rnb_err_t RNBRemote::HandlePacket_v(const char *p) {
  if (strcmp(p, "vCont;c") == 0) {
    // Simple continue
    return RNBRemote::HandlePacket_c("c");
  } else if (strcmp(p, "vCont;s") == 0) {
    // Simple step
    return RNBRemote::HandlePacket_s("s");
  } else if (strstr(p, "vCont") == p) {
    DNBThreadResumeActions thread_actions;
    char *c = const_cast<char *>(p += strlen("vCont"));
    char *c_end = c + strlen(c);
    if (*c == '?')
      return SendPacket("vCont;c;C;s;S");

    while (c < c_end && *c == ';') {
      ++c; // Skip the semi-colon
      DNBThreadResumeAction thread_action;
      thread_action.tid = INVALID_NUB_THREAD;
      thread_action.state = eStateInvalid;
      thread_action.signal = 0;
      thread_action.addr = INVALID_NUB_ADDRESS;

      char action = *c++;

      switch (action) {
      case 'C':
        errno = 0;
        thread_action.signal = static_cast<int>(strtoul(c, &c, 16));
        if (errno != 0)
          return HandlePacket_ILLFORMED(
              __FILE__, __LINE__, p, "Could not parse signal in vCont packet");
      // Fall through to next case...
        [[clang::fallthrough]];
      case 'c':
        // Continue
        thread_action.state = eStateRunning;
        break;

      case 'S':
        errno = 0;
        thread_action.signal = static_cast<int>(strtoul(c, &c, 16));
        if (errno != 0)
          return HandlePacket_ILLFORMED(
              __FILE__, __LINE__, p, "Could not parse signal in vCont packet");
      // Fall through to next case...
        [[clang::fallthrough]];
      case 's':
        // Step
        thread_action.state = eStateStepping;
        break;

      default:
        HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                               "Unsupported action in vCont packet");
        break;
      }
      if (*c == ':') {
        errno = 0;
        thread_action.tid = strtoul(++c, &c, 16);
        if (errno != 0)
          return HandlePacket_ILLFORMED(
              __FILE__, __LINE__, p,
              "Could not parse thread number in vCont packet");
      }

      thread_actions.Append(thread_action);
    }

    // If a default action for all other threads wasn't mentioned
    // then we should stop the threads
    thread_actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
    DNBProcessResume(m_ctx.ProcessID(), thread_actions.GetFirst(),
                     thread_actions.GetSize());
    return rnb_success;
  } else if (strstr(p, "vAttach") == p) {
    nub_process_t attach_pid =
        INVALID_NUB_PROCESS; // attach_pid will be set to 0 if the attach fails
    nub_process_t pid_attaching_to =
        INVALID_NUB_PROCESS; // pid_attaching_to is the original pid specified
    char err_str[1024] = {'\0'};
    std::string attach_name;

    if (strstr(p, "vAttachWait;") == p) {
      p += strlen("vAttachWait;");
      if (!GetProcessNameFrom_vAttach(p, attach_name)) {
        return HandlePacket_ILLFORMED(
            __FILE__, __LINE__, p, "non-hex char in arg on 'vAttachWait' pkt");
      }
      const bool ignore_existing = true;
      attach_pid = DNBProcessAttachWait(
          attach_name.c_str(), m_ctx.LaunchFlavor(), ignore_existing, NULL,
          1000, err_str, sizeof(err_str), RNBRemoteShouldCancelCallback);

    } else if (strstr(p, "vAttachOrWait;") == p) {
      p += strlen("vAttachOrWait;");
      if (!GetProcessNameFrom_vAttach(p, attach_name)) {
        return HandlePacket_ILLFORMED(
            __FILE__, __LINE__, p,
            "non-hex char in arg on 'vAttachOrWait' pkt");
      }
      const bool ignore_existing = false;
      attach_pid = DNBProcessAttachWait(
          attach_name.c_str(), m_ctx.LaunchFlavor(), ignore_existing, NULL,
          1000, err_str, sizeof(err_str), RNBRemoteShouldCancelCallback);
    } else if (strstr(p, "vAttachName;") == p) {
      p += strlen("vAttachName;");
      if (!GetProcessNameFrom_vAttach(p, attach_name)) {
        return HandlePacket_ILLFORMED(
            __FILE__, __LINE__, p, "non-hex char in arg on 'vAttachName' pkt");
      }

      attach_pid = DNBProcessAttachByName(attach_name.c_str(), NULL, err_str,
                                          sizeof(err_str));

    } else if (strstr(p, "vAttach;") == p) {
      p += strlen("vAttach;");
      char *end = NULL;
      pid_attaching_to = static_cast<int>(
          strtoul(p, &end, 16)); // PID will be in hex, so use base 16 to decode
      if (p != end && *end == '\0') {
        // Wait at most 30 second for attach
        struct timespec attach_timeout_abstime;
        DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, 30, 0);
        attach_pid = DNBProcessAttach(pid_attaching_to, &attach_timeout_abstime,
                                      err_str, sizeof(err_str));
      }
    } else {
      return HandlePacket_UNIMPLEMENTED(p);
    }

    if (attach_pid != INVALID_NUB_PROCESS) {
      if (m_ctx.ProcessID() != attach_pid)
        m_ctx.SetProcessID(attach_pid);
      // Send a stop reply packet to indicate we successfully attached!
      NotifyThatProcessStopped();
      return rnb_success;
    } else {
      m_ctx.LaunchStatus().SetError(-1, DNBError::Generic);
      if (err_str[0])
        m_ctx.LaunchStatus().SetErrorString(err_str);
      else
        m_ctx.LaunchStatus().SetErrorString("attach failed");

#if defined(__APPLE__) &&                                                      \
    (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 101000)
      if (pid_attaching_to == INVALID_NUB_PROCESS && !attach_name.empty()) {
        pid_attaching_to = DNBProcessGetPIDByName(attach_name.c_str());
      }
      if (pid_attaching_to != INVALID_NUB_PROCESS &&
          strcmp(err_str, "No such process") != 0) {
        // csr_check(CSR_ALLOW_TASK_FOR_PID) will be nonzero if System Integrity
        // Protection is in effect.
        if (csr_check(CSR_ALLOW_TASK_FOR_PID) != 0) {
          bool attach_failed_due_to_sip = false;

          if (rootless_allows_task_for_pid(pid_attaching_to) == 0) {
            attach_failed_due_to_sip = true;
          }

          if (!attach_failed_due_to_sip) {
            int csops_flags = 0;
            int retval = ::csops(pid_attaching_to, CS_OPS_STATUS, &csops_flags,
                                 sizeof(csops_flags));
            if (retval != -1 && (csops_flags & CS_RESTRICT)) {
              attach_failed_due_to_sip = true;
            }
          }
          if (attach_failed_due_to_sip) {
            std::string return_message = "E96;";
            return_message += cstring_to_asciihex_string(
                "Process attach denied, possibly because "
                "System Integrity Protection is enabled and "
                "process does not allow attaching.");

            SendPacket(return_message.c_str());
            DNBLogError("Attach failed because process does not allow "
                        "attaching: \"%s\".",
                        err_str);
            return rnb_err;
          }
        }
      }

#endif

      SendPacket("E01"); // E01 is our magic error value for attach failed.
      DNBLogError("Attach failed: \"%s\".", err_str);
      return rnb_err;
    }
  }

  // All other failures come through here
  return HandlePacket_UNIMPLEMENTED(p);
}

/* 'T XX' -- status of thread
 Check if the specified thread is alive.
 The thread number is in hex?  */

rnb_err_t RNBRemote::HandlePacket_T(const char *p) {
  p++;
  if (p == NULL || *p == '\0') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in T packet");
  }
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E15");
  }
  errno = 0;
  nub_thread_t tid = strtoul(p, NULL, 16);
  if (errno != 0 && tid == 0) {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Could not parse thread number in T packet");
  }

  nub_state_t state = DNBThreadGetState(m_ctx.ProcessID(), tid);
  if (state == eStateInvalid || state == eStateExited ||
      state == eStateCrashed) {
    return SendPacket("E16");
  }

  return SendPacket("OK");
}

rnb_err_t RNBRemote::HandlePacket_z(const char *p) {
  if (p == NULL || *p == '\0')
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in z packet");

  if (!m_ctx.HasValidProcessID())
    return SendPacket("E15");

  char packet_cmd = *p++;
  char break_type = *p++;

  if (*p++ != ',')
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma separator missing in z packet");

  char *c = NULL;
  nub_process_t pid = m_ctx.ProcessID();
  errno = 0;
  nub_addr_t addr = strtoull(p, &c, 16);
  if (errno != 0 && addr == 0)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid address in z packet");
  p = c;
  if (*p++ != ',')
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Comma separator missing in z packet");

  errno = 0;
  auto byte_size = strtoul(p, &c, 16);
  if (errno != 0 && byte_size == 0)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Invalid length in z packet");

  if (packet_cmd == 'Z') {
    // set
    switch (break_type) {
    case '0': // set software breakpoint
    case '1': // set hardware breakpoint
    {
      // gdb can send multiple Z packets for the same address and
      // these calls must be ref counted.
      bool hardware = (break_type == '1');

      if (DNBBreakpointSet(pid, addr, byte_size, hardware)) {
        // We successfully created a breakpoint, now lets full out
        // a ref count structure with the breakID and add it to our
        // map.
        return SendPacket("OK");
      } else {
        // We failed to set the software breakpoint
        return SendPacket("E09");
      }
    } break;

    case '2': // set write watchpoint
    case '3': // set read watchpoint
    case '4': // set access watchpoint
    {
      bool hardware = true;
      uint32_t watch_flags = 0;
      if (break_type == '2')
        watch_flags = WATCH_TYPE_WRITE;
      else if (break_type == '3')
        watch_flags = WATCH_TYPE_READ;
      else
        watch_flags = WATCH_TYPE_READ | WATCH_TYPE_WRITE;

      if (DNBWatchpointSet(pid, addr, byte_size, watch_flags, hardware)) {
        return SendPacket("OK");
      } else {
        // We failed to set the watchpoint
        return SendPacket("E09");
      }
    } break;

    default:
      break;
    }
  } else if (packet_cmd == 'z') {
    // remove
    switch (break_type) {
    case '0': // remove software breakpoint
    case '1': // remove hardware breakpoint
      if (DNBBreakpointClear(pid, addr)) {
        return SendPacket("OK");
      } else {
        return SendPacket("E08");
      }
      break;

    case '2': // remove write watchpoint
    case '3': // remove read watchpoint
    case '4': // remove access watchpoint
      if (DNBWatchpointClear(pid, addr)) {
        return SendPacket("OK");
      } else {
        return SendPacket("E08");
      }
      break;

    default:
      break;
    }
  }
  return HandlePacket_UNIMPLEMENTED(p);
}

// Extract the thread number from the thread suffix that might be appended to
// thread specific packets. This will only be enabled if
// m_thread_suffix_supported
// is true.
nub_thread_t RNBRemote::ExtractThreadIDFromThreadSuffix(const char *p) {
  if (m_thread_suffix_supported) {
    nub_thread_t tid = INVALID_NUB_THREAD;
    if (p) {
      const char *tid_cstr = strstr(p, "thread:");
      if (tid_cstr) {
        tid_cstr += strlen("thread:");
        tid = strtoul(tid_cstr, NULL, 16);
      }
    }
    return tid;
  }
  return GetCurrentThread();
}

/* 'p XX'
 print the contents of register X */

rnb_err_t RNBRemote::HandlePacket_p(const char *p) {
  if (g_num_reg_entries == 0)
    InitializeRegisters();

  if (p == NULL || *p == '\0') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in p packet");
  }
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E15");
  }
  nub_process_t pid = m_ctx.ProcessID();
  errno = 0;
  char *tid_cstr = NULL;
  uint32_t reg = static_cast<uint32_t>(strtoul(p + 1, &tid_cstr, 16));
  if (errno != 0 && reg == 0) {
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p, "Could not parse register number in p packet");
  }

  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(tid_cstr);
  if (tid == INVALID_NUB_THREAD)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in p packet");

  const register_map_entry_t *reg_entry;

  if (reg < g_num_reg_entries)
    reg_entry = &g_reg_entries[reg];
  else
    reg_entry = NULL;

  std::ostringstream ostrm;
  if (reg_entry == NULL) {
    DNBLogError(
        "RNBRemote::HandlePacket_p(%s): unknown register number %u requested\n",
        p, reg);
    ostrm << "00000000";
  } else if (reg_entry->nub_info.reg == (uint32_t)-1) {
    if (reg_entry->nub_info.size > 0) {
      std::basic_string<uint8_t> zeros(reg_entry->nub_info.size, '\0');
      append_hex_value(ostrm, zeros.data(), zeros.size(), false);
    }
  } else {
    register_value_in_hex_fixed_width(ostrm, pid, tid, reg_entry, NULL);
  }
  return SendPacket(ostrm.str());
}

/* 'Pnn=rrrrr'
 Set register number n to value r.
 n and r are hex strings.  */

rnb_err_t RNBRemote::HandlePacket_P(const char *p) {
  if (g_num_reg_entries == 0)
    InitializeRegisters();

  if (p == NULL || *p == '\0') {
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p, "Empty P packet");
  }
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E28");
  }

  nub_process_t pid = m_ctx.ProcessID();

  StdStringExtractor packet(p);

  const char cmd_char = packet.GetChar();
  // Register ID is always in big endian
  const uint32_t reg = packet.GetHexMaxU32(false, UINT32_MAX);
  const char equal_char = packet.GetChar();

  if (cmd_char != 'P')
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "Improperly formed P packet");

  if (reg == UINT32_MAX)
    return SendPacket("E29");

  if (equal_char != '=')
    return SendPacket("E30");

  const register_map_entry_t *reg_entry;

  if (reg >= g_num_reg_entries)
    return SendPacket("E47");

  reg_entry = &g_reg_entries[reg];

  if (reg_entry->nub_info.set == (uint32_t)-1 &&
      reg_entry->nub_info.reg == (uint32_t)-1) {
    DNBLogError(
        "RNBRemote::HandlePacket_P(%s): unknown register number %u requested\n",
        p, reg);
    return SendPacket("E48");
  }

  DNBRegisterValue reg_value;
  reg_value.info = reg_entry->nub_info;
  packet.GetHexBytes(reg_value.value.v_sint8, reg_entry->nub_info.size, 0xcc);

  nub_thread_t tid = ExtractThreadIDFromThreadSuffix(p);
  if (tid == INVALID_NUB_THREAD)
    return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                  "No thread specified in p packet");

  if (!DNBThreadSetRegisterValueByID(pid, tid, reg_entry->nub_info.set,
                                     reg_entry->nub_info.reg, &reg_value)) {
    return SendPacket("E32");
  }
  return SendPacket("OK");
}

/* 'c [addr]'
 Continue, optionally from a specified address. */

rnb_err_t RNBRemote::HandlePacket_c(const char *p) {
  const nub_process_t pid = m_ctx.ProcessID();

  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E23");

  DNBThreadResumeAction action = {INVALID_NUB_THREAD, eStateRunning, 0,
                                  INVALID_NUB_ADDRESS};

  if (*(p + 1) != '\0') {
    action.tid = GetContinueThread();
    errno = 0;
    action.addr = strtoull(p + 1, NULL, 16);
    if (errno != 0 && action.addr == 0)
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "Could not parse address in c packet");
  }

  DNBThreadResumeActions thread_actions;
  thread_actions.Append(action);
  thread_actions.SetDefaultThreadActionIfNeeded(eStateRunning, 0);
  if (!DNBProcessResume(pid, thread_actions.GetFirst(),
                        thread_actions.GetSize()))
    return SendPacket("E25");
  // Don't send an "OK" packet; response is the stopped/exited message.
  return rnb_success;
}

rnb_err_t RNBRemote::HandlePacket_MemoryRegionInfo(const char *p) {
  /* This packet will find memory attributes (e.g. readable, writable,
     executable, stack, jitted code)
     for the memory region containing a given address and return that
     information.

     Users of this packet must be prepared for three results:

         Region information is returned
         Region information is unavailable for this address because the address
     is in unmapped memory
         Region lookup cannot be performed on this platform or process is not
     yet launched
         This packet isn't implemented

     Examples of use:
        qMemoryRegionInfo:3a55140
        start:3a50000,size:100000,permissions:rwx

        qMemoryRegionInfo:0
        error:address in unmapped region

        qMemoryRegionInfo:3a551140   (on a different platform)
        error:region lookup cannot be performed

        qMemoryRegionInfo
        OK                   // this packet is implemented by the remote nub
  */

  p += sizeof("qMemoryRegionInfo") - 1;
  if (*p == '\0')
    return SendPacket("OK");
  if (*p++ != ':')
    return SendPacket("E67");
  if (*p == '0' && (*(p + 1) == 'x' || *(p + 1) == 'X'))
    p += 2;

  errno = 0;
  uint64_t address = strtoul(p, NULL, 16);
  if (errno != 0 && address == 0) {
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p, "Invalid address in qMemoryRegionInfo packet");
  }

  DNBRegionInfo region_info = {0, 0, 0};
  DNBProcessMemoryRegionInfo(m_ctx.ProcessID(), address, &region_info);
  std::ostringstream ostrm;

  // start:3a50000,size:100000,permissions:rwx
  ostrm << "start:" << std::hex << region_info.addr << ';';

  if (region_info.size > 0)
    ostrm << "size:" << std::hex << region_info.size << ';';

  if (region_info.permissions) {
    ostrm << "permissions:";

    if (region_info.permissions & eMemoryPermissionsReadable)
      ostrm << 'r';
    if (region_info.permissions & eMemoryPermissionsWritable)
      ostrm << 'w';
    if (region_info.permissions & eMemoryPermissionsExecutable)
      ostrm << 'x';
    ostrm << ';';
  }
  return SendPacket(ostrm.str());
}

// qGetProfileData;scan_type:0xYYYYYYY
rnb_err_t RNBRemote::HandlePacket_GetProfileData(const char *p) {
  nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("OK");

  StdStringExtractor packet(p += sizeof("qGetProfileData"));
  DNBProfileDataScanType scan_type = eProfileAll;
  std::string name;
  std::string value;
  while (packet.GetNameColonValue(name, value)) {
    if (name == "scan_type") {
      std::istringstream iss(value);
      uint32_t int_value = 0;
      if (iss >> std::hex >> int_value) {
        scan_type = (DNBProfileDataScanType)int_value;
      }
    }
  }

  std::string data = DNBProcessGetProfileData(pid, scan_type);
  if (!data.empty()) {
    return SendPacket(data.c_str());
  } else {
    return SendPacket("OK");
  }
}

// QSetEnableAsyncProfiling;enable:[0|1]:interval_usec:XXXXXX;scan_type:0xYYYYYYY
rnb_err_t RNBRemote::HandlePacket_SetEnableAsyncProfiling(const char *p) {
  nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("OK");

  StdStringExtractor packet(p += sizeof("QSetEnableAsyncProfiling"));
  bool enable = false;
  uint64_t interval_usec = 0;
  DNBProfileDataScanType scan_type = eProfileAll;
  std::string name;
  std::string value;
  while (packet.GetNameColonValue(name, value)) {
    if (name == "enable") {
      enable = strtoul(value.c_str(), NULL, 10) > 0;
    } else if (name == "interval_usec") {
      interval_usec = strtoul(value.c_str(), NULL, 10);
    } else if (name == "scan_type") {
      std::istringstream iss(value);
      uint32_t int_value = 0;
      if (iss >> std::hex >> int_value) {
        scan_type = (DNBProfileDataScanType)int_value;
      }
    }
  }

  if (interval_usec == 0) {
    enable = false;
  }

  DNBProcessSetEnableAsyncProfiling(pid, enable, interval_usec, scan_type);
  return SendPacket("OK");
}

// QEnableCompression:type:<COMPRESSION-TYPE>;minsize:<MINIMUM PACKET SIZE TO
// COMPRESS>;
//
// type: must be a type previously reported by the qXfer:features:
// SupportedCompressions list
//
// minsize: is optional; by default the qXfer:features:
// DefaultCompressionMinSize value is used
// debugserver may have a better idea of what a good minimum packet size to
// compress is than lldb.

rnb_err_t RNBRemote::HandlePacket_QEnableCompression(const char *p) {
  p += sizeof("QEnableCompression:") - 1;

  size_t new_compression_minsize = m_compression_minsize;
  const char *new_compression_minsize_str = strstr(p, "minsize:");
  if (new_compression_minsize_str) {
    new_compression_minsize_str += strlen("minsize:");
    errno = 0;
    new_compression_minsize = strtoul(new_compression_minsize_str, NULL, 10);
    if (errno != 0 || new_compression_minsize == ULONG_MAX) {
      new_compression_minsize = m_compression_minsize;
    }
  }

  if (strstr(p, "type:zlib-deflate;") != nullptr) {
    EnableCompressionNextSendPacket(compression_types::zlib_deflate);
    m_compression_minsize = new_compression_minsize;
    return SendPacket("OK");
  } else if (strstr(p, "type:lz4;") != nullptr) {
    EnableCompressionNextSendPacket(compression_types::lz4);
    m_compression_minsize = new_compression_minsize;
    return SendPacket("OK");
  } else if (strstr(p, "type:lzma;") != nullptr) {
    EnableCompressionNextSendPacket(compression_types::lzma);
    m_compression_minsize = new_compression_minsize;
    return SendPacket("OK");
  } else if (strstr(p, "type:lzfse;") != nullptr) {
    EnableCompressionNextSendPacket(compression_types::lzfse);
    m_compression_minsize = new_compression_minsize;
    return SendPacket("OK");
  }

  return SendPacket("E88");
}

rnb_err_t RNBRemote::HandlePacket_qSpeedTest(const char *p) {
  p += strlen("qSpeedTest:response_size:");
  char *end = NULL;
  errno = 0;
  uint64_t response_size = ::strtoul(p, &end, 16);
  if (errno != 0)
    return HandlePacket_ILLFORMED(
        __FILE__, __LINE__, p,
        "Didn't find response_size value at right offset");
  else if (*end == ';') {
    static char g_data[4 * 1024 * 1024 + 16] = "data:";
    memset(g_data + 5, 'a', response_size);
    g_data[response_size + 5] = '\0';
    return SendPacket(g_data);
  } else {
    return SendPacket("E79");
  }
}

rnb_err_t RNBRemote::HandlePacket_WatchpointSupportInfo(const char *p) {
  /* This packet simply returns the number of supported hardware watchpoints.

     Examples of use:
        qWatchpointSupportInfo:
        num:4

        qWatchpointSupportInfo
        OK                   // this packet is implemented by the remote nub
  */

  p += sizeof("qWatchpointSupportInfo") - 1;
  if (*p == '\0')
    return SendPacket("OK");
  if (*p++ != ':')
    return SendPacket("E67");

  errno = 0;
  uint32_t num = DNBWatchpointGetNumSupportedHWP(m_ctx.ProcessID());
  std::ostringstream ostrm;

  // size:4
  ostrm << "num:" << std::dec << num << ';';
  return SendPacket(ostrm.str());
}

/* 'C sig [;addr]'
 Resume with signal sig, optionally at address addr.  */

rnb_err_t RNBRemote::HandlePacket_C(const char *p) {
  const nub_process_t pid = m_ctx.ProcessID();

  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E36");

  DNBThreadResumeAction action = {INVALID_NUB_THREAD, eStateRunning, 0,
                                  INVALID_NUB_ADDRESS};
  int process_signo = -1;
  if (*(p + 1) != '\0') {
    action.tid = GetContinueThread();
    char *end = NULL;
    errno = 0;
    process_signo = static_cast<int>(strtoul(p + 1, &end, 16));
    if (errno != 0)
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "Could not parse signal in C packet");
    else if (*end == ';') {
      errno = 0;
      action.addr = strtoull(end + 1, NULL, 16);
      if (errno != 0 && action.addr == 0)
        return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                      "Could not parse address in C packet");
    }
  }

  DNBThreadResumeActions thread_actions;
  thread_actions.Append(action);
  thread_actions.SetDefaultThreadActionIfNeeded(eStateRunning, action.signal);
  if (!DNBProcessSignal(pid, process_signo))
    return SendPacket("E52");
  if (!DNBProcessResume(pid, thread_actions.GetFirst(),
                        thread_actions.GetSize()))
    return SendPacket("E38");
  /* Don't send an "OK" packet; response is the stopped/exited message.  */
  return rnb_success;
}

// 'D' packet
// Detach from gdb.
rnb_err_t RNBRemote::HandlePacket_D(const char *p) {
  if (m_ctx.HasValidProcessID()) {
    if (DNBProcessDetach(m_ctx.ProcessID()))
      SendPacket("OK");
    else
      SendPacket("E");
  } else {
    SendPacket("E");
  }
  return rnb_success;
}

/* 'k'
 Kill the inferior process.  */

rnb_err_t RNBRemote::HandlePacket_k(const char *p) {
  DNBLog("Got a 'k' packet, killing the inferior process.");
  // No response to should be sent to the kill packet
  if (m_ctx.HasValidProcessID())
    DNBProcessKill(m_ctx.ProcessID());
  SendPacket("X09");
  return rnb_success;
}

rnb_err_t RNBRemote::HandlePacket_stop_process(const char *p) {
//#define TEST_EXIT_ON_INTERRUPT // This should only be uncommented to test
//exiting on interrupt
#if defined(TEST_EXIT_ON_INTERRUPT)
  rnb_err_t err = HandlePacket_k(p);
  m_comm.Disconnect(true);
  return err;
#else
  if (!DNBProcessInterrupt(m_ctx.ProcessID())) {
    // If we failed to interrupt the process, then send a stop
    // reply packet as the process was probably already stopped
    DNBLogThreaded("RNBRemote::HandlePacket_stop_process() sending extra stop "
                   "reply because DNBProcessInterrupt returned false");
    HandlePacket_last_signal(NULL);
  }
  return rnb_success;
#endif
}

/* 's'
 Step the inferior process.  */

rnb_err_t RNBRemote::HandlePacket_s(const char *p) {
  const nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E32");

  // Hardware supported stepping not supported on arm
  nub_thread_t tid = GetContinueThread();
  if (tid == 0 || tid == (nub_thread_t)-1)
    tid = GetCurrentThread();

  if (tid == INVALID_NUB_THREAD)
    return SendPacket("E33");

  DNBThreadResumeActions thread_actions;
  thread_actions.AppendAction(tid, eStateStepping);

  // Make all other threads stop when we are stepping
  thread_actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
  if (!DNBProcessResume(pid, thread_actions.GetFirst(),
                        thread_actions.GetSize()))
    return SendPacket("E49");
  // Don't send an "OK" packet; response is the stopped/exited message.
  return rnb_success;
}

/* 'S sig [;addr]'
 Step with signal sig, optionally at address addr.  */

rnb_err_t RNBRemote::HandlePacket_S(const char *p) {
  const nub_process_t pid = m_ctx.ProcessID();
  if (pid == INVALID_NUB_PROCESS)
    return SendPacket("E36");

  DNBThreadResumeAction action = {INVALID_NUB_THREAD, eStateStepping, 0,
                                  INVALID_NUB_ADDRESS};

  if (*(p + 1) != '\0') {
    char *end = NULL;
    errno = 0;
    action.signal = static_cast<int>(strtoul(p + 1, &end, 16));
    if (errno != 0)
      return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                    "Could not parse signal in S packet");
    else if (*end == ';') {
      errno = 0;
      action.addr = strtoull(end + 1, NULL, 16);
      if (errno != 0 && action.addr == 0) {
        return HandlePacket_ILLFORMED(__FILE__, __LINE__, p,
                                      "Could not parse address in S packet");
      }
    }
  }

  action.tid = GetContinueThread();
  if (action.tid == 0 || action.tid == (nub_thread_t)-1)
    return SendPacket("E40");

  nub_state_t tstate = DNBThreadGetState(pid, action.tid);
  if (tstate == eStateInvalid || tstate == eStateExited)
    return SendPacket("E37");

  DNBThreadResumeActions thread_actions;
  thread_actions.Append(action);

  // Make all other threads stop when we are stepping
  thread_actions.SetDefaultThreadActionIfNeeded(eStateStopped, 0);
  if (!DNBProcessResume(pid, thread_actions.GetFirst(),
                        thread_actions.GetSize()))
    return SendPacket("E39");

  // Don't send an "OK" packet; response is the stopped/exited message.
  return rnb_success;
}

static const char *GetArchName(const uint32_t cputype,
                               const uint32_t cpusubtype) {
  switch (cputype) {
  case CPU_TYPE_ARM:
    switch (cpusubtype) {
    case 5:
      return "armv4";
    case 6:
      return "armv6";
    case 7:
      return "armv5t";
    case 8:
      return "xscale";
    case 9:
      return "armv7";
    case 10:
      return "armv7f";
    case 11:
      return "armv7s";
    case 12:
      return "armv7k";
    case 14:
      return "armv6m";
    case 15:
      return "armv7m";
    case 16:
      return "armv7em";
    default:
      return "arm";
    }
    break;
  case CPU_TYPE_ARM64:
    return "arm64";
  case CPU_TYPE_ARM64_32:
    return "arm64_32";
  case CPU_TYPE_I386:
    return "i386";
  case CPU_TYPE_X86_64:
    switch (cpusubtype) {
    default:
      return "x86_64";
    case 8:
      return "x86_64h";
    }
    break;
  }
  return NULL;
}

static bool GetHostCPUType(uint32_t &cputype, uint32_t &cpusubtype,
                           uint32_t &is_64_bit_capable, bool &promoted_to_64) {
  static uint32_t g_host_cputype = 0;
  static uint32_t g_host_cpusubtype = 0;
  static uint32_t g_is_64_bit_capable = 0;
  static bool g_promoted_to_64 = false;

  if (g_host_cputype == 0) {
    g_promoted_to_64 = false;
    size_t len = sizeof(uint32_t);
    if (::sysctlbyname("hw.cputype", &g_host_cputype, &len, NULL, 0) == 0) {
      len = sizeof(uint32_t);
      if (::sysctlbyname("hw.cpu64bit_capable", &g_is_64_bit_capable, &len,
                         NULL, 0) == 0) {
        if (g_is_64_bit_capable && ((g_host_cputype & CPU_ARCH_ABI64) == 0)) {
          g_promoted_to_64 = true;
          g_host_cputype |= CPU_ARCH_ABI64;
        }
      }
#if defined (TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
      if (g_host_cputype == CPU_TYPE_ARM64 && sizeof (void*) == 4)
        g_host_cputype = CPU_TYPE_ARM64_32;
#endif
    }

    len = sizeof(uint32_t);
    if (::sysctlbyname("hw.cpusubtype", &g_host_cpusubtype, &len, NULL, 0) ==
        0) {
      if (g_promoted_to_64 && g_host_cputype == CPU_TYPE_X86_64 &&
          g_host_cpusubtype == CPU_SUBTYPE_486)
        g_host_cpusubtype = CPU_SUBTYPE_X86_64_ALL;
    }
#if defined (TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
    // on arm64_32 devices, the machine's native cpu type is
    // CPU_TYPE_ARM64 and subtype is 2 indicating arm64e.
    // But we change the cputype to CPU_TYPE_ARM64_32 because
    // the user processes are all ILP32 processes today.
    // We also need to rewrite the cpusubtype so we vend 
    // a valid cputype + cpusubtype combination.
    if (g_host_cputype == CPU_TYPE_ARM64_32)
      g_host_cpusubtype = CPU_SUBTYPE_ARM64_32_V8;
#endif
  }

  cputype = g_host_cputype;
  cpusubtype = g_host_cpusubtype;
  is_64_bit_capable = g_is_64_bit_capable;
  promoted_to_64 = g_promoted_to_64;
  return g_host_cputype != 0;
}

static bool GetAddressingBits(uint32_t &addressing_bits) {
  static uint32_t g_addressing_bits = 0;
  static bool g_tried_addressing_bits_syscall = false;
  if (g_tried_addressing_bits_syscall == false) {
    size_t len = sizeof (uint32_t);
    if (::sysctlbyname("machdep.virtual_address_size",
          &g_addressing_bits, &len, NULL, 0) != 0) {
      g_addressing_bits = 0;
    }
  }
  g_tried_addressing_bits_syscall = true;
  addressing_bits = g_addressing_bits;
  if (addressing_bits > 0)
    return true;
  else
    return false;
}

rnb_err_t RNBRemote::HandlePacket_qHostInfo(const char *p) {
  std::ostringstream strm;

  uint32_t cputype = 0;
  uint32_t cpusubtype = 0;
  uint32_t is_64_bit_capable = 0;
  bool promoted_to_64 = false;
  if (GetHostCPUType(cputype, cpusubtype, is_64_bit_capable, promoted_to_64)) {
    strm << "cputype:" << std::dec << cputype << ';';
    strm << "cpusubtype:" << std::dec << cpusubtype << ';';
  }

  uint32_t addressing_bits = 0;
  if (GetAddressingBits(addressing_bits)) {
    strm << "addressing_bits:" << std::dec << addressing_bits << ';';
  }

  // The OS in the triple should be "ios" or "macosx" which doesn't match our
  // "Darwin" which gets returned from "kern.ostype", so we need to hardcode
  // this for now.
  if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64
      || cputype == CPU_TYPE_ARM64_32) {
#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
    strm << "ostype:tvos;";
#elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
    strm << "ostype:watchos;";
#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
    strm << "ostype:bridgeos;";
#else
    strm << "ostype:ios;";
#endif

    // On armv7 we use "synchronous" watchpoints which means the exception is
    // delivered before the instruction executes.
    strm << "watchpoint_exceptions_received:before;";
  } else {
    strm << "ostype:macosx;";
    strm << "watchpoint_exceptions_received:after;";
  }
  //    char ostype[64];
  //    len = sizeof(ostype);
  //    if (::sysctlbyname("kern.ostype", &ostype, &len, NULL, 0) == 0)
  //    {
  //        len = strlen(ostype);
  //        std::transform (ostype, ostype + len, ostype, tolower);
  //        strm << "ostype:" << std::dec << ostype << ';';
  //    }

  strm << "vendor:apple;";

  uint64_t major, minor, patch;
  if (DNBGetOSVersionNumbers(&major, &minor, &patch)) {
    strm << "os_version:" << major << "." << minor;
    if (patch != UINT64_MAX)
      strm << "." << patch;
    strm << ";";
  }

  std::string maccatalyst_version = DNBGetMacCatalystVersionString();
  if (!maccatalyst_version.empty() &&
      std::all_of(maccatalyst_version.begin(), maccatalyst_version.end(),
                  [](char c) { return (c >= '0' && c <= '9') || c == '.'; }))
    strm << "maccatalyst_version:" << maccatalyst_version << ";";

#if defined(__LITTLE_ENDIAN__)
  strm << "endian:little;";
#elif defined(__BIG_ENDIAN__)
  strm << "endian:big;";
#elif defined(__PDP_ENDIAN__)
  strm << "endian:pdp;";
#endif

  if (promoted_to_64)
    strm << "ptrsize:8;";
  else
    strm << "ptrsize:" << std::dec << sizeof(void *) << ';';

#if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
  strm << "default_packet_timeout:10;";
#endif

  return SendPacket(strm.str());
}

void XMLElementStart(std::ostringstream &s, uint32_t indent, const char *name,
                     bool has_attributes) {
  if (indent)
    s << INDENT_WITH_SPACES(indent);
  s << '<' << name;
  if (!has_attributes)
    s << '>' << std::endl;
}

void XMLElementStartEndAttributes(std::ostringstream &s, bool empty) {
  if (empty)
    s << '/';
  s << '>' << std::endl;
}

void XMLElementEnd(std::ostringstream &s, uint32_t indent, const char *name) {
  if (indent)
    s << INDENT_WITH_SPACES(indent);
  s << '<' << '/' << name << '>' << std::endl;
}

void XMLElementWithStringValue(std::ostringstream &s, uint32_t indent,
                               const char *name, const char *value,
                               bool close = true) {
  if (value) {
    if (indent)
      s << INDENT_WITH_SPACES(indent);
    s << '<' << name << '>' << value;
    if (close)
      XMLElementEnd(s, 0, name);
  }
}

void XMLElementWithUnsignedValue(std::ostringstream &s, uint32_t indent,
                                 const char *name, uint64_t value,
                                 bool close = true) {
  if (indent)
    s << INDENT_WITH_SPACES(indent);

  s << '<' << name << '>' << DECIMAL << value;
  if (close)
    XMLElementEnd(s, 0, name);
}

void XMLAttributeString(std::ostringstream &s, const char *name,
                        const char *value, const char *default_value = NULL) {
  if (value) {
    if (default_value && strcmp(value, default_value) == 0)
      return; // No need to emit the attribute because it matches the default
              // value
    s << ' ' << name << "=\"" << value << "\"";
  }
}

void XMLAttributeUnsignedDecimal(std::ostringstream &s, const char *name,
                                 uint64_t value) {
  s << ' ' << name << "=\"" << DECIMAL << value << "\"";
}

void GenerateTargetXMLRegister(std::ostringstream &s, const uint32_t reg_num,
                               nub_size_t num_reg_sets,
                               const DNBRegisterSetInfo *reg_set_info,
                               const register_map_entry_t &reg) {
  const char *default_lldb_encoding = "uint";
  const char *lldb_encoding = default_lldb_encoding;
  const char *gdb_group = "general";
  const char *default_gdb_type = "int";
  const char *gdb_type = default_gdb_type;
  const char *default_lldb_format = "hex";
  const char *lldb_format = default_lldb_format;
  const char *lldb_set = NULL;

  switch (reg.nub_info.type) {
  case Uint:
    lldb_encoding = "uint";
    break;
  case Sint:
    lldb_encoding = "sint";
    break;
  case IEEE754:
    lldb_encoding = "ieee754";
    if (reg.nub_info.set > 0)
      gdb_group = "float";
    break;
  case Vector:
    lldb_encoding = "vector";
    if (reg.nub_info.set > 0)
      gdb_group = "vector";
    break;
  }

  switch (reg.nub_info.format) {
  case Binary:
    lldb_format = "binary";
    break;
  case Decimal:
    lldb_format = "decimal";
    break;
  case Hex:
    lldb_format = "hex";
    break;
  case Float:
    gdb_type = "float";
    lldb_format = "float";
    break;
  case VectorOfSInt8:
    gdb_type = "float";
    lldb_format = "vector-sint8";
    break;
  case VectorOfUInt8:
    gdb_type = "float";
    lldb_format = "vector-uint8";
    break;
  case VectorOfSInt16:
    gdb_type = "float";
    lldb_format = "vector-sint16";
    break;
  case VectorOfUInt16:
    gdb_type = "float";
    lldb_format = "vector-uint16";
    break;
  case VectorOfSInt32:
    gdb_type = "float";
    lldb_format = "vector-sint32";
    break;
  case VectorOfUInt32:
    gdb_type = "float";
    lldb_format = "vector-uint32";
    break;
  case VectorOfFloat32:
    gdb_type = "float";
    lldb_format = "vector-float32";
    break;
  case VectorOfUInt128:
    gdb_type = "float";
    lldb_format = "vector-uint128";
    break;
  };
  if (reg_set_info && reg.nub_info.set < num_reg_sets)
    lldb_set = reg_set_info[reg.nub_info.set].name;

  uint32_t indent = 2;

  XMLElementStart(s, indent, "reg", true);
  XMLAttributeString(s, "name", reg.nub_info.name);
  XMLAttributeUnsignedDecimal(s, "regnum", reg_num);
  XMLAttributeUnsignedDecimal(s, "offset", reg.offset);
  XMLAttributeUnsignedDecimal(s, "bitsize", reg.nub_info.size * 8);
  XMLAttributeString(s, "group", gdb_group);
  XMLAttributeString(s, "type", gdb_type, default_gdb_type);
  XMLAttributeString(s, "altname", reg.nub_info.alt);
  XMLAttributeString(s, "encoding", lldb_encoding, default_lldb_encoding);
  XMLAttributeString(s, "format", lldb_format, default_lldb_format);
  XMLAttributeUnsignedDecimal(s, "group_id", reg.nub_info.set);
  if (reg.nub_info.reg_ehframe != INVALID_NUB_REGNUM)
    XMLAttributeUnsignedDecimal(s, "ehframe_regnum", reg.nub_info.reg_ehframe);
  if (reg.nub_info.reg_dwarf != INVALID_NUB_REGNUM)
    XMLAttributeUnsignedDecimal(s, "dwarf_regnum", reg.nub_info.reg_dwarf);

  const char *lldb_generic = NULL;
  switch (reg.nub_info.reg_generic) {
  case GENERIC_REGNUM_FP:
    lldb_generic = "fp";
    break;
  case GENERIC_REGNUM_PC:
    lldb_generic = "pc";
    break;
  case GENERIC_REGNUM_SP:
    lldb_generic = "sp";
    break;
  case GENERIC_REGNUM_RA:
    lldb_generic = "ra";
    break;
  case GENERIC_REGNUM_FLAGS:
    lldb_generic = "flags";
    break;
  case GENERIC_REGNUM_ARG1:
    lldb_generic = "arg1";
    break;
  case GENERIC_REGNUM_ARG2:
    lldb_generic = "arg2";
    break;
  case GENERIC_REGNUM_ARG3:
    lldb_generic = "arg3";
    break;
  case GENERIC_REGNUM_ARG4:
    lldb_generic = "arg4";
    break;
  case GENERIC_REGNUM_ARG5:
    lldb_generic = "arg5";
    break;
  case GENERIC_REGNUM_ARG6:
    lldb_generic = "arg6";
    break;
  case GENERIC_REGNUM_ARG7:
    lldb_generic = "arg7";
    break;
  case GENERIC_REGNUM_ARG8:
    lldb_generic = "arg8";
    break;
  default:
    break;
  }
  XMLAttributeString(s, "generic", lldb_generic);

  bool empty = reg.value_regnums.empty() && reg.invalidate_regnums.empty();
  if (!empty) {
    if (!reg.value_regnums.empty()) {
      std::ostringstream regnums;
      bool first = true;
      regnums << DECIMAL;
      for (auto regnum : reg.value_regnums) {
        if (!first)
          regnums << ',';
        regnums << regnum;
        first = false;
      }
      XMLAttributeString(s, "value_regnums", regnums.str().c_str());
    }

    if (!reg.invalidate_regnums.empty()) {
      std::ostringstream regnums;
      bool first = true;
      regnums << DECIMAL;
      for (auto regnum : reg.invalidate_regnums) {
        if (!first)
          regnums << ',';
        regnums << regnum;
        first = false;
      }
      XMLAttributeString(s, "invalidate_regnums", regnums.str().c_str());
    }
  }
  XMLElementStartEndAttributes(s, true);
}

void GenerateTargetXMLRegisters(std::ostringstream &s) {
  nub_size_t num_reg_sets = 0;
  const DNBRegisterSetInfo *reg_sets = DNBGetRegisterSetInfo(&num_reg_sets);

  uint32_t cputype = DNBGetRegisterCPUType();
  if (cputype) {
    XMLElementStart(s, 0, "feature", true);
    std::ostringstream name_strm;
    name_strm << "com.apple.debugserver." << GetArchName(cputype, 0);
    XMLAttributeString(s, "name", name_strm.str().c_str());
    XMLElementStartEndAttributes(s, false);
    for (uint32_t reg_num = 0; reg_num < g_num_reg_entries; ++reg_num)
    //        for (const auto &reg: g_dynamic_register_map)
    {
      GenerateTargetXMLRegister(s, reg_num, num_reg_sets, reg_sets,
                                g_reg_entries[reg_num]);
    }
    XMLElementEnd(s, 0, "feature");

    if (num_reg_sets > 0) {
      XMLElementStart(s, 0, "groups", false);
      for (uint32_t set = 1; set < num_reg_sets; ++set) {
        XMLElementStart(s, 2, "group", true);
        XMLAttributeUnsignedDecimal(s, "id", set);
        XMLAttributeString(s, "name", reg_sets[set].name);
        XMLElementStartEndAttributes(s, true);
      }
      XMLElementEnd(s, 0, "groups");
    }
  }
}

static const char *g_target_xml_header = R"(<?xml version="1.0"?>
<target version="1.0">)";

static const char *g_target_xml_footer = "</target>";

static std::string g_target_xml;

void UpdateTargetXML() {
  std::ostringstream s;
  s << g_target_xml_header << std::endl;

  // Set the architecture
  //
  // On raw targets (no OS, vendor info), I've seen replies like
  // <architecture>i386:x86-64</architecture> (for x86_64 systems - from vmware)
  // <architecture>arm</architecture> (for an unspecified arm device - from a Segger JLink)
  // For good interop, I'm not sure what's expected here.  e.g. will anyone understand
  // <architecture>x86_64</architecture> ? Or is i386:x86_64 the expected phrasing?
  //
  // s << "<architecture>" << arch "</architecture>" << std::endl;

  // Set the OSABI
  // s << "<osabi>abi-name</osabi>"

  GenerateTargetXMLRegisters(s);

  s << g_target_xml_footer << std::endl;

  // Save the XML output in case it gets retrieved in chunks
  g_target_xml = s.str();
}

rnb_err_t RNBRemote::HandlePacket_qXfer(const char *command) {
  const char *p = command;
  p += strlen("qXfer:");
  const char *sep = strchr(p, ':');
  if (sep) {
    std::string object(p, sep - p); // "auxv", "backtrace", "features", etc
    p = sep + 1;
    sep = strchr(p, ':');
    if (sep) {
      std::string rw(p, sep - p); // "read" or "write"
      p = sep + 1;
      sep = strchr(p, ':');
      if (sep) {
        std::string annex(p, sep - p); // "read" or "write"

        p = sep + 1;
        sep = strchr(p, ',');
        if (sep) {
          std::string offset_str(p, sep - p); // read the length as a string
          p = sep + 1;
          std::string length_str(p); // read the offset as a string
          char *end = nullptr;
          const uint64_t offset = strtoul(offset_str.c_str(), &end,
                                          16); // convert offset_str to a offset
          if (*end == '\0') {
            const uint64_t length = strtoul(
                length_str.c_str(), &end, 16); // convert length_str to a length
            if (*end == '\0') {
              if (object == "features" && rw == "read" &&
                  annex == "target.xml") {
                std::ostringstream xml_out;

                if (offset == 0) {
                  InitializeRegisters(true);

                  UpdateTargetXML();
                  if (g_target_xml.empty())
                    return SendPacket("E83");

                  if (length > g_target_xml.size()) {
                    xml_out << 'l'; // No more data
                    xml_out << binary_encode_string(g_target_xml);
                  } else {
                    xml_out << 'm'; // More data needs to be read with a
                                    // subsequent call
                    xml_out << binary_encode_string(
                        std::string(g_target_xml, offset, length));
                  }
                } else {
                  // Retrieving target XML in chunks
                  if (offset < g_target_xml.size()) {
                    std::string chunk(g_target_xml, offset, length);
                    if (chunk.size() < length)
                      xml_out << 'l'; // No more data
                    else
                      xml_out << 'm'; // More data needs to be read with a
                                      // subsequent call
                    xml_out << binary_encode_string(chunk.data());
                  }
                }
                return SendPacket(xml_out.str());
              }
              // Well formed, put not supported
              return HandlePacket_UNIMPLEMENTED(command);
            }
          }
        }
      } else {
        SendPacket("E85");
      }
    } else {
      SendPacket("E86");
    }
  }
  return SendPacket("E82");
}

rnb_err_t RNBRemote::HandlePacket_qGDBServerVersion(const char *p) {
  std::ostringstream strm;

#if defined(DEBUGSERVER_PROGRAM_NAME)
  strm << "name:" DEBUGSERVER_PROGRAM_NAME ";";
#else
  strm << "name:debugserver;";
#endif
  strm << "version:" << DEBUGSERVER_VERSION_NUM << ";";

  return SendPacket(strm.str());
}

// A helper function that retrieves a single integer value from
// a one-level-deep JSON dictionary of key-value pairs.  e.g.
// jThreadExtendedInfo:{"plo_pthread_tsd_base_address_offset":0,"plo_pthread_tsd_base_offset":224,"plo_pthread_tsd_entry_size":8,"thread":144305}]
//
uint64_t get_integer_value_for_key_name_from_json(const char *key,
                                                  const char *json_string) {
  uint64_t retval = INVALID_NUB_ADDRESS;
  std::string key_with_quotes = "\"";
  key_with_quotes += key;
  key_with_quotes += "\"";
  const char *c = strstr(json_string, key_with_quotes.c_str());
  if (c) {
    c += key_with_quotes.size();

    while (*c != '\0' && (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
      c++;

    if (*c == ':') {
      c++;

      while (*c != '\0' &&
             (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
        c++;

      errno = 0;
      retval = strtoul(c, NULL, 10);
      if (errno != 0) {
        retval = INVALID_NUB_ADDRESS;
      }
    }
  }
  return retval;
}

// A helper function that retrieves a boolean value from
// a one-level-deep JSON dictionary of key-value pairs.  e.g.
// jGetLoadedDynamicLibrariesInfos:{"fetch_all_solibs":true}]

// Returns true if it was able to find the key name, and sets the 'value'
// argument to the value found.

bool get_boolean_value_for_key_name_from_json(const char *key,
                                              const char *json_string,
                                              bool &value) {
  std::string key_with_quotes = "\"";
  key_with_quotes += key;
  key_with_quotes += "\"";
  const char *c = strstr(json_string, key_with_quotes.c_str());
  if (c) {
    c += key_with_quotes.size();

    while (*c != '\0' && (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
      c++;

    if (*c == ':') {
      c++;

      while (*c != '\0' &&
             (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
        c++;

      if (strncmp(c, "true", 4) == 0) {
        value = true;
        return true;
      } else if (strncmp(c, "false", 5) == 0) {
        value = false;
        return true;
      }
    }
  }
  return false;
}

// A helper function that reads an array of uint64_t's from
// a one-level-deep JSON dictionary of key-value pairs.  e.g.
// jGetLoadedDynamicLibrariesInfos:{"solib_addrs":[31345823,7768020384,7310483024]}]

// Returns true if it was able to find the key name, false if it did not.
// "ints" will have all integers found in the array appended to it.

bool get_array_of_ints_value_for_key_name_from_json(
    const char *key, const char *json_string, std::vector<uint64_t> &ints) {
  std::string key_with_quotes = "\"";
  key_with_quotes += key;
  key_with_quotes += "\"";
  const char *c = strstr(json_string, key_with_quotes.c_str());
  if (c) {
    c += key_with_quotes.size();

    while (*c != '\0' && (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
      c++;

    if (*c == ':') {
      c++;

      while (*c != '\0' &&
             (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
        c++;

      if (*c == '[') {
        c++;
        while (*c != '\0' &&
               (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
          c++;
        while (true) {
          if (!isdigit(*c)) {
            return true;
          }

          errno = 0;
          char *endptr;
          uint64_t value = strtoul(c, &endptr, 10);
          if (errno == 0) {
            ints.push_back(value);
          } else {
            break;
          }
          if (endptr == c || endptr == nullptr || *endptr == '\0') {
            break;
          }
          c = endptr;

          while (*c != '\0' &&
                 (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
            c++;
          if (*c == ',')
            c++;
          while (*c != '\0' &&
                 (*c == ' ' || *c == '\t' || *c == '\n' || *c == '\r'))
            c++;
          if (*c == ']') {
            return true;
          }
        }
      }
    }
  }
  return false;
}

JSONGenerator::ObjectSP
RNBRemote::GetJSONThreadsInfo(bool threads_with_valid_stop_info_only) {
  JSONGenerator::ArraySP threads_array_sp;
  if (m_ctx.HasValidProcessID()) {
    threads_array_sp = std::make_shared<JSONGenerator::Array>();

    nub_process_t pid = m_ctx.ProcessID();

    nub_size_t numthreads = DNBProcessGetNumThreads(pid);
    for (nub_size_t i = 0; i < numthreads; ++i) {
      nub_thread_t tid = DNBProcessGetThreadAtIndex(pid, i);

      struct DNBThreadStopInfo tid_stop_info;

      const bool stop_info_valid =
          DNBThreadGetStopReason(pid, tid, &tid_stop_info);

      // If we are doing stop info only, then we only show threads that have a
      // valid stop reason
      if (threads_with_valid_stop_info_only) {
        if (!stop_info_valid || tid_stop_info.reason == eStopTypeInvalid)
          continue;
      }

      JSONGenerator::DictionarySP thread_dict_sp(
          new JSONGenerator::Dictionary());
      thread_dict_sp->AddIntegerItem("tid", tid);

      std::string reason_value("none");

      if (stop_info_valid) {
        switch (tid_stop_info.reason) {
        case eStopTypeInvalid:
          break;

        case eStopTypeSignal:
          if (tid_stop_info.details.signal.signo != 0) {
            thread_dict_sp->AddIntegerItem("signal",
                                           tid_stop_info.details.signal.signo);
            reason_value = "signal";
          }
          break;

        case eStopTypeException:
          if (tid_stop_info.details.exception.type != 0) {
            reason_value = "exception";
            thread_dict_sp->AddIntegerItem(
                "metype", tid_stop_info.details.exception.type);
            JSONGenerator::ArraySP medata_array_sp(new JSONGenerator::Array());
            for (nub_size_t i = 0;
                 i < tid_stop_info.details.exception.data_count; ++i) {
              medata_array_sp->AddItem(
                  JSONGenerator::IntegerSP(new JSONGenerator::Integer(
                      tid_stop_info.details.exception.data[i])));
            }
            thread_dict_sp->AddItem("medata", medata_array_sp);
          }
          break;

        case eStopTypeExec:
          reason_value = "exec";
          break;
        }
      }

      thread_dict_sp->AddStringItem("reason", reason_value);

      if (!threads_with_valid_stop_info_only) {
        const char *thread_name = DNBThreadGetName(pid, tid);
        if (thread_name && thread_name[0])
          thread_dict_sp->AddStringItem("name", thread_name);

        thread_identifier_info_data_t thread_ident_info;
        if (DNBThreadGetIdentifierInfo(pid, tid, &thread_ident_info)) {
          if (thread_ident_info.dispatch_qaddr != 0) {
            thread_dict_sp->AddIntegerItem("qaddr",
                                           thread_ident_info.dispatch_qaddr);

            const DispatchQueueOffsets *dispatch_queue_offsets =
                GetDispatchQueueOffsets();
            if (dispatch_queue_offsets) {
              std::string queue_name;
              uint64_t queue_width = 0;
              uint64_t queue_serialnum = 0;
              nub_addr_t dispatch_queue_t = INVALID_NUB_ADDRESS;
              dispatch_queue_offsets->GetThreadQueueInfo(
                  pid, thread_ident_info.dispatch_qaddr, dispatch_queue_t,
                  queue_name, queue_width, queue_serialnum);
              if (dispatch_queue_t == 0 && queue_name.empty() &&
                  queue_serialnum == 0) {
                thread_dict_sp->AddBooleanItem("associated_with_dispatch_queue",
                                               false);
              } else {
                thread_dict_sp->AddBooleanItem("associated_with_dispatch_queue",
                                               true);
              }
              if (dispatch_queue_t != INVALID_NUB_ADDRESS &&
                  dispatch_queue_t != 0)
                thread_dict_sp->AddIntegerItem("dispatch_queue_t",
                                               dispatch_queue_t);
              if (!queue_name.empty())
                thread_dict_sp->AddStringItem("qname", queue_name);
              if (queue_width == 1)
                thread_dict_sp->AddStringItem("qkind", "serial");
              else if (queue_width > 1)
                thread_dict_sp->AddStringItem("qkind", "concurrent");
              if (queue_serialnum > 0)
                thread_dict_sp->AddIntegerItem("qserialnum", queue_serialnum);
            }
          }
        }

        DNBRegisterValue reg_value;

        if (g_reg_entries != NULL) {
          JSONGenerator::DictionarySP registers_dict_sp(
              new JSONGenerator::Dictionary());

          for (uint32_t reg = 0; reg < g_num_reg_entries; reg++) {
            // Expedite all registers in the first register set that aren't
            // contained in other registers
            if (g_reg_entries[reg].nub_info.set == 1 &&
                g_reg_entries[reg].nub_info.value_regs == NULL) {
              if (!DNBThreadGetRegisterValueByID(
                      pid, tid, g_reg_entries[reg].nub_info.set,
                      g_reg_entries[reg].nub_info.reg, &reg_value))
                continue;

              std::ostringstream reg_num;
              reg_num << std::dec << g_reg_entries[reg].debugserver_regnum;
              // Encode native byte ordered bytes as hex ascii
              registers_dict_sp->AddBytesAsHexASCIIString(
                  reg_num.str(), reg_value.value.v_uint8,
                  g_reg_entries[reg].nub_info.size);
            }
          }
          thread_dict_sp->AddItem("registers", registers_dict_sp);
        }

        // Add expedited stack memory so stack backtracing doesn't need to read
        // anything from the
        // frame pointer chain.
        StackMemoryMap stack_mmap;
        ReadStackMemory(pid, tid, stack_mmap);
        if (!stack_mmap.empty()) {
          JSONGenerator::ArraySP memory_array_sp(new JSONGenerator::Array());

          for (const auto &stack_memory : stack_mmap) {
            JSONGenerator::DictionarySP stack_memory_sp(
                new JSONGenerator::Dictionary());
            stack_memory_sp->AddIntegerItem("address", stack_memory.first);
            stack_memory_sp->AddBytesAsHexASCIIString(
                "bytes", stack_memory.second.bytes, stack_memory.second.length);
            memory_array_sp->AddItem(stack_memory_sp);
          }
          thread_dict_sp->AddItem("memory", memory_array_sp);
        }
      }

      threads_array_sp->AddItem(thread_dict_sp);
    }
  }
  return threads_array_sp;
}

rnb_err_t RNBRemote::HandlePacket_jThreadsInfo(const char *p) {
  JSONGenerator::ObjectSP threads_info_sp;
  std::ostringstream json;
  std::ostringstream reply_strm;
  // If we haven't run the process yet, return an error.
  if (m_ctx.HasValidProcessID()) {
    const bool threads_with_valid_stop_info_only = false;
    JSONGenerator::ObjectSP threads_info_sp =
        GetJSONThreadsInfo(threads_with_valid_stop_info_only);

    if (threads_info_sp) {
      std::ostringstream strm;
      threads_info_sp->Dump(strm);
      std::string binary_packet = binary_encode_string(strm.str());
      if (!binary_packet.empty())
        return SendPacket(binary_packet.c_str());
    }
  }
  return SendPacket("E85");
}

rnb_err_t RNBRemote::HandlePacket_jThreadExtendedInfo(const char *p) {
  nub_process_t pid;
  std::ostringstream json;
  // If we haven't run the process yet, return an error.
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E81");
  }

  pid = m_ctx.ProcessID();

  const char thread_extended_info_str[] = {"jThreadExtendedInfo:{"};
  if (strncmp(p, thread_extended_info_str,
              sizeof(thread_extended_info_str) - 1) == 0) {
    p += strlen(thread_extended_info_str);

    uint64_t tid = get_integer_value_for_key_name_from_json("thread", p);
    uint64_t plo_pthread_tsd_base_address_offset =
        get_integer_value_for_key_name_from_json(
            "plo_pthread_tsd_base_address_offset", p);
    uint64_t plo_pthread_tsd_base_offset =
        get_integer_value_for_key_name_from_json("plo_pthread_tsd_base_offset",
                                                 p);
    uint64_t plo_pthread_tsd_entry_size =
        get_integer_value_for_key_name_from_json("plo_pthread_tsd_entry_size",
                                                 p);
    uint64_t dti_qos_class_index =
        get_integer_value_for_key_name_from_json("dti_qos_class_index", p);

    if (tid != INVALID_NUB_ADDRESS) {
      nub_addr_t pthread_t_value = DNBGetPThreadT(pid, tid);

      uint64_t tsd_address = INVALID_NUB_ADDRESS;
      if (plo_pthread_tsd_entry_size != INVALID_NUB_ADDRESS &&
          plo_pthread_tsd_base_offset != INVALID_NUB_ADDRESS &&
          plo_pthread_tsd_entry_size != INVALID_NUB_ADDRESS) {
        tsd_address = DNBGetTSDAddressForThread(
            pid, tid, plo_pthread_tsd_base_address_offset,
            plo_pthread_tsd_base_offset, plo_pthread_tsd_entry_size);
      }

      bool timed_out = false;
      Genealogy::ThreadActivitySP thread_activity_sp;

      // If the pthread_t value is invalid, or if we were able to fetch the
      // thread's TSD base
      // and got an invalid value back, then we have a thread in early startup
      // or shutdown and
      // it's possible that gathering the genealogy information for this thread
      // go badly.
      // Ideally fetching this info for a thread in these odd states shouldn't
      // matter - but
      // we've seen some problems with these new SPI and threads in edge-casey
      // states.

      double genealogy_fetch_time = 0;
      if (pthread_t_value != INVALID_NUB_ADDRESS &&
          tsd_address != INVALID_NUB_ADDRESS) {
        DNBTimer timer(false);
        thread_activity_sp = DNBGetGenealogyInfoForThread(pid, tid, timed_out);
        genealogy_fetch_time = timer.ElapsedMicroSeconds(false) / 1000000.0;
      }

      std::unordered_set<uint32_t>
          process_info_indexes; // an array of the process info #'s seen

      json << "{";

      bool need_to_print_comma = false;

      if (thread_activity_sp && !timed_out) {
        const Genealogy::Activity *activity =
            &thread_activity_sp->current_activity;
        bool need_vouchers_comma_sep = false;
        json << "\"activity_query_timed_out\":false,";
        if (genealogy_fetch_time != 0) {
          //  If we append the floating point value with << we'll get it in
          //  scientific
          //  notation.
          char floating_point_ascii_buffer[64];
          floating_point_ascii_buffer[0] = '\0';
          snprintf(floating_point_ascii_buffer,
                   sizeof(floating_point_ascii_buffer), "%f",
                   genealogy_fetch_time);
          if (strlen(floating_point_ascii_buffer) > 0) {
            if (need_to_print_comma)
              json << ",";
            need_to_print_comma = true;
            json << "\"activity_query_duration\":"
                 << floating_point_ascii_buffer;
          }
        }
        if (activity->activity_id != 0) {
          if (need_to_print_comma)
            json << ",";
          need_to_print_comma = true;
          need_vouchers_comma_sep = true;
          json << "\"activity\":{";
          json << "\"start\":" << activity->activity_start << ",";
          json << "\"id\":" << activity->activity_id << ",";
          json << "\"parent_id\":" << activity->parent_id << ",";
          json << "\"name\":\""
               << json_string_quote_metachars(activity->activity_name) << "\",";
          json << "\"reason\":\""
               << json_string_quote_metachars(activity->reason) << "\"";
          json << "}";
        }
        if (thread_activity_sp->messages.size() > 0) {
          need_to_print_comma = true;
          if (need_vouchers_comma_sep)
            json << ",";
          need_vouchers_comma_sep = true;
          json << "\"trace_messages\":[";
          bool printed_one_message = false;
          for (auto iter = thread_activity_sp->messages.begin();
               iter != thread_activity_sp->messages.end(); ++iter) {
            if (printed_one_message)
              json << ",";
            else
              printed_one_message = true;
            json << "{";
            json << "\"timestamp\":" << iter->timestamp << ",";
            json << "\"activity_id\":" << iter->activity_id << ",";
            json << "\"trace_id\":" << iter->trace_id << ",";
            json << "\"thread\":" << iter->thread << ",";
            json << "\"type\":" << (int)iter->type << ",";
            json << "\"process_info_index\":" << iter->process_info_index
                 << ",";
            process_info_indexes.insert(iter->process_info_index);
            json << "\"message\":\""
                 << json_string_quote_metachars(iter->message) << "\"";
            json << "}";
          }
          json << "]";
        }
        if (thread_activity_sp->breadcrumbs.size() == 1) {
          need_to_print_comma = true;
          if (need_vouchers_comma_sep)
            json << ",";
          need_vouchers_comma_sep = true;
          json << "\"breadcrumb\":{";
          for (auto iter = thread_activity_sp->breadcrumbs.begin();
               iter != thread_activity_sp->breadcrumbs.end(); ++iter) {
            json << "\"breadcrumb_id\":" << iter->breadcrumb_id << ",";
            json << "\"activity_id\":" << iter->activity_id << ",";
            json << "\"timestamp\":" << iter->timestamp << ",";
            json << "\"name\":\"" << json_string_quote_metachars(iter->name)
                 << "\"";
          }
          json << "}";
        }
        if (process_info_indexes.size() > 0) {
          need_to_print_comma = true;
          if (need_vouchers_comma_sep)
            json << ",";
          need_vouchers_comma_sep = true;
          bool printed_one_process_info = false;
          for (auto iter = process_info_indexes.begin();
               iter != process_info_indexes.end(); ++iter) {
            if (printed_one_process_info)
              json << ",";
            Genealogy::ProcessExecutableInfoSP image_info_sp;
            uint32_t idx = *iter;
            image_info_sp = DNBGetGenealogyImageInfo(pid, idx);
            if (image_info_sp) {
              if (!printed_one_process_info) {
                json << "\"process_infos\":[";
                printed_one_process_info = true;
              }

              json << "{";
              char uuid_buf[37];
              uuid_unparse_upper(image_info_sp->image_uuid, uuid_buf);
              json << "\"process_info_index\":" << idx << ",";
              json << "\"image_path\":\""
                   << json_string_quote_metachars(image_info_sp->image_path)
                   << "\",";
              json << "\"image_uuid\":\"" << uuid_buf << "\"";
              json << "}";
            }
          }
          if (printed_one_process_info)
            json << "]";
        }
      } else {
        if (timed_out) {
          if (need_to_print_comma)
            json << ",";
          need_to_print_comma = true;
          json << "\"activity_query_timed_out\":true";
          if (genealogy_fetch_time != 0) {
            //  If we append the floating point value with << we'll get it in
            //  scientific
            //  notation.
            char floating_point_ascii_buffer[64];
            floating_point_ascii_buffer[0] = '\0';
            snprintf(floating_point_ascii_buffer,
                     sizeof(floating_point_ascii_buffer), "%f",
                     genealogy_fetch_time);
            if (strlen(floating_point_ascii_buffer) > 0) {
              json << ",";
              json << "\"activity_query_duration\":"
                   << floating_point_ascii_buffer;
            }
          }
        }
      }

      if (tsd_address != INVALID_NUB_ADDRESS) {
        if (need_to_print_comma)
          json << ",";
        need_to_print_comma = true;
        json << "\"tsd_address\":" << tsd_address;

        if (dti_qos_class_index != 0 && dti_qos_class_index != UINT64_MAX) {
          ThreadInfo::QoS requested_qos = DNBGetRequestedQoSForThread(
              pid, tid, tsd_address, dti_qos_class_index);
          if (requested_qos.IsValid()) {
            if (need_to_print_comma)
              json << ",";
            need_to_print_comma = true;
            json << "\"requested_qos\":{";
            json << "\"enum_value\":" << requested_qos.enum_value << ",";
            json << "\"constant_name\":\""
                 << json_string_quote_metachars(requested_qos.constant_name)
                 << "\",";
            json << "\"printable_name\":\""
                 << json_string_quote_metachars(requested_qos.printable_name)
                 << "\"";
            json << "}";
          }
        }
      }

      if (pthread_t_value != INVALID_NUB_ADDRESS) {
        if (need_to_print_comma)
          json << ",";
        need_to_print_comma = true;
        json << "\"pthread_t\":" << pthread_t_value;
      }

      nub_addr_t dispatch_queue_t_value = DNBGetDispatchQueueT(pid, tid);
      if (dispatch_queue_t_value != INVALID_NUB_ADDRESS) {
        if (need_to_print_comma)
          json << ",";
        need_to_print_comma = true;
        json << "\"dispatch_queue_t\":" << dispatch_queue_t_value;
      }

      json << "}";
      std::string json_quoted = binary_encode_string(json.str());
      return SendPacket(json_quoted);
    }
  }
  return SendPacket("OK");
}

//  This packet may be called in one of three ways:
//
//  jGetLoadedDynamicLibrariesInfos:{"image_count":40,"image_list_address":4295244704}
//      Look for an array of the old dyld_all_image_infos style of binary infos
//      at the image_list_address.
//      This an array of {void* load_addr, void* mod_date, void* pathname}
//
//  jGetLoadedDynamicLibrariesInfos:{"fetch_all_solibs":true}
//      Use the new style (macOS 10.12, tvOS 10, iOS 10, watchOS 3) dyld SPI to
//      get a list of all the
//      libraries loaded
//
//  jGetLoadedDynamicLibrariesInfos:{"solib_addresses":[8382824135,3258302053,830202858503]}
//      Use the new style (macOS 10.12, tvOS 10, iOS 10, watchOS 3) dyld SPI to
//      get the information
//      about the libraries loaded at these addresses.
//
rnb_err_t
RNBRemote::HandlePacket_jGetLoadedDynamicLibrariesInfos(const char *p) {
  nub_process_t pid;
  // If we haven't run the process yet, return an error.
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E83");
  }

  pid = m_ctx.ProcessID();

  const char get_loaded_dynamic_libraries_infos_str[] = {
      "jGetLoadedDynamicLibrariesInfos:{"};
  if (strncmp(p, get_loaded_dynamic_libraries_infos_str,
              sizeof(get_loaded_dynamic_libraries_infos_str) - 1) == 0) {
    p += strlen(get_loaded_dynamic_libraries_infos_str);

    JSONGenerator::ObjectSP json_sp;

    std::vector<uint64_t> macho_addresses;
    bool fetch_all_solibs = false;
    if (get_boolean_value_for_key_name_from_json("fetch_all_solibs", p,
                                                 fetch_all_solibs) &&
        fetch_all_solibs) {
      json_sp = DNBGetAllLoadedLibrariesInfos(pid);
    } else if (get_array_of_ints_value_for_key_name_from_json(
                   "solib_addresses", p, macho_addresses)) {
      json_sp = DNBGetLibrariesInfoForAddresses(pid, macho_addresses);
    } else {
      nub_addr_t image_list_address =
          get_integer_value_for_key_name_from_json("image_list_address", p);
      nub_addr_t image_count =
          get_integer_value_for_key_name_from_json("image_count", p);

      if (image_list_address != INVALID_NUB_ADDRESS &&
          image_count != INVALID_NUB_ADDRESS) {
        json_sp = DNBGetLoadedDynamicLibrariesInfos(pid, image_list_address,
                                                    image_count);
      }
    }

    if (json_sp.get()) {
      std::ostringstream json_str;
      json_sp->Dump(json_str);
      if (json_str.str().size() > 0) {
        std::string json_str_quoted = binary_encode_string(json_str.str());
        return SendPacket(json_str_quoted.c_str());
      } else {
        SendPacket("E84");
      }
    }
  }
  return SendPacket("OK");
}

// This packet does not currently take any arguments.  So the behavior is
//    jGetSharedCacheInfo:{}
//         send information about the inferior's shared cache
//    jGetSharedCacheInfo:
//         send "OK" to indicate that this packet is supported
rnb_err_t RNBRemote::HandlePacket_jGetSharedCacheInfo(const char *p) {
  nub_process_t pid;
  // If we haven't run the process yet, return an error.
  if (!m_ctx.HasValidProcessID()) {
    return SendPacket("E85");
  }

  pid = m_ctx.ProcessID();

  const char get_shared_cache_info_str[] = {"jGetSharedCacheInfo:{"};
  if (strncmp(p, get_shared_cache_info_str,
              sizeof(get_shared_cache_info_str) - 1) == 0) {
    JSONGenerator::ObjectSP json_sp = DNBGetSharedCacheInfo(pid);

    if (json_sp.get()) {
      std::ostringstream json_str;
      json_sp->Dump(json_str);
      if (json_str.str().size() > 0) {
        std::string json_str_quoted = binary_encode_string(json_str.str());
        return SendPacket(json_str_quoted.c_str());
      } else {
        SendPacket("E86");
      }
    }
  }
  return SendPacket("OK");
}

static bool MachHeaderIsMainExecutable(nub_process_t pid, uint32_t addr_size,
                                       nub_addr_t mach_header_addr,
                                       mach_header &mh) {
  DNBLogThreadedIf(LOG_RNB_PROC, "GetMachHeaderForMainExecutable(pid = %u, "
                                 "addr_size = %u, mach_header_addr = "
                                 "0x%16.16llx)",
                   pid, addr_size, mach_header_addr);
  const nub_size_t bytes_read =
      DNBProcessMemoryRead(pid, mach_header_addr, sizeof(mh), &mh);
  if (bytes_read == sizeof(mh)) {
    DNBLogThreadedIf(
        LOG_RNB_PROC, "GetMachHeaderForMainExecutable(pid = %u, addr_size = "
                      "%u, mach_header_addr = 0x%16.16llx): mh = {\n  magic = "
                      "0x%8.8x\n  cpu = 0x%8.8x\n  sub = 0x%8.8x\n  filetype = "
                      "%u\n  ncmds = %u\n  sizeofcmds = 0x%8.8x\n  flags = "
                      "0x%8.8x }",
        pid, addr_size, mach_header_addr, mh.magic, mh.cputype, mh.cpusubtype,
        mh.filetype, mh.ncmds, mh.sizeofcmds, mh.flags);
    if ((addr_size == 4 && mh.magic == MH_MAGIC) ||
        (addr_size == 8 && mh.magic == MH_MAGIC_64)) {
      if (mh.filetype == MH_EXECUTE) {
        DNBLogThreadedIf(LOG_RNB_PROC, "GetMachHeaderForMainExecutable(pid = "
                                       "%u, addr_size = %u, mach_header_addr = "
                                       "0x%16.16llx) -> this is the "
                                       "executable!!!",
                         pid, addr_size, mach_header_addr);
        return true;
      }
    }
  }
  return false;
}

static nub_addr_t GetMachHeaderForMainExecutable(const nub_process_t pid,
                                                 const uint32_t addr_size,
                                                 mach_header &mh) {
  struct AllImageInfos {
    uint32_t version;
    uint32_t dylib_info_count;
    uint64_t dylib_info_addr;
  };

  uint64_t mach_header_addr = 0;

  const nub_addr_t shlib_addr = DNBProcessGetSharedLibraryInfoAddress(pid);
  uint8_t bytes[256];
  nub_size_t bytes_read = 0;
  DNBDataRef data(bytes, sizeof(bytes), false);
  DNBDataRef::offset_t offset = 0;
  data.SetPointerSize(addr_size);

  // When we are sitting at __dyld_start, the kernel has placed the
  // address of the mach header of the main executable on the stack. If we
  // read the SP and dereference a pointer, we might find the mach header
  // for the executable. We also just make sure there is only 1 thread
  // since if we are at __dyld_start we shouldn't have multiple threads.
  if (DNBProcessGetNumThreads(pid) == 1) {
    nub_thread_t tid = DNBProcessGetThreadAtIndex(pid, 0);
    if (tid != INVALID_NUB_THREAD) {
      DNBRegisterValue sp_value;
      if (DNBThreadGetRegisterValueByID(pid, tid, REGISTER_SET_GENERIC,
                                        GENERIC_REGNUM_SP, &sp_value)) {
        uint64_t sp =
            addr_size == 8 ? sp_value.value.uint64 : sp_value.value.uint32;
        bytes_read = DNBProcessMemoryRead(pid, sp, addr_size, bytes);
        if (bytes_read == addr_size) {
          offset = 0;
          mach_header_addr = data.GetPointer(&offset);
          if (MachHeaderIsMainExecutable(pid, addr_size, mach_header_addr, mh))
            return mach_header_addr;
        }
      }
    }
  }

  // Check the dyld_all_image_info structure for a list of mach header
  // since it is a very easy thing to check
  if (shlib_addr != INVALID_NUB_ADDRESS) {
    bytes_read =
        DNBProcessMemoryRead(pid, shlib_addr, sizeof(AllImageInfos), bytes);
    if (bytes_read > 0) {
      AllImageInfos aii;
      offset = 0;
      aii.version = data.Get32(&offset);
      aii.dylib_info_count = data.Get32(&offset);
      if (aii.dylib_info_count > 0) {
        aii.dylib_info_addr = data.GetPointer(&offset);
        if (aii.dylib_info_addr != 0) {
          const size_t image_info_byte_size = 3 * addr_size;
          for (uint32_t i = 0; i < aii.dylib_info_count; ++i) {
            bytes_read = DNBProcessMemoryRead(pid, aii.dylib_info_addr +
                                                       i * image_info_byte_size,
                                              image_info_byte_size, bytes);
            if (bytes_read != image_info_byte_size)
              break;
            offset = 0;
            mach_header_addr = data.GetPointer(&offset);
            if (MachHeaderIsMainExecutable(pid, addr_size, mach_header_addr,
                                           mh))
              return mach_header_addr;
          }
        }
      }
    }
  }

  // We failed to find the executable's mach header from the all image
  // infos and by dereferencing the stack pointer. Now we fall back to
  // enumerating the memory regions and looking for regions that are
  // executable.
  DNBRegionInfo region_info;
  mach_header_addr = 0;
  while (DNBProcessMemoryRegionInfo(pid, mach_header_addr, &region_info)) {
    if (region_info.size == 0)
      break;

    if (region_info.permissions & eMemoryPermissionsExecutable) {
      DNBLogThreadedIf(
          LOG_RNB_PROC, "[0x%16.16llx - 0x%16.16llx) permissions = %c%c%c: "
                        "checking region for executable mach header",
          region_info.addr, region_info.addr + region_info.size,
          (region_info.permissions & eMemoryPermissionsReadable) ? 'r' : '-',
          (region_info.permissions & eMemoryPermissionsWritable) ? 'w' : '-',
          (region_info.permissions & eMemoryPermissionsExecutable) ? 'x' : '-');
      if (MachHeaderIsMainExecutable(pid, addr_size, mach_header_addr, mh))
        return mach_header_addr;
    } else {
      DNBLogThreadedIf(
          LOG_RNB_PROC,
          "[0x%16.16llx - 0x%16.16llx): permissions = %c%c%c: skipping region",
          region_info.addr, region_info.addr + region_info.size,
          (region_info.permissions & eMemoryPermissionsReadable) ? 'r' : '-',
          (region_info.permissions & eMemoryPermissionsWritable) ? 'w' : '-',
          (region_info.permissions & eMemoryPermissionsExecutable) ? 'x' : '-');
    }
    // Set the address to the next mapped region
    mach_header_addr = region_info.addr + region_info.size;
  }
  bzero(&mh, sizeof(mh));
  return INVALID_NUB_ADDRESS;
}

rnb_err_t RNBRemote::HandlePacket_qSymbol(const char *command) {
  const char *p = command;
  p += strlen("qSymbol:");
  const char *sep = strchr(p, ':');

  std::string symbol_name;
  std::string symbol_value_str;
  // Extract the symbol value if there is one
  if (sep > p)
    symbol_value_str.assign(p, sep - p);
  p = sep + 1;

  if (*p) {
    // We have a symbol name
    symbol_name = decode_hex_ascii_string(p);
    if (!symbol_value_str.empty()) {
      nub_addr_t symbol_value = decode_uint64(symbol_value_str.c_str(), 16);
      if (symbol_name == "dispatch_queue_offsets")
        m_dispatch_queue_offsets_addr = symbol_value;
    }
    ++m_qSymbol_index;
  } else {
    // No symbol name, set our symbol index to zero so we can
    // read any symbols that we need
    m_qSymbol_index = 0;
  }

  symbol_name.clear();

  if (m_qSymbol_index == 0) {
    if (m_dispatch_queue_offsets_addr == INVALID_NUB_ADDRESS)
      symbol_name = "dispatch_queue_offsets";
    else
      ++m_qSymbol_index;
  }

  //    // Lookup next symbol when we have one...
  //    if (m_qSymbol_index == 1)
  //    {
  //    }

  if (symbol_name.empty()) {
    // Done with symbol lookups
    return SendPacket("OK");
  } else {
    std::ostringstream reply;
    reply << "qSymbol:";
    for (size_t i = 0; i < symbol_name.size(); ++i)
      reply << RAWHEX8(symbol_name[i]);
    return SendPacket(reply.str().c_str());
  }
}

// Note that all numeric values returned by qProcessInfo are hex encoded,
// including the pid and the cpu type.

rnb_err_t RNBRemote::HandlePacket_qProcessInfo(const char *p) {
  nub_process_t pid;
  std::ostringstream rep;

  // If we haven't run the process yet, return an error.
  if (!m_ctx.HasValidProcessID())
    return SendPacket("E68");

  pid = m_ctx.ProcessID();

  rep << "pid:" << std::hex << pid << ';';

  int procpid_mib[4];
  procpid_mib[0] = CTL_KERN;
  procpid_mib[1] = KERN_PROC;
  procpid_mib[2] = KERN_PROC_PID;
  procpid_mib[3] = pid;
  struct kinfo_proc proc_kinfo;
  size_t proc_kinfo_size = sizeof(struct kinfo_proc);

  if (::sysctl(procpid_mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0) {
    if (proc_kinfo_size > 0) {
      rep << "parent-pid:" << std::hex << proc_kinfo.kp_eproc.e_ppid << ';';
      rep << "real-uid:" << std::hex << proc_kinfo.kp_eproc.e_pcred.p_ruid
          << ';';
      rep << "real-gid:" << std::hex << proc_kinfo.kp_eproc.e_pcred.p_rgid
          << ';';
      rep << "effective-uid:" << std::hex << proc_kinfo.kp_eproc.e_ucred.cr_uid
          << ';';
      if (proc_kinfo.kp_eproc.e_ucred.cr_ngroups > 0)
        rep << "effective-gid:" << std::hex
            << proc_kinfo.kp_eproc.e_ucred.cr_groups[0] << ';';
    }
  }

  cpu_type_t cputype = DNBProcessGetCPUType(pid);
  if (cputype == 0) {
    DNBLog("Unable to get the process cpu_type, making a best guess.");
    cputype = best_guess_cpu_type();
  }

  uint32_t addr_size = 0;
  if (cputype != 0) {
    rep << "cputype:" << std::hex << cputype << ";";
    if (cputype & CPU_ARCH_ABI64)
      addr_size = 8;
    else
      addr_size = 4;
  }

  bool host_cpu_is_64bit = false;
  uint32_t is64bit_capable;
  size_t is64bit_capable_len = sizeof(is64bit_capable);
  if (sysctlbyname("hw.cpu64bit_capable", &is64bit_capable,
                   &is64bit_capable_len, NULL, 0) == 0)
    host_cpu_is_64bit = is64bit_capable != 0;

  uint32_t cpusubtype;
  size_t cpusubtype_len = sizeof(cpusubtype);
  if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &cpusubtype_len, NULL, 0) ==
      0) {
    // If a process is CPU_TYPE_X86, then ignore the cpusubtype that we detected
    // from the host and use CPU_SUBTYPE_I386_ALL because we don't want the
    // CPU_SUBTYPE_X86_ARCH1 or CPU_SUBTYPE_X86_64_H to be used as the cpu
    // subtype
    // for i386...
    if (host_cpu_is_64bit) {
      if (cputype == CPU_TYPE_X86) {
        cpusubtype = 3; // CPU_SUBTYPE_I386_ALL
      } else if (cputype == CPU_TYPE_ARM) {
        // We can query a process' cputype but we cannot query a process'
        // cpusubtype.
        // If the process has cputype CPU_TYPE_ARM, then it is an armv7 (32-bit
        // process) and we
        // need to override the host cpusubtype (which is in the
        // CPU_SUBTYPE_ARM64 subtype namespace)
        // with a reasonable CPU_SUBTYPE_ARMV7 subtype.
        cpusubtype = 12; // CPU_SUBTYPE_ARM_V7K
      }
    }
#if defined (TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
    // on arm64_32 devices, the machine's native cpu type is
    // CPU_TYPE_ARM64 and subtype is 2 indicating arm64e.
    // But we change the cputype to CPU_TYPE_ARM64_32 because
    // the user processes are all ILP32 processes today.
    // We also need to rewrite the cpusubtype so we vend 
    // a valid cputype + cpusubtype combination.
    if (cputype == CPU_TYPE_ARM64_32 && cpusubtype == 2)
      cpusubtype = CPU_SUBTYPE_ARM64_32_V8;
#endif

    rep << "cpusubtype:" << std::hex << cpusubtype << ';';
  }

  bool os_handled = false;
  if (addr_size > 0) {
    rep << "ptrsize:" << std::dec << addr_size << ';';

#if (defined(__x86_64__) || defined(__i386__))
    // Try and get the OS type by looking at the load commands in the main
    // executable and looking for a LC_VERSION_MIN load command. This is the
    // most reliable way to determine the "ostype" value when on desktop.

    mach_header mh;
    nub_addr_t exe_mach_header_addr =
        GetMachHeaderForMainExecutable(pid, addr_size, mh);
    if (exe_mach_header_addr != INVALID_NUB_ADDRESS) {
      uint64_t load_command_addr =
          exe_mach_header_addr +
          ((addr_size == 8) ? sizeof(mach_header_64) : sizeof(mach_header));
      load_command lc;
      for (uint32_t i = 0; i < mh.ncmds && !os_handled; ++i) {
        const nub_size_t bytes_read =
            DNBProcessMemoryRead(pid, load_command_addr, sizeof(lc), &lc);
        (void)bytes_read;

        uint32_t major_version, minor_version, patch_version;
        auto *platform = DNBGetDeploymentInfo(pid, lc, load_command_addr,
                                              major_version, minor_version,
                                              patch_version);
        if (platform) {
          os_handled = true;
          rep << "ostype:" << platform << ";";
          break;
        }
        load_command_addr = load_command_addr + lc.cmdsize;
      }
    }
#endif // when compiling this on x86 targets
  }

  // If we weren't able to find the OS in a LC_VERSION_MIN load command, try
  // to set it correctly by using the cpu type and other tricks
  if (!os_handled) {
    // The OS in the triple should be "ios" or "macosx" which doesn't match our
    // "Darwin" which gets returned from "kern.ostype", so we need to hardcode
    // this for now.
    if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64
        || cputype == CPU_TYPE_ARM64_32) {
#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
      rep << "ostype:tvos;";
#elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
      rep << "ostype:watchos;";
#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
      rep << "ostype:bridgeos;";
#else
      rep << "ostype:ios;";
#endif
    } else {
      bool is_ios_simulator = false;
      if (cputype == CPU_TYPE_X86 || cputype == CPU_TYPE_X86_64) {
        // Check for iOS simulator binaries by getting the process argument
        // and environment and checking for SIMULATOR_UDID in the environment
        int proc_args_mib[3] = {CTL_KERN, KERN_PROCARGS2, (int)pid};

        uint8_t arg_data[8192];
        size_t arg_data_size = sizeof(arg_data);
        if (::sysctl(proc_args_mib, 3, arg_data, &arg_data_size, NULL, 0) ==
            0) {
          DNBDataRef data(arg_data, arg_data_size, false);
          DNBDataRef::offset_t offset = 0;
          uint32_t argc = data.Get32(&offset);
          const char *cstr;

          cstr = data.GetCStr(&offset);
          if (cstr) {
            // Skip NULLs
            while (true) {
              const char *p = data.PeekCStr(offset);
              if ((p == NULL) || (*p != '\0'))
                break;
              ++offset;
            }
            // Now skip all arguments
            for (uint32_t i = 0; i < argc; ++i) {
              data.GetCStr(&offset);
            }

            // Now iterate across all environment variables
            while ((cstr = data.GetCStr(&offset))) {
              if (strncmp(cstr, "SIMULATOR_UDID=", strlen("SIMULATOR_UDID=")) ==
                  0) {
                is_ios_simulator = true;
                break;
              }
              if (cstr[0] == '\0')
                break;
            }
          }
        }
      }
      if (is_ios_simulator) {
#if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
        rep << "ostype:tvos;";
#elif defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
        rep << "ostype:watchos;";
#elif defined(TARGET_OS_BRIDGE) && TARGET_OS_BRIDGE == 1
        rep << "ostype:bridgeos;";
#else
        rep << "ostype:ios;";
#endif
      } else {
        rep << "ostype:macosx;";
      }
    }
  }

  rep << "vendor:apple;";

#if defined(__LITTLE_ENDIAN__)
  rep << "endian:little;";
#elif defined(__BIG_ENDIAN__)
  rep << "endian:big;";
#elif defined(__PDP_ENDIAN__)
  rep << "endian:pdp;";
#endif

  if (addr_size == 0) {
#if (defined(__x86_64__) || defined(__i386__)) && defined(x86_THREAD_STATE)
    nub_thread_t thread = DNBProcessGetCurrentThreadMachPort(pid);
    kern_return_t kr;
    x86_thread_state_t gp_regs;
    mach_msg_type_number_t gp_count = x86_THREAD_STATE_COUNT;
    kr = thread_get_state(static_cast<thread_act_t>(thread), x86_THREAD_STATE,
                          (thread_state_t)&gp_regs, &gp_count);
    if (kr == KERN_SUCCESS) {
      if (gp_regs.tsh.flavor == x86_THREAD_STATE64)
        rep << "ptrsize:8;";
      else
        rep << "ptrsize:4;";
    }
#elif defined(__arm__)
    rep << "ptrsize:4;";
#elif (defined(__arm64__) || defined(__aarch64__)) &&                          \
    defined(ARM_UNIFIED_THREAD_STATE)
    nub_thread_t thread = DNBProcessGetCurrentThreadMachPort(pid);
    kern_return_t kr;
    arm_unified_thread_state_t gp_regs;
    mach_msg_type_number_t gp_count = ARM_UNIFIED_THREAD_STATE_COUNT;
    kr = thread_get_state(thread, ARM_UNIFIED_THREAD_STATE,
                          (thread_state_t)&gp_regs, &gp_count);
    if (kr == KERN_SUCCESS) {
      if (gp_regs.ash.flavor == ARM_THREAD_STATE64)
        rep << "ptrsize:8;";
      else
        rep << "ptrsize:4;";
    }
#endif
  }

  return SendPacket(rep.str());
}

const RNBRemote::DispatchQueueOffsets *RNBRemote::GetDispatchQueueOffsets() {
  if (!m_dispatch_queue_offsets.IsValid() &&
      m_dispatch_queue_offsets_addr != INVALID_NUB_ADDRESS &&
      m_ctx.HasValidProcessID()) {
    nub_process_t pid = m_ctx.ProcessID();
    nub_size_t bytes_read = DNBProcessMemoryRead(
        pid, m_dispatch_queue_offsets_addr, sizeof(m_dispatch_queue_offsets),
        &m_dispatch_queue_offsets);
    if (bytes_read != sizeof(m_dispatch_queue_offsets))
      m_dispatch_queue_offsets.Clear();
  }

  if (m_dispatch_queue_offsets.IsValid())
    return &m_dispatch_queue_offsets;
  else
    return nullptr;
}

void RNBRemote::EnableCompressionNextSendPacket(compression_types type) {
  m_compression_mode = type;
  m_enable_compression_next_send_packet = true;
}

compression_types RNBRemote::GetCompressionType() {
  // The first packet we send back to the debugger after a QEnableCompression
  // request
  // should be uncompressed -- so we can indicate whether the compression was
  // enabled
  // or not via OK / Enn returns.  After that, all packets sent will be using
  // the
  // compression protocol.

  if (m_enable_compression_next_send_packet) {
    // One time, we send back "None" as our compression type
    m_enable_compression_next_send_packet = false;
    return compression_types::none;
  }
  return m_compression_mode;
}