Loading...
   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

""" Please make sure you read the README COMPLETELY BEFORE reading anything below.
    It is very critical that you read coding guidelines in Section E in README file.
"""
from xnu import *
from utils import *
from string import *
from socket import *
import tempfile

import xnudefines
from netdefines import *
from routedefines import *
from mbufdefines import *

def GetDlilIfFlagsAsString(dlil_if_flags):
    """ Return a formatted string description of the dlil interface flags
    """
    out_string = ""
    flags = (unsigned)(dlil_if_flags & 0xffff)
    i = 0
    num = 1
    while num <= flags:
        if flags & num:
            out_string += dlil_if_flags_strings[i] + ","
        i += 1
        num = num << 1
    return out_string.rstrip(",")

def GetIfFlagsAsString(if_flags):
    """ Return a formatted string description of the interface flags
    """
    out_string = ""
    flags = (unsigned)(if_flags & 0xffff)
    i = 0
    num = 1
    while num <= flags:
        if flags & num:
            out_string += if_flags_strings[i] + ","
        i += 1
        num = num << 1
    return out_string.rstrip(",")

def GetIfEflagsAsString(if_eflags):
    """ Return a formatted string description of the interface extra flags
    """
    out_string = ""
    flags = unsigned(if_eflags)
    i = 0
    num = 1
    while num <= flags:
        if flags & num:
            out_string += if_eflags_strings[i] + ","
        i += 1
        num = num << 1
    return out_string.rstrip(",")

def GetIfXflagsAsString(if_xflags):
    """ Return a formatted string description of the interface extended flags
    """
    out_string = ""
    flags = unsigned(if_xflags)
    i = 0
    num = 1
    while num <= flags:
        if flags & num:
            out_string += if_xflags_strings[i] + ","
        i += 1
        num = num << 1
    return out_string.rstrip(",")


def ShowIfConfiguration(ifnet):
    """ Display ifconfig-like output for the ifnet
    """
    iface = Cast(ifnet, 'ifnet *')
    dlifnet = Cast(ifnet, 'dlil_ifnet *')
    out_string = ""
    format_string = "{0: <s}: flags={1: <x} <{2: <s}> index {3: <d} mtu {4: <d}"
    extended_flags_format_string = "\n\teflags={0: <x} <{1: <s}>"
    extra_flags_format_string = "\n\txflags={0: <x} <{1: <s}>"
    capenabled_format_string = "\n\toptions={0: <x} <{1: <s}>"
    if iface :
        out_string += format_string.format(iface.if_xname, (iface.if_flags & 0xffff), GetIfFlagsAsString(iface.if_flags), iface.if_index, iface.if_data.ifi_mtu)
        out_string += "\n\tdlil flags=" + hex(dlifnet.dl_if_flags)+ " <" + GetDlilIfFlagsAsString(dlifnet.dl_if_flags) + ">"
        if (iface.if_eflags) :
            out_string += extended_flags_format_string.format(iface.if_eflags, GetIfEflagsAsString(iface.if_eflags))
        if (iface.if_xflags) :
            out_string += extra_flags_format_string.format(iface.if_xflags, GetIfXflagsAsString(iface.if_xflags))
        if (iface.if_capenable) :
            out_string += capenabled_format_string.format(iface.if_capenable, GetCapabilitiesAsString(iface.if_capenable))
        out_string += "\n\t(struct ifnet *)" + hex(ifnet)
        if iface.if_snd and iface.if_snd.ifcq_len :
            out_string += "\n\t" + str(iface.if_snd.ifcq_len)
        if dlifnet.dl_if_inpstorage.dlth_pkts.qlen :
            out_string += "\n\t" + str(dlifnet.dl_if_inpstorage.dlth_pkts.qlen)
    print(out_string)

def GetIfConfiguration(ifname):
    """ Return ifnet structure corresponding to the ifname passed in
    """
    global kern
    ifnets = kern.globals.ifnet_head
    for ifnet in IterateTAILQ_HEAD(ifnets, "if_link") :
        if str(ifnet.if_xname) == ifname :
            return ifnet
    return None

#Macro: ifconfig_dlil
@lldb_command('ifconfig_dlil')
def ShowIfconfigDlil(cmd_args=None) :
    """ Display ifconfig-like output for DLIL interface list, print (struct ifnet *) pointer and dlil info for further inspection
    """
    dlil_ifnets = kern.globals.dlil_ifnet_head
    for dlil_ifnet in IterateTAILQ_HEAD(dlil_ifnets, "dl_if_link"):
        ShowIfConfiguration(dlil_ifnet)
        print(GetIfaddrs(Cast(dlil_ifnet, 'ifnet *')))
# EndMacro: ifconfig_dlil

#Macro: printin6addr
@lldb_command('printin6addr')
def PrintIn6Addr(cmd_args=None):
    """ Print an IPv6 address from a struct in6_addr pointer
        Usage: printin6addr <in6_addr *>
    """
    if cmd_args is None or len(cmd_args) == 0:
        print("Missing argument: provide a pointer to struct in6_addr")
        print("Usage: printin6addr <in6_addr *>")
        return

    in6_addr_ptr = kern.GetValueFromAddress(cmd_args[0], 'struct in6_addr *')
    addr_string = GetIn6AddrAsString(in6_addr_ptr.__u6_addr.__u6_addr8)
    print(addr_string)
# EndMacro: printin6addr

#Macro: printndopt
@lldb_command('printndopt')
def PrintNdOpt(cmd_args=None):
    """ Print a Neighbor Discovery option header (struct nd_opt_hdr)
        Usage: printndopt <nd_opt_hdr *>

        Displays the option type, length, and link-layer address data if present
    """
    if cmd_args is None or len(cmd_args) == 0:
        print("Missing argument: provide a pointer to struct nd_opt_hdr")
        print("Usage: printndopt <nd_opt_hdr *>")
        return

    nd_opt = kern.GetValueFromAddress(cmd_args[0], 'struct nd_opt_hdr *')

    if not nd_opt or unsigned(nd_opt) == 0:
        print("NULL or invalid pointer")
        return

    opt_type = unsigned(nd_opt.nd_opt_type)
    opt_len = unsigned(nd_opt.nd_opt_len)

    # Option type names (from RFC 4861)
    opt_type_names = {
        1: "Source Link-layer Address",
        2: "Target Link-layer Address",
        3: "Prefix Information",
        4: "Redirected Header",
        5: "MTU",
        14: "Nonce",
        24: "Route Information",
    }

    opt_type_name = opt_type_names.get(opt_type, "Unknown")
    total_len = opt_len * 8  # Length is in units of 8 bytes

    print("Neighbor Discovery Option:")
    print("  Type: {} ({})".format(opt_type, opt_type_name))
    print("  Length: {} units ({} bytes)".format(opt_len, total_len))

    # For link-layer address options (types 1 and 2), display the address
    if opt_type in [1, 2] and opt_len > 0:
        # The link-layer address follows immediately after the header
        # Header is 2 bytes (type + len), so data starts at offset 2
        data_len = total_len - 2

        if data_len > 0:
            # Read the address bytes after the header
            opt_data_ptr = unsigned(nd_opt) + 2  # Skip the 2-byte header

            # Get a uint8_t pointer to the data and use array indexing
            opt_data = kern.GetValueFromAddress(opt_data_ptr, 'uint8_t *')

            # Read bytes and format as colon-separated hex
            addr_bytes = []
            for i in range(min(data_len, 16)):  # Limit to reasonable size
                byte_val = unsigned(opt_data[i])
                addr_bytes.append("{:02x}".format(byte_val))

            print("  Link-layer Address: {}".format(":".join(addr_bytes)))

    print("")
# EndMacro: printndopt

def GetAddressAsStringColonHex(addr, count):
    out_string = ""
    i = 0
    addr_format_string = "{0:02x}"
    while (i < count):
        if (i == 0):
            out_string += addr_format_string.format(unsigned(addr[i]))[-2:]
        else:
            out_string += ":" + addr_format_string.format(unsigned(addr[i]))[-2:]
        i += 1
    return out_string

def GetSocketAddrAsStringUnspec(sockaddr):
    out_string = ""
    out_string += GetAddressAsStringColonHex(sockaddr.sa_data, sockaddr.sa_len - 2)
    return out_string

def GetSocketAddrAsStringUnix(sockaddr):
    sock_unix = Cast(sockaddr, 'sockaddr_un *')
    if (sock_unix == 0):
        return "(null)"
    else:
        if (len(str(sock_unix.sun_path)) > 0):
            return str(sock_unix.sun_path)
        else:
            return "\"\""

def GetInAddrAsString(ia):
    out_string = ""
    inaddr = Cast(ia, 'in_addr *')

    packed_value = struct.pack('I', unsigned(ia.s_addr))
    out_string = inet_ntoa(packed_value)
    return out_string

def GetIn6AddrAsString(ia):
    addr_raw_string = ":".join(["{0:02x}{1:02x}".format(unsigned(ia[i]),
        unsigned(ia[i+1])) for i in range(0, 16, 2)])
    return inet_ntop(AF_INET6, inet_pton(AF_INET6, addr_raw_string))

def GetSocketAddrAsStringInet(sockaddr):
    sock_in = Cast(sockaddr, 'sockaddr_in *')
    return GetInAddrAsString(addressof(sock_in.sin_addr))

def GetSocketAddrAsStringInet6(sockaddr):
    sock_in6 = Cast(sockaddr, 'sockaddr_in6 *')
    return GetIn6AddrAsString(sock_in6.sin6_addr.__u6_addr.__u6_addr8)

def GetSocketAddrAsStringInet6Enhanced(sockaddr, ifaddr=None):
    """Enhanced IPv6 address display with prefix length and flags like ifconfig"""
    sock_in6 = Cast(sockaddr, 'sockaddr_in6 *')
    out_string = GetIn6AddrAsString(sock_in6.sin6_addr.__u6_addr.__u6_addr8)

    # If we have the ifaddr context, extract additional IPv6 details
    if ifaddr is not None:
        try:
            if ifaddr.ifa_addr.sa_family == 30:  # AF_INET6
                in6_ia = Cast(ifaddr, 'in6_ifaddr *')

                try:
                    prefixlen = int(in6_ia.ia_plen)
                    out_string += " prefixlen " + str(prefixlen)
                except:
                    pass

                try:
                    flags = int(in6_ia.ia6_flags)
                    flag_strings = []

                    if flags & 0x0010:  # IN6_IFF_DEPRECATED
                        flag_strings.append("deprecated")

                    if flags & 0x0040:  # IN6_IFF_AUTOCONF
                        flag_strings.append("autoconf")

                    if flags & 0x0080:  # IN6_IFF_TEMPORARY
                        flag_strings.append("temporary")

                    if flags & 0x0002:  # IN6_IFF_TENTATIVE
                        flag_strings.append("tentative")

                    if flags & 0x0004:  # IN6_IFF_DUPLICATED
                        flag_strings.append("duplicated")

                    if flags & 0x0100:  # IN6_IFF_DYNAMIC (DHCPv6)
                        flag_strings.append("dynamic")

                    if flag_strings:
                        out_string += " " + " ".join(flag_strings)

                except:
                    pass

        except:
            pass

    return out_string

def GetSocketAddrAsStringLink(sockaddr):
    sock_link = Cast(sockaddr, 'sockaddr_dl *')
    if sock_link is None:
        return "(null)"
    else:
        out_string = ""
        if (sock_link.sdl_nlen == 0 and sock_link.sdl_alen == 0 and sock_link.sdl_slen == 0):
            out_string = "link#" + str(int(sock_link.sdl_index))
        else:
            out_string += GetAddressAsStringColonHex(addressof(sock_link.sdl_data[sock_link.sdl_nlen]), sock_link.sdl_alen)
    return out_string

def GetSocketAddrAsStringAT(sockaddr):
    out_string = ""
    sock_addr = Cast(sockaddr, 'sockaddr *')
    out_string += GetAddressAsStringColonHex(sockaddr.sa_data, sockaddr.sa_len - 2)
    return out_string

def GetSocketAddrAsString(sockaddr, ifaddr=None):
    if sockaddr is None :
        return "(null)"
    out_string = ""
    if (sockaddr.sa_family == 0):
        out_string += "UNSPC "
        GetSocketAddrAsStringUnspec(sockaddr)
    elif (sockaddr.sa_family == 1):
        out_string += "UNIX "
        out_string += GetSocketAddrAsStringUnix(sockaddr)
    elif (sockaddr.sa_family == 2):
        out_string += "INET "
        out_string += GetSocketAddrAsStringInet(sockaddr)
    elif (sockaddr.sa_family == 30):
        out_string += "INET6 "
        if ifaddr is not None:
            out_string += GetSocketAddrAsStringInet6Enhanced(sockaddr, ifaddr)
        else:
            out_string += GetSocketAddrAsStringInet6(sockaddr)
    elif (sockaddr.sa_family == 18):
        out_string += "LINK "
        out_string += GetSocketAddrAsStringLink(sockaddr)
    elif (sockaddr.sa_family == 16):
        out_string += "ATLK "
        out_string += GetSocketAddrAsStringAT(sockaddr)
    else:
        out_string += "FAM " + str(sockaddr.sa_family)
        out_string += GetAddressAsStringColonHex(sockaddr.sa_data, sockaddr.sa_len)
    return out_string

# Macro: showifaddrs
@lldb_command('showifaddrs')
def ShowIfaddrs(cmd_args=None):
    """ Show the (struct ifnet).if_addrhead list of addresses for the given ifp
    """
    if cmd_args != None and len(cmd_args) > 0 :
        ifp = kern.GetValueFromAddress(cmd_args[0], 'ifnet *')
        if not ifp:
            print("Unknown value passed as argument.")
            return
        i = 1
        for ifaddr in IterateTAILQ_HEAD(ifp.if_addrhead, "ifa_link"):
            format_string = "\t{0: <d}: 0x{1: <x} {2: <s} [{3: <d}]"
            print(format_string.format(i, ifaddr, GetSocketAddrAsString(ifaddr.ifa_addr, ifaddr), ifaddr.ifa_refcnt))
            i += 1
    else :
        print("Missing argument 0 in user function.")
# EndMacro: showifaddrs

def GetIfaddrs(ifp):
    out_string = ""
    if (ifp != 0):
        i = 1
        for ifaddr in IterateTAILQ_HEAD(ifp.if_addrhead, "ifa_link"):
            format_string = "\t{0: <d}: 0x{1: <x} {2: <s}"
            out_string += format_string.format(i, ifaddr, GetSocketAddrAsString(ifaddr.ifa_addr, ifaddr)) + "\n"
            i += 1
    else:
        out_string += "Missing argument 0 in user function."
    return out_string


def GetCapabilitiesAsString(flags):
    """ Return a formatted string description of the interface flags
    """
    out_string = ""
    i = 0
    num = 1
    while num <= flags:
        if flags & num:
            out_string += if_capenable_strings[i] + ","
        i += 1
        num = num << 1
    return out_string.rstrip(",")

def ShowDlilIfnetConfiguration(dlil_ifnet, show_all) :
    """ Formatted display of dlil_ifnet structures
    """
    DLIF_INUSE = 0x1
    DLIF_REUSE = 0x2

    if dlil_ifnet is None :
        return

    dlil_iface = Cast(dlil_ifnet, 'dlil_ifnet *')
    iface = Cast(dlil_ifnet, 'ifnet *')
    out_string = ""
    if (dlil_iface.dl_if_flags & DLIF_REUSE) :
        out_string  += "*"
    format_string = "{0: <s}: flags={1: <x} <{2: <s}> index {3: <d} mtu {4: <d}"
    extended_flags_format_string = "\n\teflags={0: <x} <{1: <s}>"
    extra_flags_format_string = "\n\txflags={0: <x} <{1: <s}>"
    capenabled_format_string = "\n\toptions={0: <x} <{1: <s}>"
    if (dlil_iface.dl_if_flags & DLIF_INUSE) :
        out_string += format_string.format(iface.if_xname, (iface.if_flags & 0xffff), GetIfFlagsAsString(iface.if_flags), iface.if_index, iface.if_data.ifi_mtu)
    else :
        out_string += format_string.format("[" + str(iface.if_name) + str(int(iface.if_unit)) + "]", (iface.if_flags & 0xffff), GetIfFlagsAsString(iface.if_flags), iface.if_index, iface.if_data.ifi_mtu)
    if (iface.if_eflags) :
        out_string += extended_flags_format_string.format(iface.if_eflags, GetIfEflagsAsString(iface.if_eflags))
    if (iface.if_xflags) :
        out_string += extra_flags_format_string.format(iface.if_xflags, GetIfXflagsAsString(iface.if_xflags))
    if (iface.if_capenable) :
        out_string += capenabled_format_string.format(iface.if_capenable, GetCapabilitiesAsString(iface.if_capenable))
    out_string += "\n\t(struct ifnet *)" + hex(dlil_ifnet) + "\n"
    if show_all :
        out_string += GetIfaddrs(iface)
        out_string += "\n"
    print(out_string)

# Macro: ifconfig
@lldb_command('ifconfig')
def ShowIfconfig(cmd_args=None) :
    """ Display ifconfig-like output, and print the (struct ifnet *) pointers for further inspection
    """
    if cmd_args != None and len(cmd_args) > 0:
        showall = 1
    else:
        showall = 0

    ifnets = kern.globals.ifnet_head
    for ifnet in IterateTAILQ_HEAD(ifnets, "if_link"):
        ShowIfConfiguration(ifnet)
        if (showall == 1):
            print(GetIfaddrs(ifnet))
# EndMacro: ifconfig

# Macro: showifnets
@lldb_command('showifnets')
def ShowIfnets(cmd_args=None) :
    """ Display ifconfig-like output for all attached and detached interfaces
    """
    showall = 0
    if cmd_args != None and len(cmd_args) > 0 :
        showall = 1
    dlil_ifnets = kern.globals.dlil_ifnet_head
    for dlil_ifnet in IterateTAILQ_HEAD(dlil_ifnets, "dl_if_link"):
        ShowDlilIfnetConfiguration(dlil_ifnet, showall)
# EndMacro: showifnets

# Macro: showdetachingifnets
@lldb_command('showdetachingifnets')
def ShowDetachingIfnets(cmd_args=None) :
    """ Display ifconfig-like output for all detaching interfaces
    """
    if cmd_args != None and len(cmd_args) > 0:
        showall = 1
    else:
        showall = 0
    ifnets = kern.globals.ifnet_detaching_head
    for ifnet in IterateTAILQ_HEAD(ifnets, "if_detaching_link"):
        ShowIfConfiguration(ifnet)
        if (showall == 1):
            print(GetIfaddrs(ifnet))
# EndMacro: showdetachingifnets

# Macro: showorderedifnets
@lldb_command('showorderedifnets')
def ShowOrderedIfnets(cmd_args=None) :
    """ Display ifconfig-like output for ordered interfaces
    """
    if cmd_args != None and len(cmd_args) > 0:
        showall = 1
    else:
        showall = 0
    ifnets = kern.globals.ifnet_ordered_head
    for ifnet in IterateTAILQ_HEAD(ifnets, "if_ordered_link"):
        ShowIfConfiguration(ifnet)
        if (showall == 1):
            print(GetIfaddrs(ifnet))
# EndMacro: showorderedifnets

# Macro: showifmultiaddrs
@lldb_command('showifmultiaddrs')
def ShowIfMultiAddrs(cmd_args=None) :
    """ Show the list of multicast addresses for the given ifp
    """
    out_string = ""
    if cmd_args != None and len(cmd_args) > 0 :
        ifp = kern.GetValueFromAddress(cmd_args[0], 'ifnet *')
        if not ifp:
            print("Unknown value passed as argument.")
            return
        ifmulti = cast(ifp.if_multiaddrs.lh_first, 'ifmultiaddr *')
        i = 0
        while ifmulti != 0:
            ifma_format_string = "\t{0: <d}: 0x{1: <x} "
            out_string += (ifma_format_string.format(i + 1, ifmulti))
            if (ifmulti.ifma_addr.sa_family == 2):
                if (ifmulti.ifma_ll != 0):
                    out_string += GetSocketAddrAsStringLink(ifmulti.ifma_ll.ifma_addr) + " "
                out_string += GetSocketAddrAsStringInet(ifmulti.ifma_addr)
            if (ifmulti.ifma_addr.sa_family == 30):
                if (ifmulti.ifma_ll != 0):
                    out_string += GetSocketAddrAsStringLink(ifmulti.ifma_ll.ifma_addr) + " "
                out_string += GetSocketAddrAsStringInet6(ifmulti.ifma_addr) + " "
            if (ifmulti.ifma_addr.sa_family == 18):
                out_string += GetSocketAddrAsStringLink(ifmulti.ifma_addr) + " "
            if (ifmulti.ifma_addr.sa_family == 0):
                out_string += GetSocketAddrAsStringUnspec(ifmulti.ifma_addr) + " "
            out_string += "[" + str(int(ifmulti.ifma_refcount)) + "]\n"
            ifmulti = cast(ifmulti.ifma_link.le_next, 'ifmultiaddr *')
            i += 1
        print(out_string)
    else :
        print("Missing argument 0 in user function.")
# EndMacro: showifmultiaddrs

# Macro: showinmultiaddrs
@lldb_command('showinmultiaddrs')
def ShowInMultiAddrs(cmd_args=None) :
    """ Show the contents of IPv4 multicast address records
    """
    out_string = ""
    inmultihead = kern.globals.in_multihead
    inmulti = cast(inmultihead.lh_first, 'in_multi *')
    i = 0
    while inmulti != 0:
        ifp = inmulti.inm_ifp
        inma_format_string = "\t{0: <d}: 0x{1: <x} "
        out_string += inma_format_string.format(i + 1, inmulti) + " "
        out_string += GetInAddrAsString(addressof(inmulti.inm_addr)) + " "
        ifma_format_string = "(ifp 0x{0: <x} [{1: <s}] ifma {2: <x})"
        out_string += ifma_format_string.format(ifp, ifp.if_xname, inmulti.inm_ifma) + "\n"
        inmulti = cast(inmulti.inm_link.le_next, 'in_multi *')
        i += 1
    print(out_string)
# EndMacro: showinmultiaddrs

# Macro: showin6multiaddrs
@lldb_command('showin6multiaddrs')
def ShowIn6MultiAddrs(cmd_args=None) :
    """ Show the contents of IPv6 multicast address records
    """
    out_string = ""
    in6multihead = kern.globals.in6_multihead
    in6multi = cast(in6multihead.lh_first, 'in6_multi *')
    i = 0
    while in6multi != 0:
        ifp = in6multi.in6m_ifp
        inma_format_string = "\t{0: <d}: 0x{1: <x} "
        out_string += inma_format_string.format(i + 1, in6multi) + " "
        out_string += GetIn6AddrAsString((in6multi.in6m_addr.__u6_addr.__u6_addr8)) + " "
        ifma_format_string = "(ifp 0x{0: <x} [{1: <s}] ifma {2: <x})"
        out_string += ifma_format_string.format(ifp, ifp.if_xname, in6multi.in6m_ifma) + "\n"
        in6multi = cast(in6multi.in6m_entry.le_next, 'in6_multi *')
        i += 1
    print(out_string)
# EndMacro: showin6multiaddrs

def GetTcpState(tcpcb):
    out_string = ""
    tp = Cast(tcpcb, 'tcpcb *')
    if (int(tp) != 0):
        if tp.t_state == 0:
            out_string += "CLOSED\t"
        if tp.t_state == 1:
            out_string += "LISTEN\t"
        if tp.t_state == 2:
            out_string += "SYN_SENT\t"
        if tp.t_state == 3:
            out_string += "SYN_RCVD\t"
        if tp.t_state == 4:
            out_string += "ESTABLISHED\t"
        if tp.t_state == 5:
            out_string += "CLOSE_WAIT\t"
        if tp.t_state == 6:
            out_string += "FIN_WAIT_1\t"
        if tp.t_state == 7:
            out_string += "CLOSING\t"
        if tp.t_state == 8:
            out_string += "LAST_ACK\t"
        if tp.t_state == 9:
            out_string += "FIN_WAIT_2\t"
        if tp.t_state == 10:
            out_string += "TIME_WAIT\t"
    return out_string

def GetSocketProtocolAsString(sock):
    out_string = ""
    inpcb = Cast(sock.so_pcb, 'inpcb *')
    if sock.so_proto.pr_protocol == 6:
        out_string += " TCP "
        out_string += GetTcpState(inpcb.inp_ppcb)
    if sock.so_proto.pr_protocol == 17:
        out_string += " UDP "
    if sock.so_proto.pr_protocol == 1:
        out_string += " ICMP "
    if sock.so_proto.pr_protocol == 254:
        out_string += " DIVERT "
    if sock.so_proto.pr_protocol == 255:
        out_string += " RAW "
    return out_string

def GetInAddr4to6AsString(inaddr):
    out_string = ""
    if (inaddr is not None):
        ia = Cast(inaddr, 'unsigned char *')
        inaddr_format_string = "{0:d}:{1:d}:{2:d}:{3:d}"
        out_string += inaddr_format_string.format(unsigned(ia[0]), unsigned(ia[1]), unsigned(ia[2]), unsigned(ia[3]))
    return out_string

def GetInPortAsString(port):
    out_string = ""
    port_string = Cast(port, 'char *')
    port_unsigned = dereference(Cast(port, 'unsigned short *'))

    if ((((port_unsigned & 0xff00) >> 8) == port_string[0])) and (((port_unsigned & 0x00ff) == port_string[1])):
        out_string += ":" + str(int(port_unsigned))
    else:
        out_string += ":" + str(int(((port_unsigned & 0xff00) >> 8) | ((port_unsigned & 0x00ff) << 8)))

    return out_string

def GetIPv4SocketAsString(sock) :
    out_string = ""
    pcb = Cast(sock.so_pcb, 'inpcb *')
    if (pcb == 0):
        out_string += "inpcb: (null) "
    else:
        out_string += "inpcb: " + hex(pcb)
        out_string += GetSocketProtocolAsString(sock)

        out_string += GetInAddr4to6AsString(addressof(pcb.inp_dependladdr.inp46_local.ia46_addr4))
        out_string += GetInPortAsString(addressof(pcb.inp_lport))
        out_string += " -> "
        out_string += GetInAddr4to6AsString(addressof(pcb.inp_dependfaddr.inp46_foreign.ia46_addr4))
        out_string += GetInPortAsString(addressof(pcb.inp_fport))
    return out_string

def GetIPv6SocketAsString(sock) :
    out_string = ""
    pcb = Cast(sock.so_pcb, 'inpcb *')
    if (pcb == 0):
        out_string += "inpcb: (null) "
    else:
        out_string += "inpcb: " + hex(pcb) + " "
        out_string += GetSocketProtocolAsString(sock)

        out_string += GetIn6AddrAsString((pcb.inp_dependladdr.inp6_local.__u6_addr.__u6_addr8))
        out_string += GetInPortAsString(addressof(pcb.inp_lport))
        out_string += " -> "
        out_string += GetIn6AddrAsString((pcb.inp_dependfaddr.inp6_foreign.__u6_addr.__u6_addr8))
        out_string += GetInPortAsString(addressof(pcb.inp_fport))
    return out_string

def GetUnixDomainSocketAsString(sock) :
    out_string = ""
    pcb = Cast(sock.so_pcb, 'unpcb *')
    if (pcb == 0):
        out_string += "unpcb: (null) "
    else:
        out_string += "unpcb: " + hex(pcb)  + " "
        out_string += "unp_vnode: " + hex(pcb.unp_vnode) + " "
        out_string += "unp_conn: " + hex(pcb.unp_conn) + " "
        out_string += "unp_addr: " + GetSocketAddrAsStringUnix(pcb.unp_addr)
    return out_string

def GetVsockSocketAsString(sock) :
    out_string = ""
    pcb = Cast(sock.so_pcb, 'vsockpcb *')
    if (pcb == 0):
        out_string += "vsockpcb: (null) "
    else:
        out_string += "vsockpcb: " + hex(pcb) + " "
        out_string += str(pcb.local_address) + " "
        out_string += str(pcb.remote_address)
    return out_string

def GetSocket(socket) :
    """ Show the contents of a socket
    """
    so = kern.GetValueFromAddress(unsigned(socket), 'socket *')
    if (so):
        out_string = ""
        sock_format_string = "so: 0x{0:<x} options 0x{1:<x} state 0x{2:<x}"
        out_string += sock_format_string.format(so, so.so_options, so.so_state)
        domain = so.so_proto.pr_domain
        domain_name_format_string = " {0:<s} "
        out_string += domain_name_format_string.format(domain.dom_name)
        if (domain.dom_family == 1):
            out_string += GetUnixDomainSocketAsString(so)
        if (domain.dom_family == 2):
            out_string += GetIPv4SocketAsString(so)
        if (domain.dom_family == 30):
            out_string += GetIPv6SocketAsString(so)
        if (domain.dom_family == 40):
            out_string += GetVsockSocketAsString(so)
        out_string += " s=" + str(int(so.so_snd.sb_cc)) + " r=" + str(int(so.so_rcv.sb_cc)) + " usecnt=" + str(int(so.so_usecount))
    else:
        out_string += "(null)"
    return out_string
# EndMacro: showsocket


# Macro: showsocket
@lldb_command('showsocket')
def ShowSocket(cmd_args=None) :
    """ Show the contents of a socket
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    so = kern.GetValueFromAddress(cmd_args[0], 'socket *')
    if (len(str(cmd_args[0])) > 0):
        out_string = ""
        sock_format_string = "so: 0x{0:<x} options 0x{1:<x} state 0x{2:<x}"
        out_string += sock_format_string.format(so, so.so_options, so.so_state)
        domain = so.so_proto.pr_domain
        domain_name_format_string = " {0:<s} "
        out_string += domain_name_format_string.format(domain.dom_name)
        if (domain.dom_family == 1):
            out_string += GetUnixDomainSocketAsString(so)
        if (domain.dom_family == 2):
            out_string += GetIPv4SocketAsString(so)
        if (domain.dom_family == 30):
            out_string += GetIPv6SocketAsString(so)
        if (domain.dom_family == 40):
            out_string += GetVsockSocketAsString(so)
        print(out_string)
    else:
        print("Unknown value passed as argument.")
        return
# EndMacro: showsocket

def GetProcSockets(proc, total_snd_cc, total_rcv_cc, total_sock_fd):
    """ Given a proc_t pointer, display information about its sockets
    """
    out_string = ""

    if proc is None:
        out_string += "Unknown value passed as argument."
    else:
        snd_cc = 0
        rcv_cc = 0
        sock_fd_seen = 0
        """struct  filedesc *"""
        proc_filedesc = addressof(proc.p_fd)
        """struct  fileproc **"""
        proc_ofiles = proc_filedesc.fd_ofiles
        """ high-water mark of fd_ofiles """
        if proc_filedesc.fd_nfiles != 0:
            for fd in range(0, unsigned(proc_filedesc.fd_afterlast)):
                if (unsigned(proc_ofiles[fd]) != 0 and proc_ofiles[fd].fp_glob != 0):
                        fg = proc_ofiles[fd].fp_glob
                        fg_data = Cast(fg.fg_data, 'void *')
                        if (int(fg.fg_ops.fo_type) == 2):
                            if (proc_filedesc.fd_ofileflags[fd] & 4):
                                out_string += "U: "
                            else:
                                out_string += " "
                            out_string += "fd = " + str(fd) + " "
                            if (fg_data != 0):
                                out_string += GetSocket(fg_data)
                                out_string += "\n"

                                so = Cast(fg_data, 'socket *')
                                snd_cc += int(so.so_snd.sb_cc)
                                total_snd_cc[0] += int(so.so_snd.sb_cc)
                                rcv_cc += int(so.so_rcv.sb_cc)
                                total_rcv_cc[0] += int(so.so_rcv.sb_cc)
                                sock_fd_seen += 1
                            else:
                                out_string += ""
        out_string += "total sockets " + str(int(sock_fd_seen)) + " snd_cc " + str(int(snd_cc)) + " rcv_cc " + str(int(rcv_cc)) + "\n"
        total_sock_fd[0] = sock_fd_seen
    return out_string


# Macro: showprocsockets
@lldb_command('showprocsockets')
def ShowProcSockets(cmd_args=None):
    """ Given a proc_t pointer, display information about its sockets
    """
    total_snd_cc = [0]
    total_rcv_cc = [0]
    sock_fd_seen = [0]
    out_string = ""
    if cmd_args != None and len(cmd_args) > 0 :
        proc = kern.GetValueFromAddress(cmd_args[0], 'proc *')

        if not proc:
            print("Unknown value passed as argument.")
            return
        else:
            print(GetProcInfo(proc))
            print(GetProcSockets(proc, total_snd_cc, total_rcv_cc, sock_fd_seen))
    else:
        print("Missing argument 0 in user function.")
# EndMacro: showprocsockets

# Macro: showallprocsockets
@lldb_command('showallprocsockets')
def ShowAllProcSockets(cmd_args=None):
    """Display information about the sockets of all the processes
    """
    total_snd_cc = [0]
    total_rcv_cc = [0]
    for proc in kern.procs:
        sock_fd_seen = [0]
        out_str = ""
        out_str += GetProcSockets(proc, total_snd_cc, total_rcv_cc, sock_fd_seen)
        if sock_fd_seen[0] != 0:
            print("================================================================================")
            print(GetProcInfo(proc))
            print(out_str)
    print ("total_snd_cc: " + str(int(total_snd_cc[0])) + " total_rcv_cc: " + str(int(total_rcv_cc[0])) + "\n")
# EndMacro: showallprocsockets


def GetRtEntryPrDetailsAsString(rte):
    out_string = ""
    rt = Cast(rte, 'rtentry *')
    dst = Cast(rt.rt_nodes[0].rn_u.rn_leaf.rn_Key, 'sockaddr *')
    isv6 = 0
    dst_string_format = "{0:<18s}"
    if (dst.sa_family == AF_INET):
        out_string += dst_string_format.format(GetSocketAddrAsStringInet(dst)) + " "
    else:
        if (dst.sa_family == AF_INET6):
            out_string += dst_string_format.format(GetSocketAddrAsStringInet6(dst)) + " "
            isv6 = 1
        else:
            if (dst.sa_family == AF_LINK):
                out_string += dst_string_format.format(GetSocketAddrAsStringLink(dst))
                if (isv6 == 1):
                    out_string += "                       "
                else:
                    out_string += " "
            else:
                out_string += dst_string_format.format(GetSocketAddrAsStringUnspec(dst)) + " "

    gw = Cast(rt.rt_gateway, 'sockaddr *')
    if (gw.sa_family == AF_INET):
        out_string += dst_string_format.format(GetSocketAddrAsStringInet(gw)) + " "
    else:
        if (gw.sa_family == 30):
            out_string += dst_string_format.format(GetSocketAddrAsStringInet6(gw)) + " "
            isv6 = 1
        else:
            if (gw.sa_family == 18):
                out_string += dst_string_format.format(GetSocketAddrAsStringLink(gw)) + " "
                if (isv6 == 1):
                    out_string += "                       "
                else:
                    out_string += " "
            else:
                dst_string_format.format(GetSocketAddrAsStringUnspec(gw))

    if (rt.rt_flags & RTF_WASCLONED):
        if (kern.ptrsize == 8):
            rt_flags_string_format = "0x{0:<16x}"
            out_string += rt_flags_string_format.format(rt.rt_parent) + " "
        else:
            rt_flags_string_format = "0x{0:<8x}"
            out_string += rt_flags_string_format.format(rt.rt_parent) + " "
    else:
        if (kern.ptrsize == 8):
            out_string += "                   "
        else:
            out_string += "           "

    rt_refcnt_rmx_string_format = "{0:<d} {1:>10d}  "
    out_string += rt_refcnt_rmx_string_format.format(rt.rt_refcnt, rt.rt_rmx.rmx_pksent) + "   "

    rtf_string_format = "{0:>s}"
    if (rt.rt_flags & RTF_UP):
        out_string += rtf_string_format.format("U")
    if (rt.rt_flags & RTF_GATEWAY):
        out_string += rtf_string_format.format("G")
    if (rt.rt_flags & RTF_HOST):
        out_string += rtf_string_format.format("H")
    if (rt.rt_flags & RTF_REJECT):
        out_string += rtf_string_format.format("R")
    if (rt.rt_flags & RTF_DYNAMIC):
        out_string += rtf_string_format.format("D")
    if (rt.rt_flags & RTF_MODIFIED):
        out_string += rtf_string_format.format("M")
    if (rt.rt_flags & RTF_CLONING):
        out_string += rtf_string_format.format("C")
    if (rt.rt_flags & RTF_PRCLONING):
        out_string += rtf_string_format.format("c")
    if (rt.rt_flags & RTF_LLINFO):
        out_string += rtf_string_format.format("L")
    if (rt.rt_flags & RTF_STATIC):
        out_string += rtf_string_format.format("S")
    if (rt.rt_flags & RTF_PROTO1):
        out_string += rtf_string_format.format("1")
    if (rt.rt_flags & RTF_PROTO2):
        out_string += rtf_string_format.format("2")
    if (rt.rt_flags & RTF_PROTO3):
        out_string += rtf_string_format.format("3")
    if (rt.rt_flags & RTF_WASCLONED):
        out_string += rtf_string_format.format("W")
    if (rt.rt_flags & RTF_BROADCAST):
        out_string += rtf_string_format.format("b")
    if (rt.rt_flags & RTF_MULTICAST):
        out_string += rtf_string_format.format("m")
    if (rt.rt_flags & RTF_XRESOLVE):
        out_string += rtf_string_format.format("X")
    if (rt.rt_flags & RTF_BLACKHOLE):
        out_string += rtf_string_format.format("B")
    if (rt.rt_flags & RTF_IFSCOPE):
        out_string += rtf_string_format.format("I")
    if (rt.rt_flags & RTF_CONDEMNED):
        out_string += rtf_string_format.format("Z")
    if (rt.rt_flags & RTF_IFREF):
        out_string += rtf_string_format.format("i")
    if (rt.rt_flags & RTF_PROXY):
        out_string += rtf_string_format.format("Y")
    if (rt.rt_flags & RTF_ROUTER):
        out_string += rtf_string_format.format("r")

    out_string +=  "/"
    out_string += str(rt.rt_ifp.if_name)
    out_string += str(int(rt.rt_ifp.if_unit))
    out_string += "\n"
    return out_string


RNF_ROOT = 2
def GetRtTableAsString(rt_tables):
    out_string = ""
    rn = Cast(rt_tables.rnh_treetop, 'radix_node *')
    rnh_cnt = rt_tables.rnh_cnt

    while (rn.rn_bit >= 0):
        rn = rn.rn_u.rn_node.rn_L

    while 1:
        base = Cast(rn, 'radix_node *')
        while ((rn.rn_parent.rn_u.rn_node.rn_R == rn) and (rn.rn_flags & RNF_ROOT == 0)):
            rn = rn.rn_parent
        rn = rn.rn_parent.rn_u.rn_node.rn_R
        while (rn.rn_bit >= 0):
            rn = rn.rn_u.rn_node.rn_L
        next_rn = rn
        while (base != 0):
            rn = base
            base = rn.rn_u.rn_leaf.rn_Dupedkey
            if ((rn.rn_flags & RNF_ROOT) == 0):
                rt = Cast(rn, 'rtentry *')
                if (kern.ptrsize == 8):
                    rtentry_string_format = "0x{0:<18x}"
                    out_string += rtentry_string_format.format(rt) + " "
                else:
                    rtentry_string_format = "0x{0:<10x}"
                    out_string += rtentry_string_format.format(rt) + " "
                out_string += GetRtEntryPrDetailsAsString(rt) + " "

        rn = next_rn
        if ((rn.rn_flags & RNF_ROOT) != 0):
            break
    return out_string

def GetRtInetAsString():
    rt_tables = kern.globals.rt_tables[2]
    if (kern.ptrsize == 8):
        rt_table_header_format_string = "{0:<18s} {1: <16s} {2:<20s} {3:<16s} {4:<8s} {5:<8s} {6:<8s}"
        print(rt_table_header_format_string.format("rtentry", " dst", "gw", "parent", "Refs", "Use", "flags/if"))
        print(rt_table_header_format_string.format("-" * 18, "-" * 16, "-" * 16, "-" * 16, "-" * 8, "-" * 8, "-" * 8))
        print(GetRtTableAsString(rt_tables))
    else:
        rt_table_header_format_string = "{0:<8s} {1:<16s} {2:<18s} {3:<8s} {4:<8s} {5:<8s} {6:<8s}"
        print(rt_table_header_format_string.format("rtentry", "dst", "gw", "parent", "Refs", "Use", "flags/if"))
        print(rt_table_header_format_string.format("-" * 8, "-" * 16, "-" * 16, "-" * 8, "-" * 8, "-" * 8, "-" * 8))
        print(GetRtTableAsString(rt_tables))

def GetRtInet6AsString():
    rt_tables = kern.globals.rt_tables[30]
    if (kern.ptrsize == 8):
        rt_table_header_format_string = "{0:<18s} {1: <16s} {2:<20s} {3:<16s} {4:<8s} {5:<8s} {6:<8s}"
        print(rt_table_header_format_string.format("rtentry", " dst", "gw", "parent", "Refs", "Use", "flags/if"))
        print(rt_table_header_format_string.format("-" * 18, "-" * 16, "-" * 16, "-" * 16, "-" * 8, "-" * 8, "-" * 8))
        print(GetRtTableAsString(rt_tables))
    else:
        rt_table_header_format_string = "{0:<8s} {1:<16s} {2:<18s} {3:<8s} {4:<8s} {5:<8s} {6:<8s}"
        print(rt_table_header_format_string.format("rtentry", "dst", "gw", "parent", "Refs", "Use", "flags/if"))
        print(rt_table_header_format_string.format("-" * 8, "-" * 16, "-" * 18, "-" * 8, "-" * 8, "-" * 8, "-" * 8))
        print(GetRtTableAsString(rt_tables))

# Macro: show_rt_inet
@lldb_command('show_rt_inet')
def ShowRtInet(cmd_args=None):
    """ Display the IPv4 routing table
    """
    print(GetRtInetAsString())
# EndMacro: show_rt_inet

# Macro: show_rt_inet6
@lldb_command('show_rt_inet6')
def ShowRtInet6(cmd_args=None):
    """ Display the IPv6 routing table
    """
    print(GetRtInet6AsString())
# EndMacro: show_rt_inet6

# Macro: rtentry_showdbg
@lldb_command('rtentry_showdbg')
def ShowRtEntryDebug(cmd_args=None):
    """ Print the debug information of a route entry
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    rtd = kern.GetValueFromAddress(cmd_args[0], 'rtentry_dbg *')
    rtd_summary_format_string = "{0:s} {1:d}"
    out_string += rtd_summary_format_string.format("Total holds : ", rtd.rtd_refhold_cnt) + "\n"
    out_string += rtd_summary_format_string.format("Total releases : ", rtd.rtd_refrele_cnt) + "\n"

    ix = 0
    while (ix < CTRACE_STACK_SIZE):
        kgm_pc = rtd.rtd_alloc.pc[ix]
        if (kgm_pc != 0):
            if (ix == 0):
                out_string += "\nAlloc: (thread " + hex(rtd.rtd_alloc.th) + "):\n"
            out_string += str(int(ix + 1)) + ": "
            out_string += GetSourceInformationForAddress(kgm_pc)
            out_string += "\n"
        ix += 1

    ix = 0
    while (ix < CTRACE_STACK_SIZE):
        kgm_pc = rtd.rtd_free.pc[ix]
        if (kgm_pc != 0):
            if (ix == 0):
                out_string += "\nFree: (thread " + hex(rtd.rtd_free.th) + "):\n"
            out_string += str(int(ix + 1)) + ": "
            out_string += GetSourceInformationForAddress(kgm_pc)
            out_string += "\n"
        ix += 1

    while (cnt < RTD_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = rtd.rtd_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(rtd.rtd_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1

    cnt = 0
    while (cnt < RTD_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = rtd.rtd_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(rtd.rtd_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1

    out_string += "\nTotal locks : " + str(int(rtd.rtd_lock_cnt))
    out_string += "\nTotal unlocks : " + str(int(rtd.rtd_unlock_cnt))

    cnt = 0
    while (cnt < RTD_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = rtd.rtd_lock[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nLock [" + str(int(cnt)) + "] (thread " + hex(rtd.rtd_lock[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1

    cnt = 0
    while (cnt < RTD_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = rtd.rtd_unlock[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nUnlock [" + str(int(cnt)) + "] (thread " + hex(rtd.rtd_unlock[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1

    print(out_string)
# EndMacro: rtentry_showdbg

# Macro: inm_showdbg
@lldb_command('inm_showdbg')
def InmShowDebug(cmd_args=None):
    """ Print the debug information of an IPv4 multicast address
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    inm = kern.GetValueFromAddress(cmd_args[0], 'in_multi_dbg *')
    in_multi_summary_format_string = "{0:s} {1:d}"
    out_string += in_multi_summary_format_string.format("Total holds : ", inm.inm_refhold_cnt)
    out_string += in_multi_summary_format_string.format("Total releases : ", inm.inm_refrele_cnt)

    while (cnt < INM_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = inm.inm_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(inm.inm_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < INM_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = inm.inm_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(inm.inm_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: inm_showdbg

# Macro: ifma_showdbg
@lldb_command('ifma_showdbg')
def IfmaShowDebug(cmd_args=None):
    """ Print the debug information of a link multicast address
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    ifma = kern.GetValueFromAddress(cmd_args[0], 'ifmultiaddr_dbg *')
    link_multi_summary_format_string = "{0:s} {1:d}"
    out_string += link_multi_summary_format_string.format("Total holds : ", ifma.ifma_refhold_cnt) + "\n"
    out_string += link_multi_summary_format_string.format("Total releases : ", ifma.ifma_refrele_cnt) + "\n"

    while (cnt < IFMA_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = ifma.ifma_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(ifma.ifma_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < IFMA_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = ifma.ifma_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(ifma.ifma_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: ifma_showdbg

# Macro: ifpref_showdbg
@lldb_command('ifpref_showdbg')
def IfpRefShowDebug(cmd_args=None):
    """ Print the debug information of an interface ref count
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    dl_if = kern.GetValueFromAddress(cmd_args[0], 'dlil_ifnet_dbg *')
    dl_if_summary_format_string = "{0:s} {1:d}"
    out_string +=  dl_if_summary_format_string.format("Total holds : ", dl_if.dldbg_if_refhold_cnt)
    out_string += dl_if_summary_format_string.format("Total releases : ", dl_if.dldbg_if_refrele_cnt)

    while (cnt < IF_REF_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = dl_if.dldbg_if_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(dl_if.dldbg_if_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < IF_REF_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = dl_if.dldbg_if_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(dl_if.dldbg_if_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: ifpref_showdbg

# Macro: ndpr_showdbg
@lldb_command('ndpr_showdbg')
def ndprShowDebug(cmd_args=None):
    """ Print the debug information of a nd_prefix structure
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    ndpr = kern.GetValueFromAddress(cmd_args[0], 'nd_prefix_dbg *')
    ndpr_summary_format_string = "{0:s} {1:d}"
    out_string += ndpr_summary_format_string.format("Total holds : ", ndpr.ndpr_refhold_cnt)
    out_string += ndpr_summary_format_string.format("Total releases : ", ndpr.ndpr_refrele_cnt)

    while (cnt < NDPR_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = ndpr.ndpr_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(ndpr.ndpr_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < NDPR_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = ndpr.ndpr_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(ndpr.ndpr_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: ndpr_showdbg

# Macro: nddr_showdbg
@lldb_command('nddr_showdbg')
def nddrShowDebug(cmd_args=None):
    """ Print the debug information of a nd_defrouter structure
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    nddr = kern.GetValueFromAddress(cmd_args[0], 'nd_defrouter_dbg *')
    nddr_summary_format_string = "{0:s} {1:d}"
    out_string += nddr_summary_format_string.format("Total holds : ", nddr.nddr_refhold_cnt)
    out_string += nddr_summary_format_string.format("Total releases : ", nddr.nddr_refrele_cnt)

    while (cnt < NDDR_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = nddr.nddr_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(nddr.nddr_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < NDDR_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = nddr.nddr_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(nddr.nddr_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: nddr_showdbg

# Macro: imo_showdbg
@lldb_command('imo_showdbg')
def IpmOptions(cmd_args=None):
    """ Print the debug information of a ip_moptions structure
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    imo = kern.GetValueFromAddress(cmd_args[0], 'ip_moptions_dbg *')
    imo_summary_format_string = "{0:s} {1:d}"
    out_string += imo_summary_format_string.format("Total holds : ", imo.imo_refhold_cnt)
    out_string += imo_summary_format_string.format("Total releases : ", imo.imo_refrele_cnt)

    while (cnt < IMO_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = imo.imo_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(imo.imo_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < IMO_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = imo.imo_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(imo.imo_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: imo_showdbg

# Macro: im6o_showdbg
@lldb_command('im6o_showdbg')
def IpmOptions(cmd_args=None):
    """ Print the debug information of a ip6_moptions structure
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    out_string = ""
    cnt = 0
    im6o = kern.GetValueFromAddress(cmd_args[0], 'ip6_moptions_dbg *')
    im6o_summary_format_string = "{0:s} {1:d}"
    out_string += im6o_summary_format_string.format("Total holds : ", im6o.im6o_refhold_cnt)
    out_string += im6o_summary_format_string.format("Total releases : ", im6o.im6o_refrele_cnt)

    while (cnt < IM6O_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = im6o.im6o_refhold[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nHold [" + str(int(cnt)) + "] (thread " + hex(im6o.im6o_refhold[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    cnt = 0
    while (cnt < IM6O_TRACE_HIST_SIZE):
        ix = 0
        while (ix < CTRACE_STACK_SIZE):
            kgm_pc = im6o.im6o_refrele[cnt].pc[ix]
            if (kgm_pc != 0):
                if (ix == 0):
                    out_string += "\nRelease [" + str(int(cnt)) + "] (thread " + hex(im6o.im6o_refrele[cnt].th) + "):\n"
                out_string += str(int(ix + 1)) + ": "
                out_string += GetSourceInformationForAddress(kgm_pc)
                out_string += "\n"
            ix += 1
        cnt += 1
    print(out_string)
# EndMacro: im6o_showdbg

# Macro: rtentry_trash
@lldb_command('rtentry_trash')
def RtEntryTrash(cmd_args=None):
    """ Walk the list of trash route entries
    """
    out_string = ""
    rt_trash_head = kern.globals.rttrash_head
    rtd = Cast(rt_trash_head.tqh_first, 'rtentry_dbg *')
    rt_trash_format_string = "{0:4d}: {1:x} {2:3d} {3:6d} {4:6d}"
    cnt = 0
    while (int(rtd) != 0):
        if (cnt == 0):
            if (kern.ptrsize == 8):
                print("                rtentry ref   hold   rele             dst    gw             parent flags/if\n")
                print("      ----------------- --- ------ ------ --------------- ----- ------------------ -----------\n")
            else:
                print("        rtentry ref   hold   rele             dst    gw     parent flags/if\n")
                print("      --------- --- ------ ------ --------------- ----- ---------- -----------\n")
        out_string += rt_trash_format_string.format(cnt, rtd, rtd.rtd_refhold_cnt - rtd.rtd_refrele_cnt, rtd.rtd_refhold_cnt, rtd.rtd_refrele_cnt) + "   "
        out_string += GetRtEntryPrDetailsAsString(rtd) + "\n"
        rtd = rtd.rtd_trash_link.tqe_next
        cnt += 1
    print(out_string)
# EndMacro: rtentry_trash

# Macro: show_rtentry
@lldb_command('show_rtentry')
def ShRtEntry(cmd_args=None):
    """ Print rtentry.
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError()

    out_string = ""
    rt = kern.GetValueFromAddress(cmd_args[0], 'rtentry *')
    out_string += GetRtEntryPrDetailsAsString(rt) + "\n"
    print(out_string)
# EndMacro: show_rtentry

# Macro: inm_trash
@lldb_command('inm_trash')
def InmTrash(cmd_args=None):
    """ Walk the list of trash in_multi entries
    """
    out_string = ""
    inm_trash_head = kern.globals.inm_trash_head
    inm = Cast(inm_trash_head.tqh_first, 'in_multi_dbg *')
    inm_trash_format_string = "{0:4d}: {1:x} {2:3d} {3:6d} {4:6d}"
    cnt = 0
    while (int(inm) != 0):
        if (cnt == 0):
            if (kern.ptrsize == 8):
                print("                     inm  ref   hold   rele")
                print("      ------------------  --- ------ ------")
            else:
                print("             inm  ref   hold   rele")
                print("      ----------  --- ------ ------")
        out_string += inm_trash_format_string.format(cnt + 1, inm, inm.inm_refhold_cnt - inm.inm_refrele_cnt, inm.inm_refhold_cnt, inm.inm_refrele_cnt) + "   "
        out_string += GetInAddrAsString(addressof(inm.inm.inm_addr)) + "\n"
        inm = inm.inm_trash_link.tqe_next
        cnt += 1
    print(out_string)
# EndMacro: inm_trash

# Macro: in6m_trash
@lldb_command('in6m_trash')
def In6mTrash(cmd_args=None):
    """ Walk the list of trash in6_multi entries
    """
    out_string = ""
    in6m_trash_head = kern.globals.in6m_trash_head
    in6m = Cast(in6m_trash_head.tqh_first, 'in6_multi_dbg *')
    in6m_trash_format_string = "{0:4d}: {1:x} {2:3d} {3:6d} {4:6d}"
    cnt = 0
    while (int(in6m) != 0):
        if (cnt == 0):
            if (kern.ptrsize == 8):
                print("                    in6m  ref   hold   rele")
                print("      ------------------  --- ------ ------")
            else:
                print("            in6m  ref   hold   rele")
                print("      ----------  --- ------ ------")
        out_string += in6m_trash_format_string.format(cnt + 1, in6m, in6m.in6m_refhold_cnt - in6m.in6m_refrele_cnt, in6m.in6m_refhold_cnt, in6m.in6m_refrele_cnt) + "   "
        out_string += GetIn6AddrAsString(addressof(in6m.in6m.in6m_addr)) + "\n"
        in6m = in6m.in6m_trash_link.tqe_next
        cnt += 1
    print(out_string)
# EndMacro: in6m_trash

# Macro: ifma_trash
@lldb_command('ifma_trash')
def IfmaTrash(cmd_args=None):
    """ Walk the list of trash ifmultiaddr entries
    """
    out_string = ""
    ifma_trash_head = kern.globals.ifma_trash_head
    ifma = Cast(ifma_trash_head.tqh_first, 'ifmultiaddr_dbg *')
    ifma_trash_format_string = "{0:4d}: {1:x} {2:3d} {3:6d} {4:6d}"
    cnt = 0
    while (int(ifma) != 0):
        if (cnt == 0):
            if (kern.ptrsize == 8):
                print("                    ifma  ref   hold   rele")
                print("      ------------------  --- ------ ------")
            else:
                print("            ifma  ref   hold   rele")
                print("      ----------  --- ------ ------")
        out_string += ifma_trash_format_string.format(cnt + 1, ifma, ifma.ifma_refhold_cnt - ifma.ifma_refrele_cnt, ifma.ifma_refhold_cnt, ifma.ifma_refrele_cnt) + "   "
        out_string += GetSocketAddrAsString(ifma.ifma.ifma_addr) + "\n"
        out_string += " @ " + ifma.ifma.ifma_ifp.if_xname
        ifma = ifma.ifma_trash_link.tqe_next
        cnt += 1
    print(out_string)
# EndMacro: ifma_trash

def GetInPcb(pcb, proto):
    out_string = ""
    out_string += hex(pcb)

    if (proto == IPPROTO_TCP):
        out_string +=  " tcp"
    elif (proto == IPPROTO_UDP):
        out_string += " udp"
    elif (proto == IPPROTO_RAW):
        out_string += " raw"
    else:
        out_string += str(proto) +  "."

    if (pcb.inp_vflag & INP_IPV4):
        out_string += "4 "
    if (pcb.inp_vflag & INP_IPV6):
        out_string += "6 "

    if (pcb.inp_vflag & INP_IPV4):
        out_string += "                                       "
        out_string += GetInAddrAsString(addressof(pcb.inp_dependladdr.inp46_local.ia46_addr4))
    else:
        out_string += "  "
        out_string += GetIn6AddrAsString((pcb.inp_dependladdr.inp6_local.__u6_addr.__u6_addr8))

    out_string += " "
    out_string += Getntohs(pcb.inp_lport)
    out_string += " "

    if (pcb.inp_vflag & INP_IPV4):
        out_string += "                                 "
        out_string += GetInAddrAsString(addressof(pcb.inp_dependfaddr.inp46_foreign.ia46_addr4))
    else:
        out_string += GetIn6AddrAsString((pcb.inp_dependfaddr.inp6_foreign.__u6_addr.__u6_addr8))

    out_string += " "
    out_string += Getntohs(pcb.inp_fport)
    out_string += " "

    if (proto == IPPROTO_TCP):
        out_string += GetTcpState(pcb.inp_ppcb)

    out_string += "\n\t"
    if (pcb.inp_flags & INP_RECVOPTS):
        out_string += "recvopts "
    if (pcb.inp_flags & INP_RECVRETOPTS):
        out_string += "recvretopts "
    if (pcb.inp_flags & INP_RECVDSTADDR):
        out_string += "recvdstaddr "
    if (pcb.inp_flags & INP_HDRINCL):
        out_string += "hdrincl "
    if (pcb.inp_flags & INP_HIGHPORT):
        out_string += "highport "
    if (pcb.inp_flags & INP_LOWPORT):
        out_string += "lowport "
    if (pcb.inp_flags & INP_ANONPORT):
        out_string += "anonport "
    if (pcb.inp_flags & INP_RECVIF):
        out_string += "recvif "
    if (pcb.inp_flags & INP_MTUDISC):
        out_string += "mtudisc "
    if (pcb.inp_flags & INP_STRIPHDR):
        out_string += "striphdr "
    if (pcb.inp_flags & INP_RECV_ANYIF):
        out_string += "recv_anyif "
    if (pcb.inp_flags & INP_INADDR_ANY):
        out_string += "inaddr_any "
    if (pcb.inp_flags & INP_RECVTTL):
        out_string += "recvttl "
    if (pcb.inp_flags & INP_UDP_NOCKSUM):
        out_string += "nocksum "
    if (pcb.inp_flags & INP_BOUND_IF):
        out_string += "boundif "
    if (pcb.inp_flags & IN6P_IPV6_V6ONLY):
        out_string += "v6only "
    if (pcb.inp_flags & IN6P_PKTINFO):
        out_string += "pktinfo "
    if (pcb.inp_flags & IN6P_HOPLIMIT):
        out_string += "hoplimit "
    if (pcb.inp_flags & IN6P_HOPOPTS):
        out_string += "hopopts "
    if (pcb.inp_flags & IN6P_DSTOPTS):
        out_string += "dstopts "
    if (pcb.inp_flags & IN6P_RTHDR):
        out_string += "rthdr "
    if (pcb.inp_flags & IN6P_RTHDRDSTOPTS):
        out_string += "rthdrdstopts "
    if (pcb.inp_flags & IN6P_TCLASS):
        out_string += "rcv_tclass "
    if (pcb.inp_flags & IN6P_AUTOFLOWLABEL):
        out_string += "autoflowlabel "
    if (pcb.inp_flags & IN6P_BINDV6ONLY):
        out_string += "bindv6only "
    if (pcb.inp_flags & IN6P_RFC2292):
        out_string += "RFC2292 "
    if (pcb.inp_flags & IN6P_MTU):
        out_string += "rcv_pmtu "
    if (pcb.inp_flags & INP_PKTINFO):
        out_string += "pktinfo "
    if (pcb.inp_flags & INP_FLOW_SUSPENDED):
        out_string += "suspended "
    if (pcb.inp_flags & INP_NO_IFT_CELLULAR):
        out_string += "nocellular "
    if (pcb.inp_flags & INP_FLOW_CONTROLLED):
        out_string += "flowctld "
    if (pcb.inp_flags & INP_FC_FEEDBACK):
        out_string += "fcfeedback "
    if (pcb.inp_flags2 & INP2_TIMEWAIT):
        out_string += "timewait "
    if (pcb.inp_flags2 & INP2_IN_FCTREE):
        out_string += "in_fctree "
    if (pcb.inp_flags2 & INP2_WANT_APP_POLICY):
        out_string += "want_app_policy "

    out_string += "\n\t"
    so = pcb.inp_socket
    if (so != 0):
        out_string += "so=" + str(so) + " s=" + str(int(so.so_snd.sb_cc)) + " r=" + str(int(so.so_rcv.sb_cc))
        if proto == IPPROTO_TCP :
            tcpcb = cast(pcb.inp_ppcb, 'tcpcb *')
            out_string += " reass=" + str(int(tcpcb.t_reassqlen))

        out_string += " usecnt=" + str(int(so.so_usecount))

    if (pcb.inp_state == 0 or pcb.inp_state == INPCB_STATE_INUSE):
        out_string += " inuse"
    else:
        if (pcb.inp_state == INPCB_STATE_DEAD):
            out_string += " dead"
        else:
            out_string += " unknown (" + str(int(pcb.inp_state)) + ")"

    ifname = ""
    if (pcb.inp_flags & INP_BOUND_IF):
        ifp = pcb.inp_boundifp
    else:
        ifp = pcb.inp_last_outifp
    if (ifp != 0):
        ifname = ifp.if_xname
    out_string += " ifp=" + str(ifname)

    out_string += " last_proc=" + str(pcb.inp_last_proc_name) + ":" + str(int(so.last_pid))

    return out_string

def CalcMbufInList(mpkt, pkt_cnt, buf_byte_cnt, mbuf_cnt, mbuf_cluster_cnt):
    while (mpkt != 0):
        mp = mpkt
        if kern.arch == 'x86_64':
            mpkt = mp.m_hdr.mh_nextpkt
        else:
            mpkt = mp.M_hdr_common.M_hdr.mh_nextpkt
        pkt_cnt[0] +=1
        while (mp != 0):
            if kern.arch == 'x86_64':
                mnext = mp.m_hdr.mh_next
                mflags = mp.m_hdr.mh_flags
                mtype = mp.m_hdr.mh_type
            else:
                mnext = mp.M_hdr_common.M_hdr.mh_next
                mflags = mp.M_hdr_common.M_hdr.mh_flags
                mtype = mp.M_hdr_common.M_hdr.mh_type
            mbuf_cnt[0] += 1
            buf_byte_cnt[int(mtype)] += 256
            buf_byte_cnt[Mbuf_Type.MT_LAST] += 256
            if (mflags & 0x01):
                mbuf_cluster_cnt[0] += 1
                if kern.arch == 'x86_64':
                    extsize = mp.M_dat.MH.MH_dat.MH_ext.ext_size
                else:
                    extsize = mp.M_hdr_common.M_ext.ext_size
                buf_byte_cnt[int(mtype)] += extsize
                buf_byte_cnt[Mbuf_Type.MT_LAST] += extsize
            mp = mnext

def CalcMbufInSB(so, snd_cc, snd_buf, rcv_cc, rcv_buf, snd_record_cnt, rcv_record_cnt, snd_mbuf_cnt, rcv_mbuf_cnt, snd_mbuf_cluster_cnt, rcv_mbuf_cluster_cnt):
    snd_cc[0] += so.so_snd.sb_cc
    mpkt = so.so_snd.sb_mb
    CalcMbufInList(mpkt, snd_record_cnt, snd_buf, snd_mbuf_cnt, snd_mbuf_cluster_cnt)
    rcv_cc[0] += so.so_rcv.sb_cc
    mpkt = so.so_rcv.sb_mb
    CalcMbufInList(mpkt, rcv_record_cnt, rcv_buf, rcv_mbuf_cnt, rcv_mbuf_cluster_cnt)

# Macro: show_socket_sb_mbuf_usage
@lldb_command('show_socket_sb_mbuf_usage')
def ShowSocketSbMbufUsage(cmd_args=None):
    """ Display for a socket the mbuf usage of the send and receive socket buffers
    """
    if cmd_args is None or len(cmd_args) == 0:
            print("Missing argument 0 in user function.")
            return
    so = kern.GetValueFromAddress(cmd_args[0], 'socket *')
    out_string = ""
    if (so != 0):
        snd_mbuf_cnt = [0]
        snd_mbuf_cluster_cnt = [0]
        snd_record_cnt = [0]
        snd_cc = [0]
        snd_buf = [0] * (Mbuf_Type.MT_LAST + 1)
        rcv_mbuf_cnt = [0]
        rcv_mbuf_cluster_cnt = [0]
        rcv_record_cnt = [0]
        rcv_cc = [0]
        rcv_buf = [0] * (Mbuf_Type.MT_LAST + 1)
        total_mbuf_bytes = 0
        CalcMbufInSB(so, snd_cc, snd_buf, rcv_cc, rcv_buf, snd_record_cnt, rcv_record_cnt, snd_mbuf_cnt, rcv_mbuf_cnt, snd_mbuf_cluster_cnt, rcv_mbuf_cluster_cnt)
        out_string += "total send mbuf count: " + str(int(snd_mbuf_cnt[0])) + " receive mbuf count: " + str(int(rcv_mbuf_cnt[0])) + "\n"
        out_string += "total send mbuf cluster count: " + str(int(snd_mbuf_cluster_cnt[0])) + " receive mbuf cluster count: " + str(int(rcv_mbuf_cluster_cnt[0])) + "\n"
        out_string += "total send record count: " + str(int(snd_record_cnt[0])) + " receive record count: " + str(int(rcv_record_cnt[0])) + "\n"
        out_string += "total snd_cc (total bytes in send buffers): " + str(int(snd_cc[0])) + " rcv_cc (total bytes in receive buffers): " + str(int(rcv_cc[0])) + "\n"
        out_string += "total snd_buf bytes " + str(int(snd_buf[Mbuf_Type.MT_LAST])) + " rcv_buf bytes " + str(int(rcv_buf[Mbuf_Type.MT_LAST])) + "\n"
        for x in range(Mbuf_Type.MT_LAST):
            if (snd_buf[x] != 0 or rcv_buf[x] != 0):
                out_string += "total snd_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(snd_buf[x])) + " total recv_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(rcv_buf[x])) + "\n"
                total_mbuf_bytes += snd_buf[x] + rcv_buf[x]
    print(out_string)
# EndMacro:  show_socket_sb_mbuf_usage


def GetMptcpInfo():
    mptcp = kern.globals.mtcbinfo

    mppcb = cast(mptcp.mppi_pcbs.tqh_first, 'mppcb *')
    pcbseen = 0
    reinject_cnt=[0]
    reinject_byte_cnt=[0] * (Mbuf_Type.MT_LAST + 1)
    reinject_mbuf_cnt=[0]
    reinject_mbuf_cluster_cnt=[0]

    snd_mbuf_cnt = [0]
    snd_mbuf_cluster_cnt = [0]
    snd_record_cnt = [0]
    snd_cc = [0]
    snd_buf = [0] * (Mbuf_Type.MT_LAST + 1)
    rcv_mbuf_cnt = [0]
    rcv_mbuf_cluster_cnt = [0]
    rcv_record_cnt = [0]
    rcv_cc = [0]
    rcv_buf = [0] * (Mbuf_Type.MT_LAST + 1)
    total_mbuf_bytes = 0
    while mppcb != 0:
        mpte = mppcb.mpp_pcbe
        pcbseen += 1
        CalcMbufInList(mpte.mpte_reinjectq, reinject_cnt, reinject_byte_cnt, reinject_mbuf_cnt, reinject_mbuf_cluster_cnt)

        socket = mppcb.mpp_socket
        if socket != 0:
            CalcMbufInSB(socket, snd_cc, snd_buf, rcv_cc, rcv_buf, snd_record_cnt, rcv_record_cnt, snd_mbuf_cnt, rcv_mbuf_cnt, snd_mbuf_cluster_cnt, rcv_mbuf_cluster_cnt)

        mppcb = cast(mppcb.mpp_entry.tqe_next, 'mppcb *')

    out_string = ""
    out_string += "total pcbs seen: " + str(int(pcbseen)) + "\n"
    out_string += "total reinject mbuf count: " + str(int(reinject_mbuf_cnt[0])) + "\n"
    out_string += "total reinject mbuf cluster count: " + str(int(reinject_mbuf_cluster_cnt[0])) + "\n"
    out_string += "total reinject record count: " + str(int(reinject_cnt[0])) + "\n"
    for x in range(Mbuf_Type.MT_LAST):
        if (reinject_byte_cnt[x] != 0):
            out_string += "total reinject bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(reinject_byte_cnt[x])) + "\n"
            total_mbuf_bytes += reinject_byte_cnt[x]


    out_string += "total send mbuf count: " + str(int(snd_mbuf_cnt[0])) + " receive mbuf count: " + str(int(rcv_mbuf_cnt[0])) + "\n"
    out_string += "total send mbuf cluster count: " + str(int(snd_mbuf_cluster_cnt[0])) + " receive mbuf cluster count: " + str(int(rcv_mbuf_cluster_cnt[0])) + "\n"
    out_string += "total send record count: " + str(int(snd_record_cnt[0])) + " receive record count: " + str(int(rcv_record_cnt[0])) + "\n"
    out_string += "total snd_cc (total bytes in send buffers): " + str(int(snd_cc[0])) + " rcv_cc (total bytes in receive buffers): " + str(int(rcv_cc[0])) + "\n"
    out_string += "total snd_buf bytes " + str(int(snd_buf[Mbuf_Type.MT_LAST])) + " rcv_buf bytes " + str(int(rcv_buf[Mbuf_Type.MT_LAST])) + "\n"
    for x in range(Mbuf_Type.MT_LAST):
        if (snd_buf[x] != 0 or rcv_buf[x] != 0):
            out_string += "total snd_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(snd_buf[x])) + " total recv_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(rcv_buf[x])) + "\n"
            total_mbuf_bytes += snd_buf[x] + rcv_buf[x]

    out_string += "total mbuf bytes used by MPTCP: "+ str(total_mbuf_bytes) + "\n"
    print(out_string)

def GetPcbInfo(pcbi, proto):
    tcp_reassqlen = [0]
    tcp_reassq_bytes = 0
    mbuf_reassq_cnt = [0]
    mbuf_reassq_bytes = [0] * (Mbuf_Type.MT_LAST + 1)
    mbuf_reassq_cluster = [0]
    out_string = ""
    snd_mbuf_cnt = [0]
    snd_mbuf_cluster_cnt = [0]
    snd_record_cnt = [0]
    snd_cc = [0]
    snd_buf = [0] * (Mbuf_Type.MT_LAST + 1)
    rcv_mbuf_cnt = [0]
    rcv_mbuf_cluster_cnt = [0]
    rcv_record_cnt = [0]
    rcv_cc = [0]
    rcv_buf = [0] * (Mbuf_Type.MT_LAST + 1)
    pcbseen = 0
    out_string += "lastport " + str(int(pcbi.ipi_lastport)) + " lastlow " + str(int(pcbi.ipi_lastlow)) + " lasthi " + str(int(pcbi.ipi_lasthi)) + "\n"
    out_string += "active pcb count is " + str(int(pcbi.ipi_count)) + "\n"
    hashsize = pcbi.ipi_hashmask + 1
    out_string += "hash size is " + str(int(hashsize)) + "\n"
    out_string += str(pcbi.ipi_hashbase) + " has the following inpcb(s):\n"
    if (kern.ptrsize == 8):
        out_string += "pcb                proto  source                                        port  destination                                 port\n"
    else:
        out_string += "pcb            proto  source           address  port  destination         address  port\n\n"

    if proto == IPPROTO_RAW:
        head = cast(pcbi.ipi_listhead, 'inpcbhead *')
        pcb = cast(head.lh_first, 'inpcb *')
        while pcb != 0:
            pcbseen += 1
            out_string += GetInPcb(pcb, proto) + "\n"
            so = pcb.inp_socket
            if so != 0:
                CalcMbufInSB(so, snd_cc, snd_buf, rcv_cc, rcv_buf, snd_record_cnt, rcv_record_cnt, snd_mbuf_cnt, rcv_mbuf_cnt, snd_mbuf_cluster_cnt, rcv_mbuf_cluster_cnt)
            pcb = cast(pcb.inp_list.le_next, 'inpcb *')
    else:
        i = 0
        hashbase = pcbi.ipi_hashbase
        while (i < hashsize):
            head = hashbase[i]
            pcb = cast(head.lh_first, 'inpcb *')
            while pcb != 0:
                pcbseen += 1
                out_string += GetInPcb(pcb, proto) + "\n"
                so = pcb.inp_socket
                if so != 0:
                    CalcMbufInSB(so, snd_cc, snd_buf, rcv_cc, rcv_buf, snd_record_cnt, rcv_record_cnt, snd_mbuf_cnt, rcv_mbuf_cnt, snd_mbuf_cluster_cnt, rcv_mbuf_cluster_cnt)
                if proto == IPPROTO_TCP and pcb.inp_ppcb:
                    tcpcb = cast(pcb.inp_ppcb, 'tcpcb *')
                    reass_entry = cast(tcpcb.t_segq.lh_first, 'tseg_qent *')
                    curr_reass = 0
                    while reass_entry != 0:
                        CalcMbufInList(reass_entry.tqe_m, tcp_reassqlen, mbuf_reassq_bytes, mbuf_reassq_cnt, mbuf_reassq_cluster)
                        tcp_reassq_bytes += reass_entry.tqe_len
                        curr_reass += reass_entry.tqe_len

                        reass_entry = reass_entry.tqe_q.le_next

                pcb = cast(pcb.inp_hash.le_next, 'inpcb *')
            i += 1

    out_string += "total pcbs seen: " + str(int(pcbseen)) + "\n"
    out_string += "total send mbuf count: " + str(int(snd_mbuf_cnt[0])) + " receive mbuf count: " + str(int(rcv_mbuf_cnt[0])) + "\n"
    out_string += "total send mbuf cluster count: " + str(int(snd_mbuf_cluster_cnt[0])) + " receive mbuf cluster count: " + str(int(rcv_mbuf_cluster_cnt[0])) + "\n"
    out_string += "total send record count: " + str(int(snd_record_cnt[0])) + " receive record count: " + str(int(rcv_record_cnt[0])) + "\n"
    out_string += "total snd_cc (total bytes in send buffers): " + str(int(snd_cc[0])) + " rcv_cc (total bytes in receive buffers): " + str(int(rcv_cc[0])) + "\n"
    out_string += "total snd_buf bytes " + str(int(snd_buf[Mbuf_Type.MT_LAST])) + " rcv_buf bytes " + str(int(rcv_buf[Mbuf_Type.MT_LAST])) + "\n"
    for x in range(Mbuf_Type.MT_LAST):
        if (snd_buf[x] != 0 or rcv_buf[x] != 0):
            out_string += "total snd_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(snd_buf[x])) + " total recv_buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(rcv_buf[x])) + "\n"
    out_string += "port hash base is " + hex(pcbi.ipi_porthashbase) + "\n"
    if proto == IPPROTO_TCP:
        out_string += "TCP reassembly queue length: " + str(tcp_reassqlen[0]) + " TCP-payload bytes: " + str(tcp_reassq_bytes) + "\n"

        for x in range(Mbuf_Type.MT_LAST):
            if mbuf_reassq_bytes[x] != 0:
                out_string += "total reassq bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(mbuf_reassq_bytes[x]) + "\n"

    i = 0
    hashbase = pcbi.ipi_porthashbase
    while (i < hashsize):
        head = hashbase[i]
        pcb = cast(head.lh_first, 'inpcbport *')
        while pcb != 0:
            out_string += "\t"
            out_string += GetInPcbPort(pcb)
            out_string += "\n"
            pcb = cast(pcb.phd_hash.le_next, 'inpcbport *')
        i += 1

    return out_string

def GetInPcbPort(ppcb):
    out_string = ""
    out_string += hex(ppcb) + ": lport "
    out_string += Getntohs(ppcb.phd_port)
    return out_string


def Getntohs(port):
    out_string = ""
    #p = unsigned(int(port) & 0x0000ffff)
    p = ((port & 0x0000ff00) >> 8)
    p |= ((port & 0x000000ff) << 8)
    return str(p)


# Macro: mbuf_list_usage_summary
@lldb_command('mbuf_list_usage_summary')
def ShowMbufListUsageSummary(cmd_args=None):
    """ Print mbuf list usage summary
    Usage: mbuf_list_usage_summary [mbuf_addr]
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError()

    out_string = ""
    pkt_cnt = [0]
    buf_byte_cnt = [0] * (Mbuf_Type.MT_LAST + 1)
    mbuf_cnt = [0]
    mbuf_cluster_cnt = [0]

    mpkt = kern.GetValueFromAddress(cmd_args[0], 'struct mbuf *')
    CalcMbufInList(mpkt, pkt_cnt, buf_byte_cnt, mbuf_cnt, mbuf_cluster_cnt)

    out_string += "Total packet count is " + str(int(pkt_cnt[0])) + "\n"
    for x in range(Mbuf_Type.MT_LAST):
        if (buf_byte_cnt[x] != 0):
            out_string += "Total buf bytes of type " + Mbuf_Type.reverse_mapping[x] + " : " + str(int(buf_byte_cnt[x])) + "\n"
    out_string += "Total mbuf count " + str(int(mbuf_cnt[0])) + "\n"
    out_string += "Total mbuf cluster count " + str(int(mbuf_cluster_cnt[0])) + "\n"
    print(out_string)

# Macro: show_kern_event_pcbinfo
def GetKernEventPcbInfo(kev_pcb_head):
    out_string = ""
    pcb = Cast(kev_pcb_head.lh_first, 'kern_event_pcb *')
    if (kern.ptrsize == 8):
        kev_pcb_format_string = "0x{0:<16x} {1:12d} {2:16d} {3:16d} {4:16d} {5:16d}"
        out_string += "  evp socket         vendor code      class filter      subclass filter     so_rcv.sb_cc      so_rcv.sb_mbcnt\n"
        out_string += "--------------       -----------      ------------      ---------------     ------------      ---------------\n"
    else:
        kev_pcb_format_string = "0x{0:<8x} {1:12d} {2:16d} {3:16d} {4:16d} {5:16d}"
        out_string += "evp socket       vendor code      class filter      subclass filter     so_rcv.sb_cc      so_rcv.sb_mbcnt\n"
        out_string += "----------       -----------      ------------      ---------------     ------------      ---------------\n"
    while (pcb != 0):
        out_string += kev_pcb_format_string.format(pcb.evp_socket, pcb.evp_vendor_code_filter, pcb.evp_class_filter, pcb.evp_subclass_filter, pcb.evp_socket.so_rcv.sb_cc, pcb.evp_socket.so_rcv.sb_mbcnt)
        out_string += "\n"
        pcb = pcb.evp_link.le_next
    return out_string

@lldb_command('show_kern_event_pcbinfo')
def ShowKernEventPcbInfo(cmd_args=None):
    """ Display the list of Kernel Event protocol control block information
    """
    print(GetKernEventPcbInfo(addressof(kern.globals.kern_event_head)))
# EndMacro:  show_kern_event_pcbinfo

# Macro: show_kern_control_pcbinfo
def GetKernControlPcbInfo(ctl_head):
    out_string = ""
    kctl = Cast(ctl_head.tqh_first, 'kctl *')
    if (kern.ptrsize == 8):
        kcb_format_string = "0x{0:<16x} {1:10d} {2:10d} {3:10d}\n"
    else:
        kcb_format_string = "0x{0:<8x} {1:10d} {2:10d} {3:10d}\n"
    while unsigned(kctl) != 0:
        kctl_name = "controller: " + str(kctl.name) + "\n"
        out_string += kctl_name
        kcb = Cast(kctl.kcb_head.tqh_first, 'ctl_cb *')
        if unsigned(kcb) != 0:
            if (kern.ptrsize == 8):
                out_string += "socket               usecount     snd_cc     rcv_cc\n"
                out_string += "------               --------     ------     ------\n"
            else:
                out_string += "socket       usecount     snd_cc     rcv_cc\n"
                out_string += "------       --------     ------     ------\n"
        while unsigned(kcb) != 0:
            so = Cast(kcb.so, 'socket *')
            snd_cc = so.so_snd.sb_cc
            rcv_cc = so.so_rcv.sb_cc
            out_string += kcb_format_string.format(kcb.so, kcb.usecount, snd_cc, rcv_cc)
            kcb = kcb.next.tqe_next
        out_string += "\n"
        kctl = kctl.next.tqe_next
    return out_string

@lldb_command('show_kern_control_pcbinfo')
def ShowKernControlPcbInfo(cmd_args=None):
    """ Display the list of Kernel Control protocol control block information
    """
    print(GetKernControlPcbInfo(addressof(kern.globals.ctl_head)))
# EndMacro:  show_kern_control_pcbinfo

# Macro: show_unix_domain_pcbinfo
def GetUnixDomainPCBAsString(unp, type) :
    out_string = ""
    pcb = Cast(unp, 'unpcb *')
    out_string += "unpcb: " + hex(pcb)  + " " + str(type)
    out_string += " unp_socket: " + hex(pcb.unp_socket)
    out_string += " unp_vnode: " + hex(pcb.unp_vnode)
    out_string += " unp_conn: " + hex(pcb.unp_conn)
    out_string += " unp_addr: " + GetSocketAddrAsStringUnix(pcb.unp_addr)
    out_string += " unp_gencnt: " + str(int(pcb.unp_gencnt))
    out_string += " unp_flags: " + hex(pcb.unp_flags)
    if pcb.unp_socket != 0:
        so = Cast(pcb.unp_socket, 'socket *')
        out_string += " s=" + str(int(so.so_snd.sb_cc)) + " r=" + str(int(so.so_rcv.sb_cc)) + " usecnt=" + str(int(so.so_usecount))
    return out_string

def GetUnixDomainPcbInfo(unp_head, type):
    out_string = ""
    unp = Cast(unp_head.lh_first, 'unpcb *')
    while unsigned(unp) != 0:
        out_string += GetUnixDomainPCBAsString(unp, type)
        out_string += "\n"
        unp = unp.unp_link.le_next
    return out_string

@lldb_command('show_unix_domain_pcbinfo')
def ShowUnixDomainPcbInfo(cmd_args=None):
    """ Display the list of unix domain pcb
    """
    print(GetUnixDomainPcbInfo(addressof(kern.globals.unp_dhead), "dgram"))
    print(GetUnixDomainPcbInfo(addressof(kern.globals.unp_shead), "stream"))
# EndMacro:  show_kern_control_pcbinfo

# Macro: show_tcp_pcbinfo
@lldb_command('show_tcp_pcbinfo')
def ShowTcpPcbInfo(cmd_args=None):
    """ Display the list of TCP protocol control block information
    """
    print(GetPcbInfo(addressof(kern.globals.tcbinfo), IPPROTO_TCP))
# EndMacro:  show_tcp_pcbinfo

# Macro: show_udp_pcbinfo
@lldb_command('show_udp_pcbinfo')
def ShowUdpPcbInfo(cmd_args=None):
    """ Display the list of UDP protocol control block information
    """
    print(GetPcbInfo(addressof(kern.globals.udbinfo), IPPROTO_UDP))
# EndMacro:  show_udp_pcbinfo

# Macro: show_rip_pcbinfo
@lldb_command('show_rip_pcbinfo')
def ShowRipPcbInfo(cmd_args=None):
    """ Display the list of Raw IP protocol control block information
    """
    print(GetPcbInfo(addressof(kern.globals.ripcbinfo), IPPROTO_RAW))
# EndMacro:  show_rip_pcbinfo

# Macro: show_mptcp_pcbinfo
@lldb_command('show_mptcp_pcbinfo')
def ShowMptcpPcbInfo(cmd_args=None):
    """ Display the list of MPTCP protocol control block information
    """
    GetMptcpInfo()
# EndMacro:  show_mptcp_pcbinfo

# Macro: show_domains
@lldb_command('show_domains')
def ShowDomains(cmd_args=None):
    """ Display the list of the domains
    """
    out_string = ""
    domains = kern.globals.domains
    dp = Cast(domains.tqh_first, 'domain *')
    ifma_trash_format_string = "{0:4d}: {1:x} {2:3d} {3:6d} {4:6d}"
    cnt = 0
    while (dp != 0):
        out_string += "\"" + str(dp.dom_name) + "\"" + "[" + str(int(dp.dom_refs)) + " refs] domain " + hex(dp) + "\n"
        out_string += "    family:\t" + str(int(dp.dom_family)) + "\n"
        out_string += "    flags:0x\t" + str(int(dp.dom_flags)) + "\n"
        out_string += "    rtparams:\toff=" + str(int(dp.dom_rtoffset)) + ", maxrtkey=" + str(int(dp.dom_maxrtkey)) + "\n"

        if (dp.dom_init):
            out_string += "    init:\t"
            out_string += GetSourceInformationForAddress(dp.dom_init) + "\n"
        if (dp.dom_externalize):
            out_string += "    externalize:\t"
            out_string += GetSourceInformationForAddress(dp.dom_externalize) + "\n"
        if (dp.dom_dispose):
            out_string += "    dispose:\t"
            out_string += GetSourceInformationForAddress(dp.dom_dispose) + "\n"
        if (dp.dom_rtattach):
            out_string += "    rtattach:\t"
            out_string += GetSourceInformationForAddress(dp.dom_rtattach) + "\n"
        if (dp.dom_old):
            out_string += "    old:\t"
            out_string += GetSourceInformationForAddress(dp.dom_old) + "\n"

        pr = Cast(dp.dom_protosw.tqh_first, 'protosw *')
        while pr != 0:
            pru = pr.pr_usrreqs
            out_string += "\ttype " + str(int(pr.pr_type)) + ", protocol " + str(int(pr.pr_protocol)) + ", protosw " + hex(pr) + "\n"
            out_string += "\t    flags:0x\t" + hex(pr.pr_flags) + "\n"
            if (pr.pr_input):
                out_string += "\t    input:\t"
                out_string += GetSourceInformationForAddress(pr.pr_input) + "\n"
            if (pr.pr_output):
                out_string += "\t    output:\t"
                out_string += GetSourceInformationForAddress(pr.pr_output) + "\n"
            if (pr.pr_ctlinput):
                out_string += "\t    ctlinput:\t"
                out_string += GetSourceInformationForAddress(pr.pr_ctlinput) + "\n"
            if (pr.pr_ctloutput):
                out_string += "\t    ctloutput:\t"
                out_string += GetSourceInformationForAddress(pr.pr_ctloutput) + "\n"
            if (pr.pr_init):
                out_string += "\t    init:\t"
                out_string += GetSourceInformationForAddress(pr.pr_init) + "\n"
            if (pr.pr_drain):
                out_string += "\t    drain:\t"
                out_string += GetSourceInformationForAddress(pr.pr_drain) + "\n"
            if (pr.pr_lock):
                out_string += "\t    lock:\t"
                out_string += GetSourceInformationForAddress(pr.pr_lock) + "\n"
            if (pr.pr_unlock):
                out_string += "\t    unlock:\t"
                out_string += GetSourceInformationForAddress(pr.pr_unlock) + "\n"
            if (pr.pr_getlock):
                out_string += "\t    getlock:\t"
                out_string += GetSourceInformationForAddress(pr.pr_getlock) + "\n"
            if (pr.pr_old):
                out_string += "\t    old:\t"
                out_string += GetSourceInformationForAddress(pr.pr_old) + "\n"
                if (pr.pr_old.pr_sysctl):
                    out_string += "\t    sysctl:\t"
                    out_string += GetSourceInformationForAddress(pr.pr_old.pr_sysctl) + "\n"

            out_string += "\t    pru_flags:0x\t" + hex(pru.pru_flags) + "\n"
            out_string += "\t    abort:\t"
            out_string += GetSourceInformationForAddress(pru.pru_abort) + "\n"
            out_string += "\t    accept:\t"
            out_string += GetSourceInformationForAddress(pru.pru_accept) + "\n"
            out_string += "\t    attach:\t"
            out_string += GetSourceInformationForAddress(pru.pru_attach) + "\n"
            out_string += "\t    bind:\t"
            out_string += GetSourceInformationForAddress(pru.pru_bind) + "\n"
            out_string += "\t    connect:\t"
            out_string += GetSourceInformationForAddress(pru.pru_connect) + "\n"
            out_string += "\t    connect2:\t"
            out_string += GetSourceInformationForAddress(pru.pru_connect2) + "\n"
            out_string += "\t    connectx:\t"
            out_string += GetSourceInformationForAddress(pru.pru_connectx) + "\n"
            out_string += "\t    control:\t"
            out_string += GetSourceInformationForAddress(pru.pru_control) + "\n"
            out_string += "\t    detach:\t"
            out_string += GetSourceInformationForAddress(pru.pru_detach) + "\n"
            out_string += "\t    disconnect:\t"
            out_string += GetSourceInformationForAddress(pru.pru_disconnect) + "\n"
            out_string += "\t    listen:\t"
            out_string += GetSourceInformationForAddress(pru.pru_listen) + "\n"
            out_string += "\t    peeraddr:\t"
            out_string += GetSourceInformationForAddress(pru.pru_peeraddr) + "\n"
            out_string += "\t    rcvd:\t"
            out_string += GetSourceInformationForAddress(pru.pru_rcvd) + "\n"
            out_string += "\t    rcvoob:\t"
            out_string += GetSourceInformationForAddress(pru.pru_rcvoob) + "\n"
            out_string += "\t    send:\t"
            out_string += GetSourceInformationForAddress(pru.pru_send) + "\n"
            out_string += "\t    sense:\t"
            out_string += GetSourceInformationForAddress(pru.pru_sense) + "\n"
            out_string += "\t    shutdown:\t"
            out_string += GetSourceInformationForAddress(pru.pru_shutdown) + "\n"
            out_string += "\t    sockaddr:\t"
            out_string += GetSourceInformationForAddress(pru.pru_sockaddr) + "\n"
            out_string += "\t    sopoll:\t"
            out_string += GetSourceInformationForAddress(pru.pru_sopoll) + "\n"
            out_string += "\t    soreceive:\t"
            out_string += GetSourceInformationForAddress(pru.pru_soreceive) + "\n"
            out_string += "\t    sosend:\t"
            out_string += GetSourceInformationForAddress(pru.pru_sosend) + "\n"
            pr = pr.pr_entry.tqe_next
        dp = dp.dom_entry.tqe_next

        print(out_string)
# EndMacro: show_domains

# Macro: tcp_count_rxt_segments
@lldb_command('tcp_count_rxt_segments')
def TCPCountRxtSegments(cmd_args=None):
    """ Size of the t_rxt_segments chain
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Missing argument 0 in user function.")

    tp = kern.GetValueFromAddress(cmd_args[0], 'tcpcb *')
    rxseg = cast(tp.t_rxt_segments.slh_first, 'tcp_rxt_seg *')
    cnt = 0
    while rxseg != 0:
        cnt += 1
        rxseg = rxseg.rx_link.sle_next
        if (cnt % 1000 == 0):
            print(" running count: {:d}".format(cnt))
    print(" total count: {:d}".format(cnt))
# EndMacro: tcp_count_rxt_segments

# Macro: tcp_walk_rxt_segments
@lldb_command('tcp_walk_rxt_segments')
def TCPWalkRxtSegments(cmd_args=None):
    """ Walk the t_rxt_segments chain
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Missing argument 0 in user function.")

    tp = kern.GetValueFromAddress(cmd_args[0], 'tcpcb *')
    rxseg = cast(tp.t_rxt_segments.slh_first, 'tcp_rxt_seg *')
    cnt = 0
    while rxseg != 0:
        cnt += 1
        rxseg = rxseg.rx_link.sle_next
        if (cnt % 1000 == 0):
            print(" running count: {:d}".format(cnt))
    print(" total count: {:d}".format(cnt))
    rxseg = cast(tp.t_rxt_segments.slh_first, 'tcp_rxt_seg *')
    cnt = 0
    while rxseg != 0:
        cnt += 1
        out_string = ""
        span = rxseg.rx_end - rxseg.rx_start
        rxseg_format = "{0:4d} 0x{1:x} rx_start 0x{2:x} rx_end 0x{3:x} rx_count {4:4d} rx_flags 0x{5:x} span {6:d}"
        out_string += rxseg_format.format(cnt, rxseg, rxseg.rx_start, rxseg.rx_end, rxseg.rx_count, rxseg.rx_flags, abs(span))
        print(out_string)
        rxseg = rxseg.rx_link.sle_next
# EndMacro: tcp_walk_rxt_segments

def GetTCPTimerAsString(value):
    """ Return a formatted string description of the timer index
    """
    index = unsigned(value)
    if index <= TCPT_MAX:
        out_string = tcp_timer_strings[index]
    else:
        out_string = printf("<{d}>".format(value))
    return out_string

# Macro: tcp_walk_timer_list
@lldb_command('tcp_walk_timer_list', 'V')
def TCPWalkTimerList(cmd_args=None, cmd_options={}):
    """ Walk the list of tcptimerentry from tcp_timer_list lhead field
        Usage: tcp_walk_timer_list [-V]
                -V show detail of the TCP control block
    """
    verbose = False
    if "-V" in cmd_options:
        verbose = True

    field_offset = getfieldoffset("struct tcpcb", "tentry.te_le.le_next")

    timer_list = addressof(kern.globals.tcp_timer_list)

    timer_entry = Cast(timer_list.lhead.lh_first, 'tcptimerentry *')
    cnt = 0

    print("Walking entries of tcp_timer_list at 0x{:x}".format(unsigned(timer_list)))

    timer_header_format = "{0:6s} {1:>18s} {2:>12s} {3:>14s} {4:>6s} {5:>12s} {6:>18s} {7:>18s} {8:>18s}"
    out_string = timer_header_format.format("Entry#", "(tcptimerentry *)", "timer_start", "index", "mode", "runtime", "le_next", "(tcpcb *)", "(inpcb *)")
    print(out_string)

    while timer_entry != 0:
        cnt += 1
        next_entry = timer_entry.te_le.le_next
        tp = Cast(kern.GetValueFromAddress(Cast(timer_entry, 'char *') - field_offset), 'tcpcb *')
        timer_entry_format = "{0:6d} 0x{1:<16x} {2:>12d} {3:>14s} {4:>6d} {5:>12d} 0x{6:<16x} 0x{7:<16x} 0x{8:<16x}"
        out_string = timer_entry_format.format(
            cnt,
            unsigned(timer_entry),
            unsigned(timer_entry.te_timer_start),
            GetTCPTimerAsString(timer_entry.te_index),
            unsigned(timer_entry.te_mode),
            unsigned(timer_entry.te_runtime),
            unsigned(next_entry) if next_entry else 0,
            unsigned(tp),
            unsigned(tp.t_inpcb)
        )
        print(out_string)

        if verbose:
            print(GetInPcb(tp.t_inpcb, IPPROTO_TCP))

        timer_entry = Cast(next_entry, 'tcptimerentry *')

        # Safety check to prevent infinite loops
        if cnt > 10000:
            print("Warning: Stopped after 10000 entries to prevent infinite loop")
            break

    print("Total timer entries: {:d}".format(cnt))
# EndMacro: tcp_walk_timer_list

def ShowBPFDevice(i, bpf_d):
    out_string = ""
    if bpf_d != 0:
        bd_sbuf = cast(bpf_d.bd_sbuf, 'char *')
        bd_hbuf = cast(bpf_d.bd_hbuf, 'char *')
        ifname = ""
        bd_bif = cast(bpf_d.bd_bif, 'struct bpf_if *')
        if bd_bif != 0:
            bif_ifp = cast(bd_bif.bif_ifp, 'struct ifnet *')
            if bif_ifp != 0:
                ifname = bif_ifp.if_xname
        format_string = "bpf{0:<3d} (struct bpf_d *)0x{1:16x} {2:7d} 0x{3:<16x} {4:7d} 0x{5:<16x} {6:16s}"
        out_string += format_string.format(i, bpf_d, bpf_d.bd_slen, bd_sbuf, bpf_d.bd_hlen, bd_hbuf, ifname)
    return out_string

# Macro: show_bpf_devices
@lldb_command('show_bpf_devices')
def ShowBPFDevices(cmd_args=None):
    """ Walk the bpf device array
    """
    format_string = "{0:6s} {1:34s} {2:>7s} {3:18s} {4:>7s} {5:18s} {6:16s}"
    out_string = format_string.format("device", "address", "bd_slen", "bd_sbuf", "bd_hlen", "bd_hbuf", "bif_ifp")
    print(out_string)

    bpf_dtab_size = int(kern.globals.bpf_dtab_size)
    for i in range(0, bpf_dtab_size):
        bpf_d = cast(kern.globals.bpf_dtab[i], 'struct bpf_d *')
        if bpf_d == 0:
            continue
        out_string = ShowBPFDevice(i, bpf_d)
        print(out_string)
# EndMacro: show_bpf_devices

def DumpBPFToFile(bpf_d):
    bd_bif = cast(bpf_d.bd_bif, 'struct bpf_if *')
    if bd_bif == 0:
        print("bd_bif is NULL")
        return

    bif_ifp = Cast(bd_bif.bif_ifp, 'struct ifnet *')
    if bif_ifp == 0:
        print("bd_bif.bif_ifp is NULL")
        return

    ifname = cast(bif_ifp.if_xname, 'char *')
    print("ifname: ", ifname);

    dlt = bd_bif.bif_dlt
    if dlt == 149:
        suffix = ".pktap"
    else:
        suffix = ".bpf"

    format_string = "{0:s}-dlt-{1:d}-"
    prefix = format_string.format(ifname, dlt)

    f = tempfile.NamedTemporaryFile(prefix=prefix, suffix=suffix, dir="/tmp/", mode="wb", delete=False)

    err = lldb.SBError()

    if bpf_d.bd_hlen != 0:
        addr = bpf_d.bd_hbuf[0].GetSBValue().GetLoadAddress()
        hlen = (unsigned(bpf_d.bd_hlen)+(4-1))&~(4-1)
        if hlen != 0:
            buf = LazyTarget.GetProcess().ReadMemory(addr, hlen, err)
            if err.fail:
                print("Error, getting sbuf")
            f.write(buf)

    if bpf_d.bd_slen != 0:
        addr = bpf_d.bd_sbuf[0].GetSBValue().GetLoadAddress()
        slen = (unsigned(bpf_d.bd_slen)+(4-1))&~(4-1)
        if slen != 0:
            buf = LazyTarget.GetProcess().ReadMemory(addr, slen, err)
            if err.fail:
                print("Error, getting sbuf")
                f.write(buf)

    print(f.name)
    f.close()

# Macro: net_get_always_on_pktap
@lldb_command('save_bfp_buffers')
def SaveBPFBuffer(cmd_args=None):
    """ Dump the buffers of a BPF to a file in /tmp/
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError()

    bpf_d = kern.GetValueFromAddress(cmd_args[0], 'struct bpf_d *')

    DumpBPFToFile(bpf_d)

# Macro: net_get_always_on_pktap
@lldb_command('net_get_always_on_pktap')
def NetGetAlwaysOnPktap(cmd_args=None):
    """ Dump the always-on packet capture to a file in /tmp/
    """
    for i in range(0, 10):
        ifnet = GetIfConfiguration("pktap"+str(i))
        if not ifnet:
            continue
        if ifnet.if_bpf == 0:
            ifnet = None
            continue
        if ifnet.if_bpf.bif_dlist.bd_headdrop == 0:
            ifnet = None
            continue
        break

    if not ifnet:
        print("Could not find a pktap interface")
        return

    bpf_d = ifnet.if_bpf.bif_dlist

    DumpBPFToFile(bpf_d)
# EndMacro: net_get_always_on_pktap

def GetNDPrefixFlagsAsString(flags_struct):
    """ Return a formatted string description of the nd_prefix flags
    """
    out_string = ""

    # The flags_struct parameter is the struct prf_ra which contains bit fields
    # Access the bit fields directly
    if unsigned(flags_struct.onlink):
        if out_string:
            out_string += ","
        out_string += "ONLINK"

    if unsigned(flags_struct.autonomous):
        if out_string:
            out_string += ","
        out_string += "AUTONOMOUS"

    return out_string if out_string else "NONE"

def GetNDPrefixStateAsString(stateflags):
    """ Return a formatted string description of the nd_prefix state flags
    """
    out_string = ""
    state_strings = {
        0x01: "ONDEPRECATE",
        0x02: "ONVALIDATE",
        0x04: "PROCESSED",
        0x08: "EXPIRED"
    }

    for flag_bit, flag_name in state_strings.items():
        if stateflags & flag_bit:
            if out_string:
                out_string += ","
            out_string += flag_name

    return out_string if out_string else "NONE"

def ShowNDPrefix(ndpr, index):
    """ Display formatted information about an nd_prefix entry
    """
    out_string = ""

    # Basic prefix information
    prefix_addr = GetIn6AddrAsString(ndpr.ndpr_prefix.sin6_addr.__u6_addr.__u6_addr8)
    plen = unsigned(ndpr.ndpr_plen)

    # Interface information
    ifname = ""
    if ndpr.ndpr_ifp != 0:
        ifname = str(ndpr.ndpr_ifp.if_xname)

    # Format basic info
    if kern.ptrsize == 8:
        format_string = "{0:6d} {1:<18x} {2:<25s} {3:<10s} {4:<8d} {5:<20s} {6:<12s} {7:<8d}"
    else:
        format_string = "{0:6d} {1:<10x} {2:<25s} {3:<10s} {4:<8d} {5:<20s} {6:<12s} {7:<8d}"

    prefix_with_len = prefix_addr + "/" + str(plen)

    # Get flags and state
    flags_str = GetNDPrefixFlagsAsString(ndpr.ndpr_flags)
    state_str = GetNDPrefixStateAsString(unsigned(ndpr.ndpr_stateflags))

    out_string += format_string.format(
        index,
        unsigned(ndpr),
        prefix_with_len,
        ifname,
        unsigned(ndpr.ndpr_refcount),
        flags_str,
        state_str,
        int(ndpr.ndpr_addrcnt)
    )

    return out_string

# Macro: show_nd_prefixes
@lldb_command('show_nd_prefixes')
def ShowNDPrefixes(cmd_args=None):
    """ Display the IPv6 Neighbor Discovery prefix list
        Usage: show_nd_prefixes [prefix_address]
               If prefix_address is provided, show details for that specific prefix
    """
    out_string = ""

    # Header
    if kern.ptrsize == 8:
        header_format = "{0:6s} {1:<18s} {2:<25s} {3:<10s} {4:<8s} {5:<20s} {6:<12s} {7:<8s}"
        print(header_format.format("Entry", "nd_prefix *", "Prefix/Length", "Interface", "RefCount", "Flags", "State", "AddrCnt"))
        print(header_format.format("-----", "-" * 18, "-" * 25, "-" * 10, "-" * 8, "-" * 20, "-" * 12, "-" * 8))
    else:
        header_format = "{0:6s} {1:<10s} {2:<25s} {3:<10s} {4:<8s} {5:<20s} {6:<12s} {7:<8s}"
        print(header_format.format("Entry", "nd_prefix *", "Prefix/Length", "Interface", "RefCount", "Flags", "State", "AddrCnt"))
        print(header_format.format("-----", "-" * 10, "-" * 25, "-" * 10, "-" * 8, "-" * 20, "-" * 12, "-" * 8))

    # Walk the nd_prefix list
    nd_prefix_head = kern.globals.nd_prefix
    ndpr = Cast(nd_prefix_head.lh_first, 'nd_prefix *')

    index = 0
    target_addr = None

    # Check if user provided a specific prefix address to look for
    if cmd_args is not None and len(cmd_args) > 0:
        try:
            # Convert string address to integer, handling 0x prefix if present
            addr_str = cmd_args[0]
            if addr_str.startswith('0x'):
                target_addr_int = int(addr_str, 16)
            else:
                target_addr_int = int(addr_str, 16)
            target_addr = kern.GetValueFromAddress(target_addr_int, 'nd_prefix *')
        except ValueError:
            print("Invalid address format. Use hex address like 0xfffffe1984b20a00")
            return

    while ndpr != 0:
        index += 1

        # If searching for specific prefix, only show that one
        if target_addr is not None:
            if unsigned(ndpr) == target_addr_int:
                print(ShowNDPrefix(ndpr, index))
                return
        else:
            # Show all prefixes
            print(ShowNDPrefix(ndpr, index))

        # Move to next prefix using the macro expansion
        ndpr = Cast(ndpr.ndpr_entry.le_next, 'nd_prefix *')

        # Safety check to prevent infinite loops
        if index > 1000:
            print("Warning: Stopped after 1000 entries to prevent infinite loop")
            break

    if target_addr is not None:
        print("Prefix not found in list")
    else:
        print("Total prefixes: " + str(index))

# EndMacro: show_nd_prefixes