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
from xnu import *
from utils import *
from kdp import *
from core import caching
from core.pointer import NativePointer
import sys
import lldb
import os
import sys
from collections import deque

######################################
# Globals
######################################
plane = None

#####################################
# Utility functions.
#####################################
def CastIOKitClass(obj, target_type):
    """ Type cast an object to another IOKIT CPP class.
        params:
            obj - core.value  object representing some C construct in lldb
            target_type - str : ex 'OSString *'
                        - lldb.SBType :
    """
    v = obj.GetSBValue()
    # We need to do that so that LLDB doesn't try to "helpfully"
    # Guess which instance type it is...
    v.SetPreferDynamicValue(lldb.eNoDynamicValues)
    if isinstance(target_type, str):
        target_type = gettype(target_type)
    return value(v.Cast(target_type))

#####################################
# Classes.
#####################################
class PreoslogHeader(object):
    """
    Represents preoslog buffer header. There's no symbol in the kernel for it.
    """
    valid_magic = "POSL"
    def __init__(self):
        self.magic = ""
        self.offset = 0
        self.size = 0
        self.source = 0
        self.wrapped = 0
        self.data = None


class IOKitSmartPointer(NativePointer):
    """ IOKit's smart pointer

        Every smart pointer inherits from libkern::intrusive_shared_ptr.
        The real pointer is wrapped behind ptr_ member.
    """

    @classmethod
    def match(cls, sbvalue):

        # Smart pointers in IOKit are OSSharedPtr and OSTaggedSharedPtr
        name = sbvalue.GetType().GetCanonicalType().GetName()
        if name.startswith(("OSSharedPtr", "OSTaggedSharedPtr")):
            return cls()
        
        return None

    def GetPointerSBValue(self, sbvalue):
        sbv = sbvalue.GetChildMemberWithName('ptr_')
        return super().GetPointerSBValue(sbv)


######################################
# Type Summaries
######################################
@lldb_type_summary(['OSObject *'])
@header("")
def GetObjectSummary(obj):
    """ Show info about an OSObject - its vtable ptr and retain count, & more info for simple container classes.
    """
    if obj is None:
        return

    vt = dereference(Cast(obj, 'uintptr_t *')) - 2 * sizeof('uintptr_t')
    vt = kern.StripKernelPAC(vt)
    vtype = kern.SymbolicateFromAddress(vt)
    if len(vtype):
        vtype_str = " <" + vtype[0].GetName() + ">"
    else:
        vtype_str = ""
    if (retainCount := get_field(obj, 'retainCount')) is not None:
        retCount = (retainCount & 0xffff)
        cntnrRetCount = (retainCount >> 16)
        out_string = "`object 0x{0: <16x}, vt 0x{1: <16x}{2:s}, retain count {3:d}, container retain {4:d}` ".format(obj, vt, vtype_str, retCount, cntnrRetCount)
    else:
        out_string = "`object 0x{0: <16x}, vt 0x{1: <16x}{2:s}` ".format(obj, vt, vtype_str)

    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV8OSString')
    if vt == ztvAddr:
        out_string += GetString(obj)
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV8OSSymbol')
    if vt == ztvAddr:
        out_string += GetString(obj)
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV8OSNumber')
    if vt == ztvAddr:
        out_string += GetNumber(obj)
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV9OSBoolean')
    if vt == ztvAddr:
        out_string += GetBoolean(obj)
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV7OSArray')
    if vt == ztvAddr:
        out_string += "(" + GetArray(CastIOKitClass(obj, 'OSArray *')) + ")"
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV5OSSet')
    if vt == ztvAddr:
        out_string += GetSet(CastIOKitClass(obj, 'OSSet *'))
        return out_string
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV12OSDictionary')
    if vt == ztvAddr:
        out_string += GetDictionary(CastIOKitClass(obj, 'OSDictionary *'))
        return out_string
    
    return out_string


def GetObjectTypeStr(obj):
    """ Return the type of an OSObject's container class
    """
    if obj is None:
        return None

    vt = dereference(Cast(obj, 'uintptr_t *')) - 2 * sizeof('uintptr_t')
    vt = kern.StripKernelPAC(vt)
    vtype = kern.SymbolicateFromAddress(vt)
    if len(vtype):
        return vtype[0].GetName()

    # See if the value is in a kext with no symbols
    for kval in IterateLinkedList(kern.globals.kmod, 'next'):
        if vt >= unsigned(kval.address) and vt <= (unsigned(kval.address) + unsigned(kval.size)):
            return "kmod:{:s}+{:#0x}".format(kval.name, vt - unsigned(kval.address))
    return None


@lldb_type_summary(['IORegistryEntry *'])
@header("")
def GetRegistryEntrySummary(entry):
    """ returns a string containing summary information about an IORegistry
        object including it's registry id , vtable ptr and retain count
    """
    name = None
    out_string = ""
    registryTable = entry.fRegistryTable
    propertyTable = entry.fPropertyTable
    
    name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
    if name is None:
        name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
    if name is None:
        name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)
    
    if name is not None:
        out_string += "+-o {0:s}  ".format(GetString(CastIOKitClass(name, 'OSString *')))
    elif (pwrMgt := CastIOKitClass(entry, 'IOService *').pwrMgt) and (service_name := pwrMgt.Name):
        out_string += "+-o {0:s}  ".format(service_name)
    else:
        out_string += "+-o ??  "
    
    # I'm using uintptr_t for now to work around <rdar://problem/12749733> FindFirstType & Co. should allow you to make pointer types directly
    vtableAddr = dereference(Cast(entry, 'uintptr_t *')) - 2 * sizeof('uintptr_t *')
    vtableAddr = kern.StripKernelPAC(vtableAddr)
    vtype = kern.SymbolicateFromAddress(vtableAddr)
    if vtype is None or len(vtype) < 1:
        out_string += "<object 0x{0: <16x}, id 0x{1:x}, vtable 0x{2: <16x}".format(entry, CastIOKitClass(entry, 'IORegistryEntry *').reserved.fRegistryEntryID, vtableAddr)
    else:
        out_string += "<object 0x{0: <16x}, id 0x{1:x}, vtable 0x{2: <16x} <{3:s}>".format(entry, CastIOKitClass(entry, 'IORegistryEntry *').reserved.fRegistryEntryID,
                                                                                           vtableAddr, vtype[0].GetName())
    
    ztvAddr = kern.GetLoadAddressForSymbol('_ZTV15IORegistryEntry')
    if vtableAddr != ztvAddr:
        out_string += ", "
        state = CastIOKitClass(entry, 'IOService *').__state[0]
        # kIOServiceRegisteredState
        if 0 == state & 2:
            out_string += "!"
        out_string += "registered, "
        # kIOServiceMatchedState
        if 0 == state & 4:
            out_string += "!"
        out_string += "matched, "
        #kIOServiceInactiveState
        if 0 != state & 1:
            out_string += "in"
        busyCount = (CastIOKitClass(entry, 'IOService *').__state[1] & 0xff)
        retCount = (CastIOKitClass(entry, 'IOService *').retainCount & 0xffff)
        out_string += "active, busy {0}, retain count {1}>".format(busyCount, retCount)
    return out_string

######################################
# Commands
######################################
@lldb_command('showallclasses')
def ShowAllClasses(cmd_args=None):
    """ Show the instance counts and ivar size of all OSObject subclasses.
        See ioclasscount man page for details
    """
    idx = 0
    count = unsigned(kern.globals.sAllClassesDict.count)
    
    while idx < count:
        meta = CastIOKitClass(kern.globals.sAllClassesDict.dictionary[idx].value, 'OSMetaClass *')
        idx += 1
        print(GetMetaClass(meta))

@lldb_command('showobject')
def ShowObject(cmd_args=None):
    """ Show info about an OSObject - its vtable ptr and retain count, & more info for simple container classes.
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the address of the OSObject whose info you want to view. Type help showobject for help")
        return
    
    obj = kern.GetValueFromAddress(cmd_args[0], 'OSObject *')
    print(GetObjectSummary(obj))

#Macro: dumpobject
@lldb_command('dumpobject')
def DumpObject(cmd_args=None):
    """ Dumps object information if it is a valid object confirmed by showobject
        Usage: dumpobject <address of object to be dumped> [class/struct type of object]
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("No arguments passed")
        return False

    if len(cmd_args) == 1:
        try:
            object_info = lldb_run_command("showobject {:s}".format(cmd_args[0]))
        except:
            print("Error!! showobject failed due to invalid value")
            print(DumpObject.__doc__)
            return False

        srch = re.search(r'<vtable for ([A-Za-z][^>]*)>', object_info)
        if not srch:
            print("Error!! Couldn't find object in registry, input type manually as 2nd argument")
            print(DumpObject.__doc__)
            return False

        object_type = srch.group(1)
    else:
        type_lookup = lldb_run_command("image lookup -t {:s}".format(cmd_args[1]))
        if type_lookup.find(cmd_args[1])!= -1:
            object_type = cmd_args[1]
        else:
            print("Error!! Input type {:s} isn't available in image lookup".format(cmd_args[1]))
            return False

    print("******** Object Dump for value \'{:s}\' with type \"{:s}\" ********".format(cmd_args[0], object_type))
    print(lldb_run_command("p/x *({:s}*){:s}".format(object_type, cmd_args[0])))

#EndMacro: dumpobject

@lldb_command('setregistryplane')
def SetRegistryPlane(cmd_args=None):
    """ Set the plane to be used for the IOKit registry macros
        syntax: (lldb) setregistryplane 0  - will display all known planes
        syntax: (lldb) setregistryplane 0xaddr      - will set the registry plane to 0xaddr
        syntax: (lldb) setregistryplane gIODTPlane  - will set the registry plane to gIODTPlane
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the name of the plane you want to use with the IOKit registry macros.")
    
    if cmd_args[0] == "0":
        print(GetObjectSummary(kern.globals.gIORegistryPlanes))
    else:
        global plane
        plane = kern.GetValueFromAddress(cmd_args[0], 'IORegistryPlane *')
    return

@lldb_command('showregistryentry')
def ShowRegistryEntry(cmd_args=None):
    """ Show info about a registry entry; its properties and descendants in the current plane
        syntax: (lldb) showregistryentry 0xaddr
        syntax: (lldb) showregistryentry gIOPMRootDomain
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the address of the registry entry whose info you want to view.")
        return
    
    entry = kern.GetValueFromAddress(cmd_args[0], 'IORegistryEntry *')
    ShowRegistryEntryRecurse(entry, "", True)

@lldb_command('showregistry')
def ShowRegistry(cmd_args=None):
    """ Show info about all registry entries in the current plane
        If prior to invoking this command no registry plane is specified
        using 'setregistryplane', the command defaults to the IOService plane
    """
    ShowRegistryEntryRecurse(kern.globals.gRegistryRoot, "", False)

@lldb_command('showregistryprops')
def ShowRegistryProps(cmd_args=None):
    """ Show info about all registry entries in the current plane, and their properties
        If prior to invoking this command no registry plane is specified
        using 'setregistryplane', the command defaults to the IOService plane
    """
    ShowRegistryEntryRecurse(kern.globals.gRegistryRoot, "", True)

@lldb_command('findregistryentry')
def FindRegistryEntry(cmd_args=None):
    """ Search for registry entry that matches the given string
        If prior to invoking this command no registry plane is specified
        using 'setregistryplane', the command defaults to searching entries from the IOService plane
        syntax: (lldb) findregistryentries AppleACPICPU - will find the first registry entry that matches AppleACPICPU
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the name of the registry entry you want to find")
        
    FindRegistryEntryRecurse(kern.globals.gRegistryRoot, cmd_args[0], True)

@lldb_command('findregistryentries')
def FindRegistryEntries(cmd_args=None):
    """ Search for all registry entries that match the given string
        If prior to invoking this command no registry plane is specified
        using 'setregistryplane', the command defaults to searching entries from the IOService plane
        syntax: (lldb) findregistryentries AppleACPICPU - will find all registry entries that match AppleACPICPU
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the name of the registry entry/entries you want to find")
    
    FindRegistryEntryRecurse(kern.globals.gRegistryRoot, cmd_args[0], False)

@lldb_command('findregistryprop')
def FindRegistryProp(cmd_args=None):
    """ Given a registry entry, print out the contents for the property that matches
        a specific string
        syntax: (lldb) findregistryprop 0xaddr IOSleepSupported
        syntax: (lldb) findregistryprop gIOPMRootDomain IOSleepSupported
        syntax: (lldb) findregistryprop gIOPMRootDomain "Supported Features"
    """
    if cmd_args is None or len(cmd_args) < 2:
        raise ArgumentError("Please specify the address of a IORegistry entry and the property you're looking for")
    
    entry = kern.GetValueFromAddress(cmd_args[0], 'IOService *')
    propertyTable = entry.fPropertyTable
    print(GetObjectSummary(LookupKeyInPropTable(propertyTable, cmd_args[1])))

@lldb_command('showuserserver')
def ShowUserServer(cmd_args=None):
    """ Show info about an IOUserServer object
        syntax: (lldb) showuserserver 0xaddr
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the address of the IOUserServer object whose info you want to view.")
        return
    ShowUserServerSummary(cmd_args[0])

@lldb_command('readioport8')
def ReadIOPort8(cmd_args=None):
    """ Read value stored in the specified IO port. The CPU can be optionally
        specified as well.
        Prints 0xBAD10AD in case of a bad read
        Syntax: (lldb) readioport8 <port> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify a port to read out of")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    if len(cmd_args) >= 2:
        lcpu = ArgumentStringToInt(cmd_args[1])
    else:
        lcpu = xnudefines.lcpu_self
            
    ReadIOPortInt(portAddr, 1, lcpu)

@lldb_command('readioport16')
def ReadIOPort16(cmd_args=None):
    """ Read value stored in the specified IO port. The CPU can be optionally
        specified as well.
        Prints 0xBAD10AD in case of a bad read
        Syntax: (lldb) readioport16 <port> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify a port to read out of")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    if len(cmd_args) >= 2:
        lcpu = ArgumentStringToInt(cmd_args[1])
    else:
        lcpu = xnudefines.lcpu_self
    
    ReadIOPortInt(portAddr, 2, lcpu)

@lldb_command('readioport32')
def ReadIOPort32(cmd_args=None):
    """ Read value stored in the specified IO port. The CPU can be optionally
        specified as well.
        Prints 0xBAD10AD in case of a bad read
        Syntax: (lldb) readioport32 <port> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify a port to read out of")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    if len(cmd_args) >= 2:
        lcpu = ArgumentStringToInt(cmd_args[1])
    else:
        lcpu = xnudefines.lcpu_self
    
    ReadIOPortInt(portAddr, 4, lcpu)

@lldb_command('writeioport8')
def WriteIOPort8(cmd_args=None):
    """ Write the value to the specified IO port. The size of the value is
        determined by the name of the command. The CPU used can be optionally
        specified as well.
        Syntax: (lldb) writeioport8 <port> <value> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) < 2:
        raise ArgumentError("Please specify a port to write to, followed by the value you want to write")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    value = ArgumentStringToInt(cmd_args[1])
    
    if len(cmd_args) >= 3:
        lcpu = ArgumentStringToInt(cmd_args[2])
    else:
        lcpu = xnudefines.lcpu_self
    
    WriteIOPortInt(portAddr, 1, value, lcpu)

@lldb_command('writeioport16')
def WriteIOPort16(cmd_args=None):
    """ Write the value to the specified IO port. The size of the value is
        determined by the name of the command. The CPU used can be optionally
        specified as well.
        Syntax: (lldb) writeioport16 <port> <value> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) < 2:
        raise ArgumentError("Please specify a port to write to, followed by the value you want to write")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    value = ArgumentStringToInt(cmd_args[1])
    
    if len(cmd_args) >= 3:
        lcpu = ArgumentStringToInt(cmd_args[2])
    else:
        lcpu = xnudefines.lcpu_self
    
    WriteIOPortInt(portAddr, 2, value, lcpu)

@lldb_command('writeioport32')
def WriteIOPort32(cmd_args=None):
    """ Write the value to the specified IO port. The size of the value is
        determined by the name of the command. The CPU used can be optionally
        specified as well.
        Syntax: (lldb) writeioport32 <port> <value> [lcpu (kernel's numbering convention)]
    """
    if cmd_args is None or len(cmd_args) < 2:
        raise ArgumentError("Please specify a port to write to, followed by the value you want to write")
    
    portAddr = ArgumentStringToInt(cmd_args[0])
    value = ArgumentStringToInt(cmd_args[1])
    
    if len(cmd_args) >= 3:
        lcpu = ArgumentStringToInt(cmd_args[2])
    else:
        lcpu = xnudefines.lcpu_self
    
    WriteIOPortInt(portAddr, 4, value, lcpu)

@lldb_command('showioservicepm')
def ShowIOServicePM(cmd_args=None):
    """ Routine to dump the IOServicePM object
        Syntax: (lldb) showioservicepm <IOServicePM pointer>
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please enter the pointer to the IOServicePM object you'd like to introspect")
    
    iopmpriv = kern.GetValueFromAddress(cmd_args[0], 'IOServicePM *')
    out_string = "MachineState {0: <6d} (".format(iopmpriv.MachineState)
    
    # Power state map
    pstate_map = {
            0:  'kIOPM_Finished',
            1:  'kIOPM_OurChangeTellClientsPowerDown',
            2:  'kIOPM_OurChangeTellClientsPowerDown',
            3:  'kIOPM_OurChangeNotifyInterestedDriversWillChange',
            4:  'kIOPM_OurChangeSetPowerState',
            5:  'kIOPM_OurChangeWaitForPowerSettle',
            6:  'kIOPM_OurChangeNotifyInterestedDriversDidChange',
            7:  'kIOPM_OurChangeTellCapabilityDidChange',
            8:  'kIOPM_OurChangeFinish',
            9:  'Unused_MachineState_9',
            10: 'kIOPM_ParentChangeTellPriorityClientsPowerDown',
            11: 'kIOPM_ParentChangeNotifyInterestedDriversWillChange',
            12: 'kIOPM_ParentChangeSetPowerState',
            13: 'kIOPM_ParentChangeWaitForPowerSettle',
            14: 'kIOPM_ParentChangeNotifyInterestedDriversDidChange',
            15: 'kIOPM_ParentChangeTellCapabilityDidChange',
            16: 'kIOPM_ParentChangeAcknowledgePowerChange',
            17: 'kIOPM_NotifyChildrenStart',
            18: 'kIOPM_NotifyChildrenOrdered',
            19: 'kIOPM_NotifyChildrenDelayed',
            20: 'kIOPM_SyncTellClientsPowerDown',
            21: 'kIOPM_SyncTellPriorityClientsPowerDown',
            22: 'kIOPM_SyncNotifyWillChange',
            23: 'kIOPM_SyncNotifyDidChange',
            24: 'kIOPM_SyncTellCapabilityDidChange',
            25: 'kIOPM_SyncFinish',
            26: 'kIOPM_TellCapabilityChangeDone',
            27: 'kIOPM_DriverThreadCallDone'
        }
    powerstate = unsigned(iopmpriv.MachineState)
    if powerstate in pstate_map:
        out_string += "{0:s}".format(pstate_map[powerstate])
    else:
        out_string += "Unknown_MachineState"
    out_string += "), "
    
    if iopmpriv.MachineState != 20:
        if hasattr(iopmpriv, "SettleTimeUS"):
            out_string += "DriverTimer = {0: <6d}, SettleTime = {1: < 6d}, HeadNoteFlags = {2: #12x}, HeadNotePendingAcks = {3: #012x}, ".format(
                    unsigned(iopmpriv.DriverTimer),
                    unsigned(iopmpriv.SettleTimeUS),
                    unsigned(iopmpriv.HeadNoteChangeFlags),
                    unsigned(iopmpriv.HeadNotePendingAcks))
        else:
            out_string += "DriverTimer = {0: <6d}, HeadNoteFlags = {1: #12x}, HeadNotePendingAcks = {2: #012x}, ".format(
                    unsigned(iopmpriv.DriverTimer),
                    unsigned(iopmpriv.HeadNoteChangeFlags),
                    unsigned(iopmpriv.HeadNotePendingAcks))
    
    if iopmpriv.DeviceOverrideEnabled != 0:
        out_string += "DeviceOverrides, "
    
    out_string += "DeviceDesire = {0: <6d}, DesiredPowerState = {1: <6d}, PreviousRequest = {2: <6d}\n".format(
            unsigned(iopmpriv.DeviceDesire),
            unsigned(iopmpriv.DesiredPowerState),
            unsigned(iopmpriv.PreviousRequestPowerFlags))
    
    print(out_string)

@lldb_type_summary(['IOPMWorkQueue *'])
@header("")
def GetIOPMWorkQueueSummary(wq):
    out_str = ""
    ioservicepm_header = "{:<20s}{:<4s}{:<4s}{:<4s}{:<4s}\n"
    iopmrequest_indent = "    "
    iopmrequest_header = iopmrequest_indent + "{:<20s}{:<6s}{:<20s}{:<20s}{:<12s}{:<12s}{:<20s}{:<20s}{:<20s}\n"
    head = kern.StripKernelPAC(addressof(wq.fWorkQueue))
    head = kern.GetValueFromAddress(head, 'queue_head_t *')

    for next in IterateQueue(head, 'IOServicePM *', 'WorkChain'):
        out_str += ioservicepm_header.format("IOService", "ps", "ms", "wr", "name")
        out_str += "0x{:<16x}  {:<2d}  {:<2d}  {:<2d}  {:<s}\n".format(
            next.Owner, next.CurrentPowerState, next.MachineState, next.WaitReason, next.Name)
        out_str += iopmrequest_header.format("IOPMRequest", "type", "next_req", "root_req", "work_wait", "free_wait", "arg0", "arg1", "arg2")
        next_head = kern.StripKernelPAC(addressof(next.RequestHead))
        next_head = kern.GetValueFromAddress(next_head, 'queue_head_t *')
        for request in IterateQueue(next_head, 'IOPMRequest *', 'fCommandChain'):
            out_str += iopmrequest_indent
            out_str += "0x{:<16x}  0x{:<2x}  0x{:<16x}  0x{:<16x}".format(
                request, request.fRequestType, request.fRequestNext, request.fRequestRoot)
            out_str += "  0x{:<8x}  0x{:<8x}".format(
                request.fWorkWaitCount, request.fFreeWaitCount)
            out_str += "  0x{:<16x}  0x{:<16x}  0x{:<16x}\n".format(
                request.fArg0, request.fArg1, request.fArg2)
    return out_str

@lldb_command('showiopmqueues')
def ShowIOPMQueues(cmd_args=None):
    """ Show IOKit power management queues and IOPMRequest objects.
    """
    print("IOPMWorkQueue 0x{:<16x} ({:<d} IOServicePM)\n".format(
        kern.globals.gIOPMWorkQueue, kern.globals.gIOPMWorkQueue.fQueueLength))
    print(GetIOPMWorkQueueSummary(kern.globals.gIOPMWorkQueue))

@lldb_command('showiouserserverpm')
def ShowIOUserServerPM(cmd_args=None):
    """ Show pending power requests managed by IOUserServer instances.
    """
    pendingServers = kern.globals.fUserServersWait
    count = int(pendingServers.count)
    if count == 0:
        print("No user servers with pending power request found")
        return
    for idx in range(count):
        server = CastIOKitClass(pendingServers.array[idx], "IOUserServer *")
        print(f"IOUserServer: {hex(server)}")
        services = server.fServices
        serviceCount = services.count
        services = services.array
        for serviceIdx in range(serviceCount):
            service = CastIOKitClass(services[serviceIdx], "IOService *")
            uvars = service.reserved.uvars
            powerState = uvars.powerState
            pmPending = int(powerState)
            if pmPending == 0:
                continue
            # blatantly copied from GetRegistryEntrySummary
            name = None
            registryTable = service.fRegistryTable
            propertyTable = service.fPropertyTable
            name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
            if name is None:
                name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
            if name is None:
                name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)
            name = GetString(CastIOKitClass(name, 'OSString *'))
            print(f"{name}: {hex(service)}")
        print("")

@lldb_type_summary(['IOService *'])
@header("")
def GetIOPMInterest(service):
    iopm = CastIOKitClass(service.pwrMgt, 'IOServicePM *')
    if unsigned(iopm) == 0:
        raise ArgumentError("error: no IOServicePM")
        return

    list = CastIOKitClass(iopm.InterestedDrivers, 'IOPMinformeeList *')
    out_str = "IOServicePM 0x{:<16x} ({:<d} interest, {:<d} pending ack)\n".format(
        iopm, list.length, iopm.HeadNotePendingAcks)
    if list.length == 0:
        return

    out_str += "    {:<20s}{:<8s}{:<10s}{:<20s}{:<20s}{:<20s}{:<s}\n".format(
        "informee", "active", "ticks", "notifyTime", "service", "regId", "name")
    next = CastIOKitClass(list.firstItem, 'IOPMinformee *')
    while unsigned(next) != 0:
        driver = CastIOKitClass(next.whatObject, 'IOService *')
        name = GetRegistryEntryName(driver)
        reg_id = CastIOKitClass(driver, 'IORegistryEntry *').reserved.fRegistryEntryID;
        out_str += "    0x{:<16x}  {:<6s}  {:<8d}  0x{:<16x}  0x{:<16x}  0x{:<16x}  {:<s}\n".format(
            next, "Yes" if next.active != 0 else "No" , next.timer, next.startTime, next.whatObject, reg_id, name)
        next = CastIOKitClass(next.nextInList, 'IOPMinformee *')
    return out_str

@lldb_command('showiopminterest')
def ShowIOPMInterest(cmd_args=None):
    """ Show the interested drivers for an IOService.
        syntax: (lldb) showiopminterest <IOService>
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the address of the IOService")

    obj = kern.GetValueFromAddress(cmd_args[0], 'IOService *')
    print(GetIOPMInterest(obj))

@lldb_command("showinterruptvectors")
def ShowInterruptVectorInfo(cmd_args=None):
    """
    Shows interrupt vectors.
    """

    # Constants
    kInterruptTriggerModeMask  = 0x01
    kInterruptTriggerModeEdge  = 0x00
    kInterruptTriggerModeLevel = kInterruptTriggerModeMask
    kInterruptPolarityMask     = 0x02
    kInterruptPolarityHigh     = 0x00
    kInterruptPolarityLow      = kInterruptPolarityMask
    kInterruptShareableMask    = 0x04
    kInterruptNotShareable     = 0x00
    kInterruptIsShareable      = kInterruptShareableMask
    kIOInterruptTypePCIMessaged = 0x00010000

    # Get all interrupt controllers
    interrupt_controllers = list(SearchInterruptControllerDrivers())

    print("Interrupt controllers: ")
    for ic in interrupt_controllers:
        print("  {}".format(ic))
    print("")

    # Iterate over all entries in the registry
    for entry in GetMatchingEntries(lambda _: True):
        # Get the name of the entry
        entry_name = GetRegistryEntryName(entry)

        # Get the location of the entry
        entry_location = GetRegistryEntryLocationInPlane(entry, kern.globals.gIOServicePlane)
        if entry_location is None:
            entry_location = ""
        else:
            entry_location = "@" + entry_location

        # Get the interrupt properties
        (msi_mode, vectorDataList, vectorContList) = GetRegistryEntryInterruptProperties(entry)
        should_print = False
        out_str = ""
        for (vector_data, vector_cont) in zip(vectorDataList, vectorContList):
            # vector_cont is the name of the interrupt controller. Find the matching controller from
            # the list of controllers obtained earlier
            matching_ics = [ic for ic in interrupt_controllers if ic.name == vector_cont]

            if len(matching_ics) > 0:
                should_print = True
                # Take the first match
                matchingIC = matching_ics[0]

                # Use the vector_data to determine the vector and any flags
                data_ptr = vector_data.data
                data_length = vector_data.length

                # Dereference vector_data as a uint32_t * and add the base vector number
                gsi = unsigned(dereference(Cast(data_ptr, 'uint32_t *')))
                gsi += matchingIC.base_vector_number

                # If data_length is >= 8 then vector_data contains interrupt flags
                if data_length >= 8:
                    # Add sizeof(uint32_t) to data_ptr to get the flags pointer
                    flags_ptr = kern.GetValueFromAddress(unsigned(data_ptr) + sizeof("uint32_t"))
                    flags = unsigned(dereference(Cast(flags_ptr, 'uint32_t *')))
                    out_str += "  +----- [Interrupt Controller {ic}] vector {gsi}, {trigger_level}, {active}, {shareable}{messaged}\n" \
                            .format(ic=matchingIC.name, gsi=hex(gsi), 
                                    trigger_level="level trigger" if flags & kInterruptTriggerModeLevel else "edge trigger",
                                    active="active low" if flags & kInterruptPolarityLow else "active high",
                                    shareable="shareable" if flags & kInterruptIsShareable else "exclusive",
                                    messaged=", messaged" if flags & kIOInterruptTypePCIMessaged else "")
                else:
                    out_str += "  +----- [Interrupt Controller {ic}] vector {gsi}\n".format(ic=matchingIC.name, gsi=hex(gsi))
        if should_print:
            print("[ {entry_name}{entry_location} ]{msi_mode}\n{out_str}" \
                .format(entry_name=entry_name,
                        entry_location=entry_location,
                        msi_mode=" - MSIs enabled" if msi_mode else "",
                        out_str=out_str))

@lldb_command("showiokitclasshierarchy")
def ShowIOKitClassHierarchy(cmd_args=None):
    """
    Show class hierarchy for a IOKit class
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Usage: showiokitclasshierarchy <IOKit class name>")

    class_name = cmd_args[0]
    metaclasses = GetMetaClasses()
    if class_name not in metaclasses:
        print("Class {} does not exist".format(class_name))
        return
    metaclass = metaclasses[class_name]

    # loop over superclasses
    hierarchy = []
    current_metaclass = metaclass
    while current_metaclass is not None:
        hierarchy.insert(0, current_metaclass)
        current_metaclass = current_metaclass.superclass()

    for (index, mc) in enumerate(hierarchy):
        indent = ("    " * index) + "+---"
        print("{}[ {} ] {}".format(indent, str(mc.className()), str(mc.data())))


######################################
#  Helper routines
######################################
def ShowRegistryEntryRecurse(entry, prefix, printProps):
    """ prints registry entry summary and recurses through all its children.
    """
    # Setup
    global plane
    out_string = ""
    plen = (len(prefix)//2)
    registryTable = entry.fRegistryTable
    propertyTable = entry.fPropertyTable
    
    # Print entry details
    print("{0:s}{1:s}".format(prefix, GetRegistryEntrySummary(entry)))
    # Printing large property tables make it look like lldb is 'stuck'
    if printProps:
        print(GetRegDictionary(propertyTable, prefix + "  | "))
    
    # Recurse
    if plane is None:
        childKey = kern.globals.gIOServicePlane.keys[1]
    else:
        childKey = plane.keys[1]
    childArray = LookupKeyInOSDict(registryTable, childKey)
    if childArray is not None:
        idx = 0
        ca = CastIOKitClass(childArray, 'OSArray *')
        count = unsigned(ca.count)
        array = ca.array
        while idx < count:
            if plen != 0 and plen != 1 and (plen & (plen - 1)) == 0:
                ShowRegistryEntryRecurse(CastIOKitClass(array[idx], 'IORegistryEntry *'), prefix + "| ", printProps)
            else:
                ShowRegistryEntryRecurse(CastIOKitClass(array[idx], 'IORegistryEntry *'), prefix + "  ", printProps)
            idx += 1

def FindRegistryEntryRecurse(entry, search_name, stopAfterFirst):
    """ Checks if given registry entry's name matches the search_name we're looking for
        If yes, it prints the entry's summary and then recurses through its children
        If no, it does nothing and recurses through its children
    """
    # Setup
    global plane
    registryTable = entry.fRegistryTable
    propertyTable = entry.fPropertyTable
    
    # Compare
    name = None
    name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
    if name is None:
        name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
    if name is None:
        name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)
    
    if name is not None:
        if str(CastIOKitClass(name, 'OSString *').string) == search_name:
            print(GetRegistryEntrySummary(entry))
            if stopAfterFirst is True:
                return True
    elif (pwrMgt := CastIOKitClass(entry, 'IOService *').pwrMgt) and (name := pwrMgt.Name):
        if str(name) == search_name:
            print(GetRegistryEntrySummary(entry))
            if stopAfterFirst is True:
                return True
    
    # Recurse
    if plane is None:
        childKey = kern.globals.gIOServicePlane.keys[1]
    else:
        childKey = plane.keys[1]
    childArray = LookupKeyInOSDict(registryTable, childKey)
    if childArray is not None:
        idx = 0
        ca = CastIOKitClass(childArray, 'OSArray *')
        array = ca.array
        count = unsigned(ca.count)
        while idx < count:
            if FindRegistryEntryRecurse(CastIOKitClass(array[idx], 'IORegistryEntry *'), search_name, stopAfterFirst) is True:
                return True
            idx += 1
    return False

def FindRegistryObjectRecurse(entry, search_name):
    """ Checks if given registry entry's name matches the search_name we're looking for
        If yes, return the entry
        If no, it does nothing and recurses through its children
        Implicitly stops after finding the first entry
    """
    # Setup
    global plane
    registryTable = entry.fRegistryTable
    propertyTable = entry.fPropertyTable

    # Compare
    name = None
    name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
    if name is None:
        name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
    if name is None:
        name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)
    
    if name is not None:
        if str(CastIOKitClass(name, 'OSString *').string) == search_name:
            return entry
    elif (pwrMgt := CastIOKitClass(entry, 'IOService *').pwrMgt) and (name := pwrMgt.Name):
        if str(name) == search_name:
            return entry
    
    # Recurse
    if plane is None:
        childKey = kern.globals.gIOServicePlane.keys[1]
    else:
        childKey = plane.keys[1]
    childArray = LookupKeyInOSDict(registryTable, childKey)
    if childArray is not None:
        ca = CastIOKitClass(childArray, 'OSArray *')
        array = ca.array
        for idx in range(ca.count):
            registry_object = FindRegistryObjectRecurse(CastIOKitClass(array[idx], 'IORegistryEntry *'), search_name)
            if not registry_object or int(registry_object) == int(0):
                continue
            else:
                return registry_object
    return None

def ShowUserServiceRecursive(service, prefix, last, childServices, sortedServices):
    # blatantly copied from GetRegistryEntrySummary
    name = None
    registryTable = service.fRegistryTable
    propertyTable = service.fPropertyTable
    name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
    if name is None:
        name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
    if name is None:
        name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)
    name = GetString(CastIOKitClass(name, 'OSString *'))
    sortedServices.append((service, f"{prefix}+-o {name}"))
    if last:
        prefix += "  "
    else:
        prefix += "| "
    if int(service) not in childServices:
        return
    children = childServices[int(service)]
    if len(children) == 0:
        return
    childrenCount = len(children)
    for idx in range(childrenCount):
        ShowUserServiceRecursive(children[idx], prefix, idx == childrenCount - 1, childServices, sortedServices)

def ShowUserServerSummary(server):
    reasonStrings = {
        1: "jetsam",
        2: "signal",
        3: "codesigning",
        6: "dyld",
        9: "exec",
        23: "guard",
        25: "sandbox",
        26: "security",
        28: "PAC exception",
        30: "port space",
        34: "Rosetta"
    }
    server = kern.GetValueFromAddress(server, "IOUserServer *")
    services = server.fServices
    serviceCount = services.count
    services = services.array
    print(f"IOUserServer {hex(server)} (task {hex(server.fOwningTask)}):")
    if int(server.fTaskCrashReason) != 0:
        reasonString = "Dext crash reason: "
        if server.fTaskCrashReason.osr_namespace in reasonStrings:
            reasonString += reasonStrings[server.fTaskCrashReason.osr_namespace]
            if server.fTaskCrashReason.osr_namespace == 2:
                reasonString += f", {server.fTaskCrashReason.osr_namespace.osr_ode}"
        print(reasonString)
    # Attempt to reconstruct registry hierarchy
    childServices = {}
    for serviceIdx in range(serviceCount):
        service = CastIOKitClass(services[serviceIdx], "IOService *")
        provider = service.__provider
        if int(provider) not in childServices:
            childServices[int(provider)] = []
        childServices[int(provider)].append(service)
    rootServices = []
    for provider in childServices:
        provider = kern.GetValueFromAddress(provider, "IOService *")
        if int(provider.__provider) not in childServices:
            rootServices.append(provider)
    sortedServices = []
    for service in rootServices:
        ShowUserServiceRecursive(service, "", True, childServices, sortedServices)
    maxNameLen = -1
    minNameLen = -1
    for serviceData in sortedServices:
        currNameLen = len(serviceData[1])
        if maxNameLen < 0 or currNameLen > maxNameLen:
            maxNameLen = currNameLen
        if minNameLen < 0 or currNameLen < minNameLen:
            minNameLen = currNameLen
    nameLen = maxNameLen + 4
    print("wt: willTerminate")
    print("dt: didTerminate")
    print("sd: serverDied")
    print("it: instantiated")
    print("sr: started")
    print("sp: stopped")
    print("wp: willPower")
    print("ps: powerState")
    print("Service" + (nameLen - len("Service")) * " ", end = "")
    print("Address             wt  dt  sd  it  sr  sp  wp  ps")
    for serviceData in sortedServices:
        service = serviceData[0]
        currNameLen = len(serviceData[1])

        print(serviceData[1] + (nameLen - currNameLen) * " ", end = "")
        print(f"{hex(serviceData[0])}  ", end = "")
        if int(service.reserved) == 0 or int(service.reserved.uvars) == 0:
            print("")
            continue
        #print(f"service {hex(service)}")
        wt = service.reserved.uvars.willTerminate
        wt = "N   " if int(wt) == 0 else "Y   "
        dt = service.reserved.uvars.didTerminate
        dt = "N   " if int(dt) == 0 else "Y   "
        sd = service.reserved.uvars.serverDied
        sd = "N   " if int(sd) == 0 else "Y   "
        it = service.reserved.uvars.instantiated
        it = "N   " if int(it) == 0 else "Y   "
        sr = service.reserved.uvars.started
        sr = "N   " if int(sr) == 0 else "Y   "
        sp = service.reserved.uvars.stopped
        sp = "N   " if int(sp) == 0 else "Y   "
        wp = service.reserved.uvars.willPower
        wp = "N   " if int(wp) == 0 else "Y   "
        ps = service.reserved.uvars.powerState
        ps = "N   " if int(ps) == 0 else "Y   "
        print(wt + dt + sd + it + sr + sp + wp + ps)

def CompareStringToOSSymbol(string, os_sym):
    """
    Lexicographically compare python string to OSSymbol
    Params:
    string - python string
    os_sym - OSSymbol

    Returns:
    0 if string == os_sym
    1 if string > os_sym
    -1 if string < os_sym
    """
    os_sym_str = GetString(os_sym)
    if string > os_sym_str:
        return 1
    elif string < os_sym_str:
        return -1
    else:
        return 0

class IOKitMetaClass(object):
    """
    A class that represents a IOKit metaclass. This is used to represent the
    IOKit inheritance hierarchy.
    """

    def __init__(self, meta):
        """
        Initialize a IOKitMetaClass object.

        Args:
            meta (core.cvalue.value): A LLDB value representing a
                OSMetaClass *.
        """
        self._meta = meta
        self._superclass = None

    def data(self):
        return self._meta

    def setSuperclass(self, superclass):
        """
        Set the superclass for this metaclass.

        Args:
            superclass (core.cvalue.value): A LLDB value representing a
                OSMetaClass *.
        """
        self._superclass = superclass

    def superclass(self):
        """
        Get the superclass for this metaclass (set by the setSuperclass method).

        Returns:
            core.cvalue.value: A LLDB value representing a OSMetaClass *.
        """
        return self._superclass

    def className(self):
        """
        Get the name of the class this metaclass represents.

        Returns:
            str: The class name
        """
        return self._meta.className.string

    def inheritsFrom(self, other):
        """
        Check if the class represented by this metaclass inherits from a class
        represented by another metaclass.

        Args:
            other (IOKitMetaClass): The other metaclass

        Returns:
            bool: Returns True if this class inherits from the other class and
                False otherwise.
        """
        current = self
        while current is not None:
            if current == other:
                return True
            else:
                current = current.superclass()


def GetRegistryEntryClassName(entry):
    """
    Get the class name of a registry entry.

    Args:
        entry (core.cvalue.value): A LLDB value representing a
            IORegistryEntry *.

    Returns:
        str: The class name of the entry or None if a class name could not be
            found.
    """
    # Check using IOClass key
    result = LookupKeyInOSDict(entry.fPropertyTable, kern.globals.gIOClassKey)
    if result is not None:
        return GetString(result).replace("\"", "")
    else:
        # Use the vtable of the entry to determine the concrete type
        vt = dereference(Cast(entry, 'uintptr_t *')) - 2 * sizeof('uintptr_t')
        vt = kern.StripKernelPAC(vt)
        vtype = kern.SymbolicateFromAddress(vt)
        if len(vtype) > 0:
            vtableName = vtype[0].GetName()
            return vtableName[11:] # strip off "vtable for "
        else:
            return None


def GetRegistryEntryName(entry):
    """
    Get the name of a registry entry.

    Args:
        entry (core.cvalue.value): A LLDB value representing a
            IORegistryEntry *.

    Returns:
        str: The name of the entry or None if a name could not be found.
    """
    name = None

    # First check the IOService plane nameKey
    result = LookupKeyInOSDict(entry.fRegistryTable, kern.globals.gIOServicePlane.nameKey)
    if result is not None:
        name = GetString(result)

    # Check the global IOName key
    if name is None:
        result = LookupKeyInOSDict(entry.fRegistryTable, kern.globals.gIONameKey)
        if result is not None:
            name = GetString(result)

    # Check the IOClass key
    if name is None:
        result = LookupKeyInOSDict(entry.fPropertyTable, kern.globals.gIOClassKey)
        if result is not None:
            name = GetString(result)

    # Remove extra quotes        
    if name is not None:
        return name.replace("\"", "")
    else:
        return GetRegistryEntryClassName(entry)


def GetRegistryEntryLocationInPlane(entry, plane):
    """
    Get the registry entry location in a IOKit plane.

    Args:
        entry (core.cvalue.value): A LLDB value representing a
            IORegistryEntry *.
        plane: An IOKit plane such as kern.globals.gIOServicePlane.

    Returns:
        str: The location of the entry or None if a location could not be
            found.
    """
    # Check the plane's pathLocationKey
    sym = LookupKeyInOSDict(entry.fRegistryTable, plane.pathLocationKey)

    # Check the global IOLocation key
    if sym is None:
        sym = LookupKeyInOSDict(entry.fRegistryTable, kern.globals.gIOLocationKey)
    if sym is not None:
        return GetString(sym).replace("\"", "")
    else:
        return None


@caching.cache_dynamically
def GetMetaClasses(target=None):
    """
    Enumerate all IOKit metaclasses. Uses dynamic caching.

    Returns:
        Dict[str, IOKitMetaClass]: A dictionary mapping each metaclass name to
            a IOKitMetaClass object representing the metaclass.
    """

    # This method takes a while, so it prints a progress indicator
    print("Enumerating IOKit metaclasses: ")

    do_progress = os.isatty(sys.__stderr__.fileno())

    # Iterate over all classes present in sAllClassesDict
    count = unsigned(kern.globals.sAllClassesDict.count)
    metaclasses_by_address = {}
    for idx in range(count):
        if do_progress and idx % 10 == 0:
            sys.stderr.write("\033[K  {} metaclass found...\r".format(idx))

        # Address of metaclass
        address = kern.globals.sAllClassesDict.dictionary[idx].value

        # Create IOKitMetaClass and store in dict
        metaclasses_by_address[int(address)] = IOKitMetaClass(CastIOKitClass(kern.globals.sAllClassesDict.dictionary[idx].value, 'OSMetaClass *'))

    # At this point, each metaclass is independent of each other. We don't have superclass links set up yet.

    for address, metaclass in metaclasses_by_address.items():
        # Get the address of the superclass using the superClassLink in IOMetaClass
        superclass_address = int(metaclass.data().superClassLink)

        # Skip null superclass
        if superclass_address == 0:
            continue

        # Find the superclass object in the dict
        if superclass_address in metaclasses_by_address:
            metaclass.setSuperclass(metaclasses_by_address[superclass_address])
        else:
            print("warning: could not find superclass for {}".format(str(metaclass.data())))

    # This method returns a dictionary mapping each class name to the associated metaclass object
    metaclasses_by_name = {}
    for idx, (_, metaclass) in enumerate(metaclasses_by_address.items()):
        if do_progress and idx % 10 == 0:
            sys.stderr.write("\033[K  {} metaclass indexed...\r".format(idx))

        metaclasses_by_name[str(metaclass.className())] = metaclass

    print("  Indexed {} IOKit metaclasses.".format(count))
    return metaclasses_by_name


def GetMatchingEntries(matcher):
    """
    Iterate over the IOKit registry and find entries that match specific
        criteria.

    Args:
        matcher (function): A matching function that returns True for a match
            and False otherwise.

    Yields:
        core.cvalue.value: LLDB values that represent IORegistryEntry * for
            each registry entry found.
    """

    # Perform a BFS over the IOKit registry tree
    bfs_queue = deque()
    bfs_queue.append(kern.globals.gRegistryRoot)
    while len(bfs_queue) > 0:
        # Dequeue an entry
        entry = bfs_queue.popleft()

        # Check if entry matches
        if matcher(entry):
            yield entry

        # Find children of this entry and enqueue them
        child_array = LookupKeyInOSDict(entry.fRegistryTable, kern.globals.gIOServicePlane.keys[1])
        if child_array is not None:
            idx = 0
            ca = CastIOKitClass(child_array, 'OSArray *')
            count = unsigned(ca.count)
            while idx < count:
                bfs_queue.append(CastIOKitClass(ca.array[idx], 'IORegistryEntry *'))
                idx += 1


def FindMatchingServices(matching_name):
    """
    Finds registry entries that match the given string. Works similarly to:

    io_iterator_t iter;
    IOServiceGetMatchingServices(..., IOServiceMatching(matching_name), &iter);
    while (( io_object_t next = IOIteratorNext(iter))) { ... }

    Args:
        matching_name (str): The class name to search for.

    Yields:
        core.cvalue.value: LLDB values that represent IORegistryEntry * for
            each registry entry found.
    """

    # Check if the argument is valid
    metaclasses = GetMetaClasses()
    if matching_name not in metaclasses:
        return
    matching_metaclass = metaclasses[matching_name]

    # An entry matches if it inherits from matching_metaclass
    def matcher(entry):
        # Get the class name of the entry and the associated metaclass
        entry_name = GetRegistryEntryClassName(entry)
        if entry_name in metaclasses:
            entry_metaclass = metaclasses[entry_name]
            return entry_metaclass.inheritsFrom(matching_metaclass)
        else:
            return False
    
    # Search for entries
    for entry in GetMatchingEntries(matcher):
        yield entry


def GetRegistryEntryParent(entry, iokit_plane=None):
    """
    Gets the parent entry of a registry entry.

    Args:
        entry (core.cvalue.value): A LLDB value representing a
            IORegistryEntry *.
        iokit_plane (core.cvalue.value, optional): A LLDB value representing a
            IORegistryPlane *. By default, this method uses the IOService
            plane.

    Returns:
        core.cvalue.value: A LLDB value representing a IORegistryEntry* that
            is the parent entry of the entry argument in the specified plane.
            Returns None if no entry could be found.
    """
    kParentSetIndex = 0
    parent_key = None
    if iokit_plane is None:
        parent_key = kern.globals.gIOServicePlane.keys[kParentSetIndex]
    else:
        parent_key = plane.keys[kParentSetIndex]
    parent_array = LookupKeyInOSDict(entry.fRegistryTable, parent_key)
    parent_entry = None
    if parent_array is not None:
        idx = 0
        ca = CastIOKitClass(parent_array, 'OSArray *')
        count = unsigned(ca.count)
        if count > 0:
            parent_entry = CastIOKitClass(ca.array[0], 'IORegistryEntry *')
    return parent_entry


def GetRegistryEntryInterruptProperties(entry):
    """
    Get the interrupt properties of a registry entry.

    Args:
        entry (core.cvalue.value): A LLDB value representing a IORegistryEntry *.

    Returns:
        (bool, List[core.cvalue.value], List[str]): A tuple with the following
            fields:
                - First field (bool): Whether this entry has a non-null
                    IOPCIMSIMode.
                - Second field (List[core.cvalue.value]): A list of LLDB values
                    representing OSData *. The OSData* pointer points to
                    interrupt vector data.
                - Third field (List[str]): A list of strings representing the
                    interrupt controller names from the
                    IOInterruptControllers property.
    """
    INTERRUPT_SPECIFIERS_PROPERTY = "IOInterruptSpecifiers"
    INTERRUPT_CONTROLLERS_PROPERTY = "IOInterruptControllers"
    MSI_MODE_PROPERTY = "IOPCIMSIMode"

    # Check IOInterruptSpecifiers
    interrupt_specifiers = LookupKeyInPropTable(entry.fPropertyTable, INTERRUPT_SPECIFIERS_PROPERTY)
    if interrupt_specifiers is not None:
        interrupt_specifiers = CastIOKitClass(interrupt_specifiers, 'OSArray *')
    
    # Check IOInterruptControllers
    interrupt_controllers = LookupKeyInPropTable(entry.fPropertyTable, INTERRUPT_CONTROLLERS_PROPERTY)
    if interrupt_controllers is not None:
        interrupt_controllers = CastIOKitClass(interrupt_controllers, 'OSArray *')

    # Check MSI mode
    msi_mode = LookupKeyInPropTable(entry.fPropertyTable, MSI_MODE_PROPERTY)

    result_vector_data = []
    result_vector_cont = []
    if interrupt_specifiers is not None and interrupt_controllers is not None:
        interrupt_specifiers_array_count = unsigned(interrupt_specifiers.count)
        interrupt_controllers_array_count = unsigned(interrupt_controllers.count)
        # The array lengths should be the same
        if interrupt_specifiers_array_count == interrupt_controllers_array_count and interrupt_specifiers_array_count > 0:
            idx = 0
            while idx < interrupt_specifiers_array_count:
                # IOInterruptSpecifiers is an array of OSData *
                vector_data = CastIOKitClass(interrupt_specifiers.array[idx], "OSData *")

                # IOInterruptControllers is an array of OSString *
                vector_cont = GetString(interrupt_controllers.array[idx])

                result_vector_data.append(vector_data)
                result_vector_cont.append(vector_cont)
                idx += 1
    
    return (msi_mode is not None, result_vector_data, result_vector_cont)


class InterruptControllerDevice(object):
    """Represents a IOInterruptController"""

    def __init__(self, device, driver, base_vector_number, name):
        """
        Initialize a InterruptControllerDevice.

        Args:
            device (core.cvalue.value): The device object.
            driver (core.cvalue.value): The driver object.
            base_vector_number (int): The base interrupt vector.
            name (str): The name of this interrupt controller.

        Note:
            Use the factory method makeInterruptControllerDevice to validate
            properties.
        """
        self.device = device
        self.driver = driver
        self.name = name
        self.base_vector_number = base_vector_number


    def __str__(self):
        """
        String representation of this InterruptControllerDevice.
        """
        return " Name {}, base vector = {}, device = {}, driver = {}".format(
            self.name, hex(self.base_vector_number), str(self.device), str(self.driver))

    @staticmethod
    def makeInterruptControllerDevice(device, driver):
        """
        Factory method to create a InterruptControllerDevice.

        Args:
            device (core.cvalue.value): The device object.
            driver (core.cvalue.value): The driver object.

        Returns:
            InterruptControllerDevice: Returns an instance of
                InterruptControllerDevice or None if the arguments do not have
                the required properties.
        """
        BASE_VECTOR_PROPERTY = "Base Vector Number"
        INTERRUPT_CONTROLLER_NAME_PROPERTY = "InterruptControllerName"
        base_vector = LookupKeyInPropTable(device.fPropertyTable, BASE_VECTOR_PROPERTY)
        if base_vector is None:
            base_vector = LookupKeyInPropTable(driver.fPropertyTable, BASE_VECTOR_PROPERTY)
        device_name = LookupKeyInPropTable(device.fPropertyTable, INTERRUPT_CONTROLLER_NAME_PROPERTY)
        if device_name is None:
            device_name = LookupKeyInPropTable(driver.fPropertyTable, INTERRUPT_CONTROLLER_NAME_PROPERTY)

        if device_name is not None:
            # Some interrupt controllers do not have a base vector number. Assume it is 0.
            base_vector_number = 0
            if base_vector is not None:
                base_vector_number = unsigned(GetNumber(base_vector))
            device_name = GetString(device_name)
            # Construct object and return
            return InterruptControllerDevice(device, driver, base_vector_number, device_name)
        else:
            # error case
            return None


def SearchInterruptControllerDrivers():
    """
    Search the IOKit registry for entries that match IOInterruptController.

    Yields:
        core.cvalue.value: A LLDB value representing a IORegistryEntry * that
        inherits from IOInterruptController.
    """
    for entry in FindMatchingServices("IOInterruptController"):
        # Get parent
        parent = GetRegistryEntryParent(entry)

        # Make the interrupt controller object
        ic = InterruptControllerDevice.makeInterruptControllerDevice(parent, entry)

        # Yield object
        if ic is not None:
            yield ic


def LookupKeyInOSDict(osdict, key, comparer = None):
    """ Returns the value corresponding to a given key in a OSDictionary
        Returns None if the key was not found
    """
    if not osdict:
        return
    count = unsigned(osdict.count)
    result = None
    idx = 0

    dictionary = osdict.dictionary
    key_value = unsigned(key) if type(key) is value else key
    while idx < count and result is None:
        elem = dictionary[idx]
        if comparer is not None:
            if comparer(key, elem.key) == 0:
                result = elem.value
        elif key_value == unsigned(elem.key):
            result = elem.value
        idx += 1
    return result

def LookupKeyInPropTable(propertyTable, key_str):
    """ Returns the value corresponding to a given key from a registry entry's property table
        Returns None if the key was not found
        The property that is being searched for is specified as a string in key_str
    """
    if not propertyTable:
        return
    count = unsigned(propertyTable.count)
    result = None
    idx = 0
    while idx < count and result is None:
        if key_str == str(propertyTable.dictionary[idx].key.string):
            result = propertyTable.dictionary[idx].value
        idx += 1
    return result

def GetRegDictionary(osdict, prefix):
    """ Returns a specially formatted string summary of the given OSDictionary
        This is done in order to pretty-print registry property tables in showregistry
        and other macros
    """
    out_string = prefix + "{\n"
    idx = 0
    count = unsigned(osdict.count)
    
    dictionary = osdict.dictionary
    while idx < count:
        entry = dictionary[idx]
        out_string += prefix + "  " + GetObjectSummary(entry.key) + " = " + GetObjectSummary(entry.value) + "\n"
        idx += 1
    out_string += prefix + "}\n"
    return out_string

def GetString(string):
    """ Returns the python string representation of a given OSString
    """
    out_string = "{0:s}".format(CastIOKitClass(string, 'OSString *').string)
    return out_string

def GetNumber(num):
    out_string = "{0:d}".format(CastIOKitClass(num, 'OSNumber *').value)
    return out_string

def GetBoolean(b):
    """ Shows info about a given OSBoolean
    """
    out_string = ""
    if b == kern.globals.gOSBooleanFalse:
        out_string += "No"
    else:
        out_string += "Yes"
    return out_string

def GetMetaClass(mc):
    """ Shows info about a given OSSymbol
    """
    out_string = "{0: <5d}x {1: >5d} bytes {2:s}\n".format(mc.instanceCount, mc.classSize, mc.className.string)
    return out_string

def GetArray(arr):
    """ Returns a string containing info about a given OSArray
    """
    out_string = ""
    idx = 0
    count = unsigned(arr.count)
    
    array = arr.array
    while idx < count:
        obj = array[idx]
        idx += 1
        out_string += GetObjectSummary(obj)
        if idx < count:
            out_string += ","
    return out_string

def GetDictionary(d):
    """ Returns a string containing info about a given OSDictionary
    """
    if d is None:
        return ""
    out_string = "{\n"
    idx = 0
    count = unsigned(d.count)
    dictionary = d.dictionary
    while idx < count:
        entry = dictionary[idx]
        key = entry.key
        value = entry.value
        out_string += "    \"{}\" = {}\n".format(GetString(key), GetObjectSummary(value))
        idx += 1
    out_string += "}"
    return out_string

def GetSet(se):
    """ Returns a string containing info about a given OSSet
    """
    out_string = "[" + GetArray(se.members) + "]"
    return out_string

def ReadIOPortInt(addr, numbytes, lcpu):
    """ Prints results after reading a given ioport
    """
    result = 0xBAD10AD
    
    if "kdp" != GetConnectionProtocol():
        print("Target is not connected over kdp. Nothing to do here.")
        return
    
    # Set up the manual KDP packet
    input_address = unsigned(addressof(kern.globals.manual_pkt.input))
    len_address = unsigned(addressof(kern.globals.manual_pkt.len))
    data_address = unsigned(addressof(kern.globals.manual_pkt.data))
    if not WriteInt32ToMemoryAddress(0, input_address):
        print("0x{0: <4x}: 0x{1: <1x}".format(addr, result))
        return
    
    kdp_pkt_size = GetType('kdp_readioport_req_t').GetByteSize()
    if not WriteInt32ToMemoryAddress(kdp_pkt_size, len_address):
        print("0x{0: <4x}: 0x{1: <1x}".format(addr, result))
        return
    
    kgm_pkt = kern.GetValueFromAddress(data_address, 'kdp_readioport_req_t *')
    
    header_value = GetKDPPacketHeaderInt(request=GetEnumValue('kdp_req_t::KDP_READIOPORT'), length = kdp_pkt_size)
    
    if( WriteInt64ToMemoryAddress((header_value), int(addressof(kgm_pkt.hdr))) and
        WriteInt16ToMemoryAddress(addr, int(addressof(kgm_pkt.address))) and
        WriteInt32ToMemoryAddress(numbytes, int(addressof(kgm_pkt.nbytes))) and
        WriteInt16ToMemoryAddress(lcpu, int(addressof(kgm_pkt.lcpu))) and
        WriteInt32ToMemoryAddress(1, input_address)
        ):
        
        result_pkt = Cast(addressof(kern.globals.manual_pkt.data), 'kdp_readioport_reply_t *')
        
        if(result_pkt.error == 0):
            if numbytes == 1:
                result = dereference(Cast(addressof(result_pkt.data), 'uint8_t *'))
            elif numbytes == 2:
                result = dereference(Cast(addressof(result_pkt.data), 'uint16_t *'))
            elif numbytes == 4:
                result = dereference(Cast(addressof(result_pkt.data), 'uint32_t *'))

    print("{0: <#6x}: {1:#0{2}x}".format(addr, result, (numbytes*2)+2))

def WriteIOPortInt(addr, numbytes, value, lcpu):
    """ Writes 'value' into ioport specified by 'addr'. Prints errors if it encounters any
    """
    if "kdp" != GetConnectionProtocol():
        print("Target is not connected over kdp. Nothing to do here.")
        return
    
    # Set up the manual KDP packet
    input_address = unsigned(addressof(kern.globals.manual_pkt.input))
    len_address = unsigned(addressof(kern.globals.manual_pkt.len))
    data_address = unsigned(addressof(kern.globals.manual_pkt.data))
    if not WriteInt32ToMemoryAddress(0, input_address):
        print("error writing {0: #x} to port {1: <#6x}: failed to write 0 to input_address".format(value, addr))
        return
    
    kdp_pkt_size = GetType('kdp_writeioport_req_t').GetByteSize()
    if not WriteInt32ToMemoryAddress(kdp_pkt_size, len_address):
        print("error writing {0: #x} to port {1: <#6x}: failed to write kdp_pkt_size".format(value, addr))
        return
    
    kgm_pkt = kern.GetValueFromAddress(data_address, 'kdp_writeioport_req_t *')
    
    header_value = GetKDPPacketHeaderInt(request=GetEnumValue('kdp_req_t::KDP_WRITEIOPORT'), length = kdp_pkt_size)
    
    if( WriteInt64ToMemoryAddress((header_value), int(addressof(kgm_pkt.hdr))) and
        WriteInt16ToMemoryAddress(addr, int(addressof(kgm_pkt.address))) and
        WriteInt32ToMemoryAddress(numbytes, int(addressof(kgm_pkt.nbytes))) and
        WriteInt16ToMemoryAddress(lcpu, int(addressof(kgm_pkt.lcpu)))
        ):
        if numbytes == 1:
            if not WriteInt8ToMemoryAddress(value, int(addressof(kgm_pkt.data))):
                print("error writing {0: #x} to port {1: <#6x}: failed to write 8 bit data".format(value, addr))
                return
        elif numbytes == 2:
            if not WriteInt16ToMemoryAddress(value, int(addressof(kgm_pkt.data))):
                print("error writing {0: #x} to port {1: <#6x}: failed to write 16 bit data".format(value, addr))
                return
        elif numbytes == 4:
            if not WriteInt32ToMemoryAddress(value, int(addressof(kgm_pkt.data))):
                print("error writing {0: #x} to port {1: <#6x}: failed to write 32 bit data".format(value, addr))
                return
        if not WriteInt32ToMemoryAddress(1, input_address):
            print("error writing {0: #x} to port {1: <#6x}: failed to write to input_address".format(value, addr))
            return

        result_pkt = Cast(addressof(kern.globals.manual_pkt.data), 'kdp_writeioport_reply_t *')
        
        # Done with the write
        if(result_pkt.error == 0):
            print("Writing {0: #x} to port {1: <#6x} was successful".format(value, addr))
    else:
        print("error writing {0: #x} to port {1: <#6x}".format(value, addr))

@lldb_command('showinterruptcounts')
def showinterruptcounts(cmd_args=None):
    """ Shows event source based interrupt counts by nub name and interrupt index.
        Does not cover interrupts that are not event source based.  Will report 0
        if interrupt accounting is disabled.
    """

    header_format = "{0: <20s} {1: >5s} {2: >20s}"
    content_format = "{0: <20s} {1: >5d} {2: >20d}"

    print(header_format.format("Name", "Index", "Count"))
    
    for i in kern.interrupt_stats:
        owner = CastIOKitClass(i.owner, 'IOInterruptEventSource *')
        nub = CastIOKitClass(owner.provider, 'IORegistryEntry *') 
        name = None

        # To uniquely identify an interrupt, we need the nub name and the index.  The index
        # is stored with the stats object, but we need to retrieve the name.

        registryTable = nub.fRegistryTable
        propertyTable = nub.fPropertyTable
    
        name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
        if name is None:
            name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
        if name is None:
            name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)

        if name is None:
            nub_name = "Unknown"
        else:
            nub_name = GetString(CastIOKitClass(name, 'OSString *'))

        # We now have everything we need; spew the requested data.

        interrupt_index = i.interruptIndex
        first_level_count = i.interruptStatistics[0]

        print(content_format.format(nub_name, interrupt_index, first_level_count))
    
    return True

@lldb_command('showinterruptstats')
def showinterruptstats(cmd_args=None):
    """ Shows event source based interrupt statistics by nub name and interrupt index.
        Does not cover interrupts that are not event source based.  Will report 0
        if interrupt accounting is disabled, or if specific statistics are disabled.
        Time is reported in ticks of mach_absolute_time.  Statistics are:
        
        Interrupt Count: Number of times the interrupt context handler was run
        Interrupt Time: Total time spent in the interrupt context handler (if any)
        Workloop Count: Number of times the kernel context handler was run
        Workloop CPU Time: Total CPU time spent running the kernel context handler
        Workloop Time: Total time spent running the kernel context handler
    """

    header_format = "{0: <20s} {1: >5s} {2: >20s} {3: >20s} {4: >20s} {5: >20s} {6: >20s} {7: >20s} {8: >20s} {9: >20s}"
    content_format = "{0: <20s} {1: >5d} {2: >20d} {3: >20d} {4: >20d} {5: >20d} {6: >20d} {7: >20d} {8: >20d} {9: >#20x}"

    print(header_format.format("Name", "Index", "Interrupt Count", "Interrupt Time", "Avg Interrupt Time", "Workloop Count", "Workloop CPU Time", "Workloop Time", "Avg Workloop Time", "Owner"))
    
    for i in kern.interrupt_stats:
        owner = CastIOKitClass(i.owner, 'IOInterruptEventSource *')
        nub = CastIOKitClass(owner.provider, 'IORegistryEntry *') 
        name = None

        # To uniquely identify an interrupt, we need the nub name and the index.  The index
        # is stored with the stats object, but we need to retrieve the name.

        registryTable = nub.fRegistryTable
        propertyTable = nub.fPropertyTable
    
        name = LookupKeyInOSDict(registryTable, kern.globals.gIOServicePlane.nameKey)
        if name is None:
            name = LookupKeyInOSDict(registryTable, kern.globals.gIONameKey)
        if name is None:
            name = LookupKeyInOSDict(propertyTable, kern.globals.gIOClassKey)

        if name is None:
            nub_name = "Unknown"
        else:
            nub_name = GetString(CastIOKitClass(name, 'OSString *'))

        # We now have everything we need; spew the requested data.

        interrupt_index = i.interruptIndex
        first_level_count = i.interruptStatistics[0]
        second_level_count = i.interruptStatistics[1]
        first_level_time = i.interruptStatistics[2]
        second_level_cpu_time = i.interruptStatistics[3]
        second_level_system_time = i.interruptStatistics[4]

        avg_first_level_time = 0
        if first_level_count != 0:
            avg_first_level_time = first_level_time // first_level_count

        avg_second_level_time = 0
        if second_level_count != 0:
            avg_second_level_time = second_level_system_time // second_level_count

        print(content_format.format(nub_name, interrupt_index, first_level_count, first_level_time, avg_first_level_time,
            second_level_count, second_level_cpu_time, second_level_system_time, avg_second_level_time, owner))
    
    return True

def GetRegistryPlane(plane_name):
    """
    Given plane_name, returns IORegistryPlane * object or None if there's no such registry plane
    """
    return LookupKeyInOSDict(kern.globals.gIORegistryPlanes, plane_name, CompareStringToOSSymbol)

def DecodePreoslogSource(source):
    """
    Given preoslog source, return a matching string representation
    """
    source_to_str = {0 : "iboot"}
    if source in source_to_str:
        return source_to_str[source]
    return "UNKNOWN"

def GetPreoslogHeader():
    """
    Scan IODeviceTree for preoslog and return a python representation of it
    """
    edt_plane = GetRegistryPlane("IODeviceTree")
    if edt_plane is None:
        print("Couldn't obtain a pointer to IODeviceTree")
        return None

    # Registry API functions operate on "plane" global variable
    global plane
    prev_plane = plane
    plane = edt_plane
    chosen = FindRegistryObjectRecurse(kern.globals.gRegistryRoot, "chosen")
    if chosen is None:
        print("Couldn't obtain /chosen IORegistryEntry")
        return None

    memory_map = FindRegistryObjectRecurse(chosen, "memory-map")
    if memory_map is None:
        print("Couldn't obtain memory-map from /chosen")
        return None

    plane = prev_plane

    mm_preoslog = LookupKeyInOSDict(memory_map.fPropertyTable, "preoslog", CompareStringToOSSymbol)
    if mm_preoslog is None:
        print("Couldn't find preoslog entry in memory-map")
        return None

    if mm_preoslog.length != 16:
        print("preoslog entry in memory-map is malformed, expected len is 16, given len is {:d}".format(mm_preoslog.length))
        return None

    data = cast(mm_preoslog.data, "dtptr_t *")
    preoslog_paddr = unsigned(data[0])
    preoslog_vaddr = kern.PhysToKernelVirt(preoslog_paddr)
    preoslog_size = unsigned(data[1])

    preoslog_header = PreoslogHeader()

    # This structure defnition doesn't exist in xnu
    """
    typedef struct  __attribute__((packed)) {
        char magic[4];
        uint32_t size;
        uint32_t offset;
        uint8_t source;
        uint8_t wrapped;
        char data[];
    } preoslog_header_t; 
    """
    preoslog_header_ptr = kern.GetValueFromAddress(preoslog_vaddr, "uint8_t *")
    preoslog_header.magic = preoslog_header_ptr[0:4]
    preoslog_header.source = DecodePreoslogSource(unsigned(preoslog_header_ptr[12]))
    preoslog_header.wrapped = unsigned(preoslog_header_ptr[13])
    preoslog_header_ptr = kern.GetValueFromAddress(preoslog_vaddr, "uint32_t *")
    preoslog_header.size = unsigned(preoslog_header_ptr[1])
    preoslog_header.offset = unsigned(preoslog_header_ptr[2])

    for i in range(len(preoslog_header.valid_magic)):
        c = chr(unsigned(preoslog_header.magic[i]))
        if c != preoslog_header.valid_magic[i]:
            string = "Error: magic doesn't match, expected {:.4s}, given {:.4s}"
            print(string.format(preoslog_header.valid_magic, preoslog_header.magic))
            return None

    if preoslog_header.size != preoslog_size:
        string = "Error: size mismatch preoslog_header.size ({}) != preoslog_size ({})"
        print(string.format(preoslog_header.size, preoslog_size))
        return None

    preoslog_data_ptr = kern.GetValueFromAddress(preoslog_vaddr + 14, "char *")
    preoslog_header.data = preoslog_data_ptr.GetSBValue().GetPointeeData(0, preoslog_size)
    return preoslog_header

@lldb_command("showpreoslog")
def showpreoslog(cmd_args=None):
    """ Display preoslog buffer """

    preoslog = GetPreoslogHeader()
    if preoslog is None:
        print("Error: couldn't obtain preoslog header")
        return False

    header = "".join([
        "----preoslog log header-----\n",
        "size - {} bytes\n",
        "write offset - {:#x}\n",
        "wrapped - {}\n",
        "source - {}\n",
        "----preoslog log start------"
        ])

    print(header.format(preoslog.size, preoslog.offset, preoslog.wrapped, preoslog.source))

    err = lldb.SBError()
    if preoslog.wrapped > 0:
        print(preoslog.data.GetString(err, preoslog.offset + 1))
    
    print(preoslog.data.GetString(err, 0).encode(errors='backslashreplace').decode())
    print("-----preoslog log end-------")

    if not err.success:
        raise RuntimeError(f"SBError when retreiving preoslog data: {err.GetDescription()}")
        
    return True

@lldb_command('showeventsources')
def ShowEventSources(cmd_args=None):
    """ Show all event sources for a IOWorkLoop
        syntax: (lldb) showeventsources <IOWorkLoop *>
    """
    if cmd_args is None or len(cmd_args) == 0:
        raise ArgumentError("Please specify the address of the IOWorkLoop")

    obj = kern.GetValueFromAddress(cmd_args[0], 'IOWorkLoop *')
    idx = 0
    event = obj.eventChain
    while event != 0:
        enabled = event.enabled
        print("{}: {} [{}]".format(idx, GetObjectSummary(event), "enabled" if enabled else "disabled"))
        event = event.eventChainNext
        idx += 1

def GetRegionProp(propertyTable, pattern):
    """ Returns the list corresponding to a given pattern from a registry entry's property table
        Returns empty list if the key is not found
        The property that is being searched for is specified as a string in pattern
    """
    if not propertyTable:
        return None

    count = unsigned(propertyTable.count)
    result = []
    res = None
    idx = 0
    while idx < count:
        res = re.search(pattern, str(propertyTable.dictionary[idx].key.string))
        if res:
            result.append(res.group())
        idx += 1

    return result

@lldb_command("showcarveouts")
def ShowCarveouts(cmd_args=None):
    """
    Scan IODeviceTree for every object in carveout-memory-map and print the memory carveouts.
    syntax: (lldb) showcarveouts
    """
    edt_plane = GetRegistryPlane("IODeviceTree")
    if edt_plane is None:
        print("Couldn't obtain a pointer to IODeviceTree")
        return None

    # Registry API functions operate on "plane" global variable
    global plane
    prev_plane = plane
    plane = edt_plane

    chosen = FindRegistryObjectRecurse(kern.globals.gRegistryRoot, "chosen")
    if chosen is None:
        print("Couldn't obtain /chosen IORegistryEntry")
        return None

    memory_map = FindRegistryObjectRecurse(chosen, "carveout-memory-map")
    if memory_map is None:
        print("Couldn't obtain memory-map from /chosen/carveout-memory-map")
        return None

    plane = prev_plane

    """
    Dynamically populated by iBoot to store memory region description
    region-id-<n>: <region n base> <region n size>
    region-name-id-<n>: <region n name>
    """
    name_prop_list = []
    range_prop_list = []
    region_id_list = []
    region_name_id_list = []

    region_id = re.compile(r"region-id-\d+")
    region_id_list = GetRegionProp(memory_map.fPropertyTable, region_id);
    region_name_id = re.compile(r"region-name-id-\d+")
    region_name_id_list = GetRegionProp(memory_map.fPropertyTable, region_name_id);

    for names in region_name_id_list:
        mm_entry = LookupKeyInOSDict(memory_map.fPropertyTable, names, CompareStringToOSSymbol)
        if mm_entry is None:
            print("Couldn't find " + names + " entry in carveout-memory-map", file=sys.stderr)
            continue
        data = cast(mm_entry.data, "char *")
        string = "{:<32s}: "
        name_prop_list.append( string.format(data) );

    for ids in region_id_list:
        mm_entry = LookupKeyInOSDict(memory_map.fPropertyTable, ids, CompareStringToOSSymbol)
        if mm_entry is None:
            print("Couldn't find " + ids + " entry in carveout-memory-map")
            continue

        data = cast(mm_entry.data, "dtptr_t *")
        paddr = unsigned(data[0])
        size = unsigned(data[1])

        string = "0x{:x}-0x{:x} (size: 0x{:x})"
        range_prop_list.append(string.format(paddr, paddr+size, size));

    for namep, rangep in zip(name_prop_list, range_prop_list):
        print(namep, rangep)

    return True