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
/*
 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * The contents of this file constitute Original Code as defined in and
 * are subject to the Apple Public Source License Version 1.1 (the
 * "License").  You may not use this file except in compliance with the
 * License.  Please obtain a copy of the License at
 * http://www.apple.com/publicsource and read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
#include <libkern/c++/OSContainers.h>
#include <IOKit/IODeviceTreeSupport.h>
#include <IOKit/IORegistryEntry.h>
#include <IOKit/IOCatalogue.h>
#include <libkern/c++/OSUnserialize.h>
#include <libkern/OSByteOrder.h>
#include <libsa/catalogue.h>

extern "C" {
#include <machine/machine_routines.h>
#include <mach/host_info.h>
#include <mach/kmod.h>
#include <libsa/mkext.h>
#include <libsa/vers_rsrc.h>
};

#include <IOKit/IOLib.h>

#include <IOKit/assert.h>

extern "C" {
extern void IODTFreeLoaderInfo( char *key, void *infoAddr, int infoSize );
extern kern_return_t host_info(host_t host,
    host_flavor_t flavor,
    host_info_t info,
    mach_msg_type_number_t  *count);
extern int check_cpu_subtype(cpu_subtype_t cpu_subtype);
};


#define LOG_DELAY()

#define VTYELLOW   "\033[33m"
#define VTRESET    "\033[0m"


/*********************************************************************
*********************************************************************/
static OSDictionary * gStartupExtensions = 0;
static OSArray * gBootLoaderObjects = 0;

OSDictionary * getStartupExtensions(void) {
    if (gStartupExtensions) {
        return gStartupExtensions;
    }
    gStartupExtensions = OSDictionary::withCapacity(1);
    if (!gStartupExtensions) {
        IOLog("Error: Couldn't allocate "
            "startup extensions dictionary.\n");
        LOG_DELAY();
    }
    return gStartupExtensions;
}

/* This array holds objects that are needed to be held around during
 * boot before kextd starts up. Currently it contains OSData objects
 * copied from OF entries for mkext archives in device ROMs. Because
 * the Device Tree support code dumps these after initially handing
 * them to us, we have to be able to clean them up later.
 */
OSArray * getBootLoaderObjects(void) {
    if (gBootLoaderObjects) {
        return gBootLoaderObjects;
    }
    gBootLoaderObjects = OSArray::withCapacity(1);
    if (! gBootLoaderObjects) {
        IOLog("Error: Couldn't allocate "
            "bootstrap objects array.\n");
        LOG_DELAY();
    }
    return gBootLoaderObjects;
}


/*********************************************************************
* This function checks that a driver dict has all the required
* entries and does a little bit of value checking too.
*********************************************************************/
bool validateExtensionDict(OSDictionary * extension) {

    bool result = true;
    OSString * name;         // do not release
    OSString * stringValue;  // do not release
    UInt32 vers;

    name = OSDynamicCast(OSString,
        extension->getObject("CFBundleIdentifier"));
    if (!name) {
        IOLog(VTYELLOW "Extension has no \"CFBundleIdentifier\" property.\n"
            VTRESET);
        LOG_DELAY();
        result = false;
        goto finish;
    }

    stringValue = OSDynamicCast(OSString,
        extension->getObject("CFBundleVersion"));
    if (!stringValue) {
        IOLog(VTYELLOW "Extension \"%s\" has no \"CFBundleVersion\" "
            "property.\n" VTRESET,
            name->getCStringNoCopy());
        LOG_DELAY();
        result = false;
        goto finish;
    }
    if (!VERS_parse_string(stringValue->getCStringNoCopy(),
        &vers)) {
        IOLog(VTYELLOW "Extension \"%s\" has an invalid "
            "\"CFBundleVersion\" property.\n" VTRESET,
            name->getCStringNoCopy());
        LOG_DELAY();
        result = false;
        goto finish;
    }


finish:
    // FIXME: Make return real result after kext conversion
    return true;

    return result;
}


/*********************************************************************
*********************************************************************/
OSDictionary * compareExtensionVersions(
    OSDictionary * incumbent,
    OSDictionary * candidate) {

    OSDictionary * winner = NULL;

    OSDictionary * incumbentPlist = NULL;
    OSDictionary * candidatePlist = NULL;
    OSString * incumbentName = NULL;
    OSString * candidateName = NULL;
    OSString * incumbentVersionString = NULL;
    OSString * candidateVersionString = NULL;
    UInt32 incumbent_vers = 0;
    UInt32 candidate_vers = 0;

    incumbentPlist = OSDynamicCast(OSDictionary,
        incumbent->getObject("plist"));
    candidatePlist = OSDynamicCast(OSDictionary,
        candidate->getObject("plist"));

    if (!incumbentPlist || !candidatePlist) {
        IOLog("compareExtensionVersions() called with invalid "
            "extension dictionaries.\n");
        LOG_DELAY();
        winner = NULL;
        goto finish;
    }

    incumbentName = OSDynamicCast(OSString,
        incumbentPlist->getObject("CFBundleIdentifier"));
    candidateName = OSDynamicCast(OSString,
        candidatePlist->getObject("CFBundleIdentifier"));
    incumbentVersionString = OSDynamicCast(OSString,
        incumbentPlist->getObject("CFBundleVersion"));
    candidateVersionString = OSDynamicCast(OSString,
        candidatePlist->getObject("CFBundleVersion"));

    if (!incumbentName || !candidateName ||
        !incumbentVersionString || !candidateVersionString) {

        IOLog("compareExtensionVersions() called with invalid "
            "extension dictionaries.\n");
        LOG_DELAY();
        winner = NULL;
        goto finish;
    }

    if (strcmp(incumbentName->getCStringNoCopy(),
               candidateName->getCStringNoCopy())) {

        IOLog("compareExtensionVersions() called with different "
            "extension names (%s and %s).\n",
            incumbentName->getCStringNoCopy(),
            candidateName->getCStringNoCopy());
        LOG_DELAY();
        winner = NULL;
        goto finish;
    }

    if (!VERS_parse_string(incumbentVersionString->getCStringNoCopy(),
        &incumbent_vers)) {

        IOLog(VTYELLOW "Error parsing version string for extension %s (%s)\n"
            VTRESET,
            incumbentName->getCStringNoCopy(),
            incumbentVersionString->getCStringNoCopy());
        LOG_DELAY();
        winner = NULL;
        goto finish;
    }

    if (!VERS_parse_string(candidateVersionString->getCStringNoCopy(),
        &candidate_vers)) {

        IOLog(VTYELLOW "Error parsing version string for extension %s (%s)\n"
            VTRESET,
            candidateName->getCStringNoCopy(),
            candidateVersionString->getCStringNoCopy());
        LOG_DELAY();
        winner = NULL;
        goto finish;
     }
  
    if (candidate_vers > incumbent_vers) {
        IOLog(VTYELLOW "Replacing extension \"%s\" with newer version "
            "(%s -> %s).\n" VTRESET,
            incumbentName->getCStringNoCopy(),
            incumbentVersionString->getCStringNoCopy(),
            candidateVersionString->getCStringNoCopy());
        LOG_DELAY();
        winner = candidate;
        goto finish;
    } else {
        IOLog(VTYELLOW "Skipping duplicate extension \"%s\" with older/same "
            " version (%s -> %s).\n" VTRESET,
            candidateName->getCStringNoCopy(),
            candidateVersionString->getCStringNoCopy(),
            incumbentVersionString->getCStringNoCopy());
        LOG_DELAY();
        winner = incumbent;
        goto finish;
    }

finish:

    // no cleanup, how nice
    return winner;
}


/*********************************************************************
* This function merges entries in the mergeFrom dictionary into the
* mergeInto dictionary. If it returns false, the two dictionaries are
* not altered. If it returns true, then mergeInto may have new
* entries; any keys that were already present in mergeInto are
* removed from mergeFrom, so that the caller can see what was
* actually merged.
*********************************************************************/
bool mergeExtensionDictionaries(OSDictionary * mergeInto,
    OSDictionary * mergeFrom) {

    bool result = true;
    OSDictionary * mergeIntoCopy = NULL;       // must release
    OSDictionary * mergeFromCopy = NULL;       // must release
    OSCollectionIterator * keyIterator = NULL; // must release
    OSString * key;                            // don't release

   /* Add 1 to count to guarantee copy can grow (grr).
    */
    mergeIntoCopy = OSDictionary::withDictionary(mergeInto,
        mergeInto->getCount() + 1);
    if (!mergeIntoCopy) {
        IOLog("Error: Failed to copy 'into' extensions dictionary "
            "for merge.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

   /* Add 1 to count to guarantee copy can grow (grr).
    */
    mergeFromCopy = OSDictionary::withDictionary(mergeFrom,
        mergeFrom->getCount() + 1);
    if (!mergeFromCopy) {
        IOLog("Error: Failed to copy 'from' extensions dictionary "
            "for merge.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    keyIterator = OSCollectionIterator::withCollection(mergeFrom);
    if (!keyIterator) {
        IOLog("Error: Failed to allocate iterator for extensions.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }


   /*****
    * Loop through "from" dictionary, checking if the identifier already
    * exists in the "into" dictionary and checking versions if it does.
    */
    while ((key = OSDynamicCast(OSString, keyIterator->getNextObject()))) {
        OSDictionary * incumbentExt = OSDynamicCast(OSDictionary,
            mergeIntoCopy->getObject(key));
        OSDictionary * candidateExt = OSDynamicCast(OSDictionary,
            mergeFrom->getObject(key));

        if (!incumbentExt) {
            if (!mergeIntoCopy->setObject(key, candidateExt)) {

               /* This is a fatal error, so bail.
                */
                IOLog("mergeExtensionDictionaries(): Failed to add "
                    "identifier %s\n",
                    key->getCStringNoCopy());
                LOG_DELAY();
                result = false;
                goto finish;
            }
        } else {
            OSDictionary * mostRecentExtension =
                compareExtensionVersions(incumbentExt, candidateExt);

            if (mostRecentExtension == incumbentExt) {
                mergeFromCopy->removeObject(key);
            } else if (mostRecentExtension == candidateExt) {

                if (!mergeIntoCopy->setObject(key, candidateExt)) {

                   /* This is a fatal error, so bail.
                    */
                    IOLog("mergeExtensionDictionaries(): Failed to add "
                        "identifier %s\n",
                        key->getCStringNoCopy());
                    LOG_DELAY();
                    result = false;
                    goto finish;
                }
            } else /* should be NULL */ {
    
               /* This is a nonfatal error, so continue doing others.
                */
                IOLog("mergeExtensionDictionaries(): Error comparing "
                    "versions of duplicate extensions %s.\n",
                    key->getCStringNoCopy());
                LOG_DELAY();
                continue;
            }
        }
    }

finish:

   /* If successful, replace the contents of the original
    * dictionaries with those of the modified copies.
    */
    if (result) {
        mergeInto->flushCollection();
        mergeInto->merge(mergeIntoCopy);
        mergeFrom->flushCollection();
        mergeFrom->merge(mergeFromCopy);
    }

    if (mergeIntoCopy) mergeIntoCopy->release();
    if (mergeFromCopy) mergeFromCopy->release();
    if (keyIterator)   keyIterator->release();

    return result;
}


/****
 * These bits are used to parse data made available by bootx.
 */
#define BOOTX_KEXT_PREFIX       "Driver-"
#define BOOTX_MULTIKEXT_PREFIX  "DriversPackage-"

typedef struct MemoryMapFileInfo {
    UInt32 paddr;
    UInt32 length;
} MemoryMapFileInfo;

typedef struct BootxDriverInfo {
    char *plistAddr;
    long  plistLength;
    void *moduleAddr;
    long  moduleLength;
} BootxDriverInfo;

typedef struct MkextEntryInfo {
    vm_address_t  base_address;
    mkext_file  * fileinfo;
} MkextEntryInfo;


/*********************************************************************
* This private function reads the data for a single extension from
* the bootx memory-map's propery dict, returning a dictionary with
* keys "plist" for the extension's Info.plist as a parsed OSDictionary
* and "code" for the extension's executable code as an OSData.
*********************************************************************/
OSDictionary * readExtension(OSDictionary * propertyDict,
    const char * memory_map_name) {

    int error = 0;
    OSData               * bootxDriverDataObject = NULL;
    OSDictionary         * driverPlist = NULL;
    OSString             * driverName = NULL;
    OSData               * driverCode = NULL;
    OSString             * errorString = NULL;
    OSDictionary         * driverDict = NULL;

    MemoryMapFileInfo * driverInfo = 0;
    BootxDriverInfo * dataBuffer;

    kmod_info_t          * loaded_kmod = NULL;

    bootxDriverDataObject = OSDynamicCast(OSData,
        propertyDict->getObject(memory_map_name));
    // don't release bootxDriverDataObject

    if (!bootxDriverDataObject) {
        IOLog("Error: No driver data object "
            "for device tree entry \"%s\".\n",
            memory_map_name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

    driverDict = OSDictionary::withCapacity(2);
    if (!driverDict) {
        IOLog("Error: Couldn't allocate dictionary "
            "for device tree entry \"%s\".\n", memory_map_name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

    driverInfo = (MemoryMapFileInfo *)
        bootxDriverDataObject->getBytesNoCopy(0,
        sizeof(MemoryMapFileInfo));
    dataBuffer = (BootxDriverInfo *)ml_static_ptovirt(
        driverInfo->paddr);
    if (!dataBuffer) {
        IOLog("Error: No data buffer "
        "for device tree entry \"%s\".\n", memory_map_name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

    driverPlist = OSDynamicCast(OSDictionary,
        OSUnserializeXML(dataBuffer->plistAddr, &errorString));
    if (!driverPlist) {
        IOLog("Error: Couldn't read XML property list "
            "for device tree entry \"%s\".\n", memory_map_name);
        LOG_DELAY();
        if (errorString) {
            IOLog("XML parse error: %s.\n",
                errorString->getCStringNoCopy());
            LOG_DELAY();
        }
        error = 1;
        goto finish;
    }


    driverName = OSDynamicCast(OSString,
        driverPlist->getObject("CFBundleIdentifier"));  // do not release
    if (!driverName) {
        IOLog("Error: Device tree entry \"%s\" has "
            "no \"CFBundleIdentifier\" property.\n", memory_map_name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

   /* Check if kmod is already loaded and is a real loadable one (has
    * an address).
    */
    loaded_kmod = kmod_lookupbyname_locked(driverName->getCStringNoCopy());
    if (loaded_kmod && loaded_kmod->address) {
        IOLog("Skipping new extension \"%s\"; an extension named "
            "\"%s\" is already loaded.\n",
            driverName->getCStringNoCopy(),
            loaded_kmod->name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

    if (!validateExtensionDict(driverPlist)) {
        IOLog("Error: Failed to validate property list "
            "for device tree entry \"%s\".\n", memory_map_name);
        LOG_DELAY();
        error = 1;
        goto finish;
    }

    driverDict->setObject("plist", driverPlist);

   /* It's perfectly okay for a KEXT to have no executable.
    * Check that moduleAddr is nonzero before attempting to
    * get one.
    *
    * NOTE: The driverCode object is created "no-copy", so
    * it doesn't own that memory. The memory must be freed
    * separately from the OSData object (see
    * clearStartupExtensionsAndLoaderInfo() at the end of this file).
    */
    if (dataBuffer->moduleAddr && dataBuffer->moduleLength) {
        driverCode = OSData::withBytesNoCopy(dataBuffer->moduleAddr,
            dataBuffer->moduleLength);
        if (!driverCode) {
            IOLog("Error: Couldn't allocate data object "
                "to hold code for device tree entry \"%s\".\n",
                memory_map_name);
            LOG_DELAY();
            error = 1;
            goto finish;
        }

        if (driverCode) {
            driverDict->setObject("code", driverCode);
        }
    }

finish:

    if (loaded_kmod) {
        kfree(loaded_kmod, sizeof(kmod_info_t));
    }

    // do not release bootxDriverDataObject
    // do not release driverName

    if (driverPlist) {
        driverPlist->release();
    }
    if (errorString) {
        errorString->release();
    }
    if (driverCode) {
        driverCode->release();
    }
    if (error) {
        if (driverDict) {
            driverDict->release();
            driverDict = NULL;
        }
    }
    return driverDict;
}


/*********************************************************************
* Used to uncompress a single file entry in an mkext archive.
*
* The OSData returned does not own its memory! You must deallocate
* that memory using kmem_free() before releasing the OSData().
*********************************************************************/
static bool uncompressFile(u_int8_t *base_address, mkext_file * fileinfo,
		           /* out */ OSData ** file) {

    bool result = true;
    kern_return_t kern_result;
    u_int8_t * uncompressed_file = 0; // kmem_free() on error
    OSData * uncompressedFile = 0;    // returned
    size_t uncompressed_size = 0;

    size_t offset = OSSwapBigToHostInt32(fileinfo->offset);
    size_t compsize = OSSwapBigToHostInt32(fileinfo->compsize);
    size_t realsize = OSSwapBigToHostInt32(fileinfo->realsize);
    time_t modifiedsecs = OSSwapBigToHostInt32(fileinfo->modifiedsecs);

    *file = 0;

   /* If these four fields are zero there's no file, but that isn't
    * an error.
    */
    if (offset == 0 && compsize == 0 &&
        realsize == 0 && modifiedsecs == 0) {
        goto finish;
    }

    // Add 1 for '\0' to terminate XML string!
    kern_result = kmem_alloc(kernel_map, (vm_offset_t *)&uncompressed_file,
        realsize + 1);
    if (kern_result != KERN_SUCCESS) {
        IOLog("Error: Couldn't allocate data buffer "
              "to uncompress file.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    uncompressedFile = OSData::withBytesNoCopy(uncompressed_file,
        realsize + 1);
    if (!uncompressedFile) {
        IOLog("Error: Couldn't allocate data object "
              "to uncompress file.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    if (compsize != 0) {
        uncompressed_size = decompress_lzss(uncompressed_file,
            base_address + offset,
            compsize);
        if (uncompressed_size != realsize) {
            IOLog("Error: Uncompressed file is not the length "
                  "recorded.\n");
            LOG_DELAY();
            result = false;
            goto finish;
        }
        uncompressed_file[uncompressed_size] = '\0';
    } else {
        bcopy(base_address + offset, uncompressed_file,
            realsize);
        uncompressed_file[realsize] = '\0';
    }

    *file = uncompressedFile;

finish:
    if (!result) {
        if (uncompressed_file) {
            kmem_free(kernel_map, (vm_address_t)uncompressed_file,
                realsize + 1);
        }
        if (uncompressedFile) {
            uncompressedFile->release();
            *file = 0;
        }
    }
    return result;
}

bool uncompressModule(OSData *compData, /* out */ OSData ** file) {

    MkextEntryInfo *info = (MkextEntryInfo *) compData->getBytesNoCopy();

    return uncompressFile((u_int8_t *) info->base_address, 
			  info->fileinfo, file);
}


/*********************************************************************
* Does the work of pulling extensions out of an mkext archive located
* in memory.
*********************************************************************/
bool extractExtensionsFromArchive(MemoryMapFileInfo * mkext_file_info,
    OSDictionary * extensions) {

    bool result = true;

    u_int8_t     * crc_address = 0;
    u_int32_t      checksum;
    mkext_header * mkext_data = 0;   // don't free
    mkext_kext   * onekext_data = 0; // don't free
    mkext_file   * plist_file = 0;   // don't free
    mkext_file   * module_file = 0;  // don't free
    kmod_info_t  * loaded_kmod = 0;  // must free

    OSData       * driverPlistDataObject = 0; // must release
    OSDictionary * driverPlist = 0;  // must release
    OSData       * driverCode = 0;   // must release
    OSDictionary * driverDict = 0;   // must release
    OSString     * moduleName = 0;   // don't release
    OSString     * errorString = NULL;  // must release

    OSData         * moduleInfo = 0;  // must release
    MkextEntryInfo   module_info;

    mkext_data = (mkext_header *)mkext_file_info->paddr;

    if (OSSwapBigToHostInt32(mkext_data->magic) != MKEXT_MAGIC ||
        OSSwapBigToHostInt32(mkext_data->signature) != MKEXT_SIGN) {
        IOLog("Error: Extension archive has invalid magic or signature.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    if (OSSwapBigToHostInt32(mkext_data->length) != mkext_file_info->length) {
        IOLog("Error: Mismatch between extension archive & "
            "recorded length.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    crc_address = (u_int8_t *)&mkext_data->version;
    checksum = adler32(crc_address,
        (unsigned int)mkext_data +
        OSSwapBigToHostInt32(mkext_data->length) - (unsigned int)crc_address);

    if (OSSwapBigToHostInt32(mkext_data->adler32) != checksum) {
        IOLog("Error: Extension archive has a bad checksum.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

   /* If the MKEXT archive isn't fat, check that the CPU type & subtype
    * match that of the running kernel.
    */
    if (OSSwapBigToHostInt32(mkext_data->cputype) != (UInt32)CPU_TYPE_ANY) {
        kern_return_t          kresult = KERN_FAILURE;
        host_basic_info_data_t hostinfo;
        host_info_t            hostinfo_ptr = (host_info_t)&hostinfo;
        mach_msg_type_number_t count = sizeof(hostinfo)/sizeof(integer_t);

        kresult = host_info((host_t)1, HOST_BASIC_INFO,
            hostinfo_ptr, &count);
        if (kresult != KERN_SUCCESS) {
            IOLog("Error: Couldn't get current host info.\n");
            LOG_DELAY();
            result = false;
            goto finish;
        }
        if ((UInt32)hostinfo.cpu_type !=
            OSSwapBigToHostInt32(mkext_data->cputype)) {

            IOLog("Error: Extension archive doesn't contain software "
                "for this computer's CPU type.\n");
            LOG_DELAY();
            result = false;
            goto finish;
        }
        if (!check_cpu_subtype(OSSwapBigToHostInt32(mkext_data->cpusubtype))) {
            IOLog("Error: Extension archive doesn't contain software "
                "for this computer's CPU subtype.\n");
            LOG_DELAY();
            result = false;
            goto finish;
        }
    }

    for (unsigned int i = 0;
         i < OSSwapBigToHostInt32(mkext_data->numkexts);
         i++) {

        if (loaded_kmod) {
            kfree(loaded_kmod, sizeof(kmod_info_t));
            loaded_kmod = 0;
        }

        if (driverPlistDataObject) {
            driverPlistDataObject->release();
            driverPlistDataObject = NULL;
        }
        if (driverPlist) {
            driverPlist->release();
            driverPlist = NULL;
        }
        if (driverCode) {
            driverCode->release();
            driverCode = NULL;
        }
        if (driverDict) {
            driverDict->release();
            driverDict = NULL;
        }
        if (errorString) {
            errorString->release();
            errorString = NULL;
        }

        onekext_data = &mkext_data->kext[i];
        plist_file = &onekext_data->plist;
        module_file = &onekext_data->module;

        if (!uncompressFile((u_int8_t *)mkext_data, plist_file,
            &driverPlistDataObject)) {

            IOLog("Error: couldn't uncompress plist file "
                "from multikext archive entry %d.\n", i);
            LOG_DELAY();
            continue;
        }

        if (!driverPlistDataObject) {
            IOLog("Error: No property list present "
                "for multikext archive entry %d.\n", i);
            LOG_DELAY();
            continue;
        } else {
            driverPlist = OSDynamicCast(OSDictionary,
                OSUnserializeXML(
                    (char *)driverPlistDataObject->getBytesNoCopy(),
                    &errorString));
            if (!driverPlist) {
                IOLog("Error: Couldn't read XML property list "
                      "for multikext archive entry %d.\n", i);
                LOG_DELAY();
                if (errorString) {
                    IOLog("XML parse error: %s.\n",
                        errorString->getCStringNoCopy());
                    LOG_DELAY();
                }
                continue;
            }

            if (!validateExtensionDict(driverPlist)) {
                IOLog("Error: Failed to validate property list "
                      "for multikext archive entry %d.\n", i);
                LOG_DELAY();
                continue;
            }

        }

       /* Get the extension's module name. This is used to record
        * the extension.
        */
        moduleName = OSDynamicCast(OSString,
            driverPlist->getObject("CFBundleIdentifier"));  // do not release
        if (!moduleName) {
            IOLog("Error: Multikext archive entry %d has "
                "no \"CFBundleIdentifier\" property.\n", i);
            LOG_DELAY();
            continue; // assume a kext config error & continue
        }

       /* Check if kmod is already loaded and is a real loadable one (has
        * an address).
        */
        loaded_kmod = kmod_lookupbyname_locked(moduleName->getCStringNoCopy());
        if (loaded_kmod && loaded_kmod->address) {
            IOLog("Skipping new extension \"%s\"; an extension named "
                "\"%s\" is already loaded.\n",
                moduleName->getCStringNoCopy(),
                loaded_kmod->name);
            continue;
        }


        driverDict = OSDictionary::withCapacity(2);
        if (!driverDict) {
            IOLog("Error: Couldn't allocate dictionary "
                  "for multikext archive entry %d.\n", i);
            LOG_DELAY();
            result = false;
            goto finish;
        }

        driverDict->setObject("plist", driverPlist);

       /*****
        * Prepare an entry to hold the mkext entry info for the
        * compressed binary module, if there is one. If all four fields
        * of the module entry are zero, there isn't one.
        */
        if (OSSwapBigToHostInt32(module_file->offset) ||
            OSSwapBigToHostInt32(module_file->compsize) ||
            OSSwapBigToHostInt32(module_file->realsize) ||
            OSSwapBigToHostInt32(module_file->modifiedsecs)) {

            moduleInfo = OSData::withCapacity(sizeof(MkextEntryInfo));
            if (!moduleInfo) {
                IOLog("Error: Couldn't allocate data object "
                      "for multikext archive entry %d.\n", i);
                LOG_DELAY();
                result = false;
                goto finish;
            }

            module_info.base_address = (vm_address_t)mkext_data;
            module_info.fileinfo = module_file;

            if (!moduleInfo->appendBytes(&module_info, sizeof(module_info))) {
                IOLog("Error: Couldn't record info "
                      "for multikext archive entry %d.\n", i);
                LOG_DELAY();
                result = false;
                goto finish;
            }

            driverDict->setObject("compressedCode", moduleInfo);
        }

        OSDictionary * incumbentExt = OSDynamicCast(OSDictionary,
            extensions->getObject(moduleName));

        if (!incumbentExt) {
            extensions->setObject(moduleName, driverDict);
        } else {
            OSDictionary * mostRecentExtension =
                compareExtensionVersions(incumbentExt, driverDict);

            if (mostRecentExtension == incumbentExt) {
                /* Do nothing, we've got the most recent. */
            } else if (mostRecentExtension == driverDict) {
                if (!extensions->setObject(moduleName, driverDict)) {

                   /* This is a fatal error, so bail.
                    */
                    IOLog("extractExtensionsFromArchive(): Failed to add "
                        "identifier %s\n",
                        moduleName->getCStringNoCopy());
                    LOG_DELAY();
                    result = false;
                    goto finish;
                }
            } else /* should be NULL */ {

               /* This is a nonfatal error, so continue.
                */
                IOLog("extractExtensionsFromArchive(): Error comparing "
                    "versions of duplicate extensions %s.\n",
                    moduleName->getCStringNoCopy());
                LOG_DELAY();
                continue;
            }
        }
    }

finish:

    if (loaded_kmod) kfree(loaded_kmod, sizeof(kmod_info_t));
    if (driverPlistDataObject) driverPlistDataObject->release();
    if (driverPlist) driverPlist->release();
    if (driverCode)  driverCode->release();
    if (moduleInfo)  moduleInfo->release();
    if (driverDict)  driverDict->release();
    if (errorString) errorString->release();

    return result;
}

/*********************************************************************
*
*********************************************************************/
bool readExtensions(OSDictionary * propertyDict,
    const char * memory_map_name,
    OSDictionary * extensions) {

    bool result = true;
    OSData * mkextDataObject = 0;      // don't release
    MemoryMapFileInfo * mkext_file_info = 0; // don't free

    mkextDataObject = OSDynamicCast(OSData,
        propertyDict->getObject(memory_map_name));
    // don't release mkextDataObject

    if (!mkextDataObject) {
        IOLog("Error: No mkext data object "
            "for device tree entry \"%s\".\n",
            memory_map_name);
        LOG_DELAY();
        result = false;
        goto finish;
    }

    mkext_file_info = (MemoryMapFileInfo *)mkextDataObject->getBytesNoCopy();
    if (!mkext_file_info) {
        result = false;
        goto finish;
    }

    result = extractExtensionsFromArchive(mkext_file_info, extensions);

finish:

    if (!result && extensions) {
        extensions->flushCollection();
    }

    return result;
}


/*********************************************************************
* Adds the personalities for an extensions dictionary to the global
* IOCatalogue.
*********************************************************************/
bool addPersonalities(OSDictionary * extensions) {
    bool result = true;
    OSCollectionIterator * keyIterator = NULL;  // must release
    OSString             * key;          // don't release
    OSDictionary * driverDict = NULL;    // don't release
    OSDictionary * driverPlist = NULL;   // don't release
    OSDictionary * thisDriverPersonalities = NULL;  // don't release
    OSArray      * allDriverPersonalities = NULL;   // must release

    allDriverPersonalities = OSArray::withCapacity(1);
    if (!allDriverPersonalities) {
        IOLog("Error: Couldn't allocate personality dictionary.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

   /* Record all personalities found so that they can be
    * added to the catalogue.
    * Note: Not all extensions have personalities.
    */

    keyIterator = OSCollectionIterator::withCollection(extensions);
    if (!keyIterator) {
        IOLog("Error: Couldn't allocate iterator to record personalities.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    while ( ( key = OSDynamicCast(OSString,
              keyIterator->getNextObject() ))) {

        driverDict = OSDynamicCast(OSDictionary,
            extensions->getObject(key));
        driverPlist = OSDynamicCast(OSDictionary,
            driverDict->getObject("plist"));
        thisDriverPersonalities = OSDynamicCast(OSDictionary,
            driverPlist->getObject("IOKitPersonalities"));

        if (thisDriverPersonalities) {
            OSCollectionIterator * pIterator;
            OSString * key;
            pIterator = OSCollectionIterator::withCollection(
                thisDriverPersonalities);
            if (!pIterator) {
                IOLog("Error: Couldn't allocate iterator "
                    "to record extension personalities.\n");
                LOG_DELAY();
                continue;
            }
            while ( (key = OSDynamicCast(OSString,
                     pIterator->getNextObject())) ) {

                OSDictionary * personality = OSDynamicCast(
                    OSDictionary,
                    thisDriverPersonalities->getObject(key));
                if (personality) {
                    allDriverPersonalities->setObject(personality);
                }
            }
            pIterator->release();
        }
    } /* extract personalities */


   /* Add all personalities found to the IOCatalogue,
    * but don't start matching.
    */
    gIOCatalogue->addDrivers(allDriverPersonalities, false);

finish:

    if (allDriverPersonalities) allDriverPersonalities->release();
    if (keyIterator) keyIterator->release();

    return result;
}


/*********************************************************************
* Called from IOCatalogue to add extensions from an mkext archive.
* This function makes a copy of the mkext object passed in because
* the device tree support code dumps it after calling us (indirectly
* through the IOCatalogue).
*********************************************************************/
bool addExtensionsFromArchive(OSData * mkextDataObject) {
    bool result = true;

    OSDictionary * startupExtensions = NULL;  // don't release
    OSArray      * bootLoaderObjects = NULL;  // don't release
    OSData       * localMkextDataObject = NULL; // don't release
    OSDictionary * extensions = NULL;         // must release
    MemoryMapFileInfo mkext_file_info;
    OSCollectionIterator * keyIterator = NULL;   // must release
    OSString             * key = NULL;           // don't release

    startupExtensions = getStartupExtensions();
    if (!startupExtensions) {
        IOLog("Can't record extension archive; there is no"
            " extensions dictionary.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    bootLoaderObjects = getBootLoaderObjects();
    if (! bootLoaderObjects) {
        IOLog("Error: Couldn't allocate array to hold temporary objects.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    extensions = OSDictionary::withCapacity(2);
    if (!extensions) {
        IOLog("Error: Couldn't allocate dictionary to unpack "
            "extension archive.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

   /* The mkext we've been handed (or the data it references) can go away,
    * so we need to make a local copy to keep around as long as it might
    * be needed.
    */
    localMkextDataObject = OSData::withData(mkextDataObject);
    if (!localMkextDataObject) {
        IOLog("Error: Couldn't copy extension archive.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    mkext_file_info.paddr = (UInt32)localMkextDataObject->getBytesNoCopy();
    mkext_file_info.length = localMkextDataObject->getLength();

   /* Save the local mkext data object so that we can deallocate it later.
    */
    bootLoaderObjects->setObject(localMkextDataObject);
    localMkextDataObject->release();

    result = extractExtensionsFromArchive(&mkext_file_info, extensions);
    if (!result) {
        IOLog("Error: Failed to extract extensions from archive.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    result = mergeExtensionDictionaries(startupExtensions, extensions);
    if (!result) {
        IOLog("Error: Failed to merge new extensions into existing set.\n");
        LOG_DELAY();
        goto finish;
    }

    result = addPersonalities(extensions);
    if (!result) {
        IOLog("Error: Failed to add personalities for extensions extracted "
            "from archive.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

finish:

    if (!result) {
        IOLog("Error: Failed to record extensions from archive.\n");
        LOG_DELAY();
    } else {
        keyIterator = OSCollectionIterator::withCollection(
            extensions);

        if (keyIterator) {
            while ( (key = OSDynamicCast(OSString,
                     keyIterator->getNextObject())) ) {

                IOLog("Added extension \"%s\" from archive.\n",
                    key->getCStringNoCopy());
                LOG_DELAY();
            }
            keyIterator->release();
        }
    }

    if (extensions) extensions->release();

    return result;
}


/*********************************************************************
* This function builds dictionaries for the startup extensions
* put into memory by bootx, recording each in the startup extensions
* dictionary. The dictionary format is this:
*
* {
*     "plist" = (the extension's Info.plist as an OSDictionary)
*     "code"  = (an OSData containing the executable file)
* }
*
* This function returns true if any extensions were found and
* recorded successfully, or if there are no start extensions,
* and false if an unrecoverable error occurred. An error reading
* a single extension is not considered fatal, and this function
* will simply skip the problematic extension to try the next one.
*********************************************************************/
bool recordStartupExtensions(void) {
    bool result = true;
    OSDictionary         * startupExtensions = NULL; // must release
    OSDictionary         * existingExtensions = NULL; // don't release
    OSDictionary         * mkextExtensions = NULL;   // must release
    IORegistryEntry      * bootxMemoryMap = NULL;    // must release
    OSDictionary         * propertyDict = NULL;      // must release
    OSCollectionIterator * keyIterator = NULL;       // must release
    OSString             * key = NULL;               // don't release

    OSDictionary * newDriverDict = NULL;  // must release
    OSDictionary * driverPlist = NULL; // don't release

    IOLog("Recording startup extensions.\n");
    LOG_DELAY();

    existingExtensions = getStartupExtensions();
    if (!existingExtensions) {
        IOLog("Error: There is no dictionary for startup extensions.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    startupExtensions = OSDictionary::withCapacity(1);
    if (!startupExtensions) {
        IOLog("Error: Couldn't allocate dictionary "
            "to record startup extensions.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    bootxMemoryMap =
        IORegistryEntry::fromPath(
            "/chosen/memory-map", // path
            gIODTPlane            // plane
            );
    // return value is retained so be sure to release it

    if (!bootxMemoryMap) {
        IOLog("Error: Couldn't read booter memory map.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    propertyDict = bootxMemoryMap->dictionaryWithProperties();
    if (!propertyDict) {
        IOLog("Error: Couldn't get property dictionary "
            "from memory map.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    keyIterator = OSCollectionIterator::withCollection(propertyDict);
    if (!keyIterator) {
        IOLog("Error: Couldn't allocate iterator for driver images.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

    while ( (key = OSDynamicCast(OSString,
             keyIterator->getNextObject())) ) {
       /* Clear newDriverDict & mkextExtensions upon entry to the loop,
        * handling both successful and unsuccessful iterations.
        */
        if (newDriverDict) {
            newDriverDict->release();
            newDriverDict = NULL;
        }
        if (mkextExtensions) {
            mkextExtensions->release();
            mkextExtensions = NULL;
        }

        const char * keyValue = key->getCStringNoCopy();

        if ( !strncmp(keyValue, BOOTX_KEXT_PREFIX,
              strlen(BOOTX_KEXT_PREFIX)) ) {

           /* Read the extension from the bootx-supplied memory.
            */
            newDriverDict = readExtension(propertyDict, keyValue);
            if (!newDriverDict) {
                IOLog("Error: Couldn't read data "
                    "for device tree entry \"%s\".\n", keyValue);
                LOG_DELAY();
                continue;
            }


           /* Preprare to record the extension by getting its info plist.
            */
            driverPlist = OSDynamicCast(OSDictionary,
                newDriverDict->getObject("plist"));
            if (!driverPlist) {
                IOLog("Error: Extension in device tree entry \"%s\" "
                    "has no property list.\n", keyValue);
                LOG_DELAY();
                continue;
            }


           /* Get the extension's module name. This is used to record
            * the extension. Do *not* release the moduleName.
            */
            OSString * moduleName = OSDynamicCast(OSString,
                driverPlist->getObject("CFBundleIdentifier"));
            if (!moduleName) {
                IOLog("Error: Device tree entry \"%s\" has "
                    "no \"CFBundleIdentifier\" property.\n", keyValue);
                LOG_DELAY();
                continue;
            }


           /* All has gone well so far, so record the extension under
            * its module name, checking for an existing duplicate.
            *
            * Do not release moduleName, as it's part of the extension's
            * plist.
            */
            OSDictionary * incumbentExt = OSDynamicCast(OSDictionary,
                startupExtensions->getObject(moduleName));

            if (!incumbentExt) {
                startupExtensions->setObject(moduleName, newDriverDict);
            } else {
                OSDictionary * mostRecentExtension =
                    compareExtensionVersions(incumbentExt, newDriverDict);

                if (mostRecentExtension == incumbentExt) {
                    /* Do nothing, we've got the most recent. */
                } else if (mostRecentExtension == newDriverDict) {
                    if (!startupExtensions->setObject(moduleName,
                         newDriverDict)) {

                       /* This is a fatal error, so bail.
                        */
                        IOLog("recordStartupExtensions(): Failed to add "
                            "identifier %s\n",
                            moduleName->getCStringNoCopy());
                        LOG_DELAY();
                        result = false;
                        goto finish;
                    }
                } else /* should be NULL */ {

                   /* This is a nonfatal error, so continue.
                    */
                    IOLog("recordStartupExtensions(): Error comparing "
                        "versions of duplicate extensions %s.\n",
                        moduleName->getCStringNoCopy());
                    LOG_DELAY();
                    continue;
                }
            }


        } else if ( !strncmp(keyValue, BOOTX_MULTIKEXT_PREFIX,
              strlen(BOOTX_MULTIKEXT_PREFIX)) ) {

            mkextExtensions = OSDictionary::withCapacity(10);
            if (!mkextExtensions) {
                IOLog("Error: Couldn't allocate dictionary to unpack "
                    "multi-extension archive.\n");
                LOG_DELAY();
                result = false;
                goto finish;  // allocation failure is fatal for this routine
            }
            if (!readExtensions(propertyDict, keyValue, mkextExtensions)) {
                IOLog("Error: Couldn't unpack multi-extension archive.\n");
                LOG_DELAY();
                continue;
            } else {
                if (!mergeExtensionDictionaries(startupExtensions,
                     mkextExtensions)) {

                    IOLog("Error: Failed to merge new extensions into "
                        "existing set.\n");
                    LOG_DELAY();
                    result = false;
                    goto finish;  // merge error is fatal for this routine
                }
            }
        }

        // Do not release key.

    } /* while ( (key = OSDynamicCast(OSString, ...) ) ) */

    if (!mergeExtensionDictionaries(existingExtensions, startupExtensions)) {
        IOLog("Error: Failed to merge new extensions into existing set.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    } 

    result = addPersonalities(startupExtensions);
    if (!result) {
        IOLog("Error: Failed to add personalities for extensions extracted "
            "from archive.\n");
        LOG_DELAY();
        result = false;
        goto finish;
    }

finish:

    // reused so clear first!
    if (keyIterator) {
        keyIterator->release();
        keyIterator = 0;
    }

    if (!result) {
        IOLog("Error: Failed to record startup extensions.\n");
        LOG_DELAY();
    } else {
#if DEBUG
        keyIterator = OSCollectionIterator::withCollection(
            startupExtensions);

        if (keyIterator) {
            while ( (key = OSDynamicCast(OSString,
                     keyIterator->getNextObject())) ) {

                IOLog("Found extension \"%s\".\n",
                    key->getCStringNoCopy());
                LOG_DELAY();
            }
            keyIterator->release();
            keyIterator = 0;
        }
#endif DEBUG
    }

    if (newDriverDict)     newDriverDict->release();
    if (propertyDict)      propertyDict->release();
    if (bootxMemoryMap)    bootxMemoryMap->release();
    if (mkextExtensions)   mkextExtensions->release();
    if (startupExtensions) startupExtensions->release();

    return result;
}


/*********************************************************************
* This function removes an entry from the dictionary of startup
* extensions. It's used when an extension can't be loaded, for
* whatever reason. For drivers, this allows another matching driver
* to be loaded, so that, for example, a driver for the root device
* can be found.
*********************************************************************/
void removeStartupExtension(const char * extensionName) {
    OSDictionary * startupExtensions = NULL;      // don't release
    OSDictionary * extensionDict = NULL;          // don't release
    OSDictionary * extensionPlist = NULL;         // don't release
    OSDictionary * extensionPersonalities = NULL; // don't release
    OSDictionary * personality = NULL;            // don't release
    OSCollectionIterator * keyIterator = NULL;    // must release
    OSString     * key = NULL;                    // don't release

    startupExtensions = getStartupExtensions();
    if (!startupExtensions) goto finish;


   /* Find the extension's entry in the dictionary of
    * startup extensions.
    */
    extensionDict = OSDynamicCast(OSDictionary,
        startupExtensions->getObject(extensionName));
    if (!extensionDict) goto finish;

    extensionPlist = OSDynamicCast(OSDictionary,
        extensionDict->getObject("plist"));
    if (!extensionPlist) goto finish;

    extensionPersonalities = OSDynamicCast(OSDictionary,
        extensionPlist->getObject("IOKitPersonalities"));
    if (!extensionPersonalities) goto finish;

   /* If it was there, remove it from the catalogue proper
    * by calling removeDrivers(). Pass true for the second
    * argument to trigger a new round of matching, and
    * then remove the extension from the dictionary of startup
    * extensions.
    */
    keyIterator = OSCollectionIterator::withCollection(
        extensionPersonalities);
    if (!keyIterator) {
        IOLog("Error: Couldn't allocate iterator to scan"
            " personalities for %s.\n", extensionName);
        LOG_DELAY();
    }

    while ((key = OSDynamicCast(OSString, keyIterator->getNextObject()))) {
        personality = OSDynamicCast(OSDictionary,
            extensionPersonalities->getObject(key));


        if (personality) {
            gIOCatalogue->removeDrivers(personality, true);
        }
    }

    startupExtensions->removeObject(extensionName);

finish:

    if (keyIterator) keyIterator->release();
    return;
}

/*********************************************************************
* FIXME: This function invalidates the globals gStartupExtensions and
* FIXME: ...gBootLoaderObjects without setting them to NULL. Since
* FIXME: ...the code itself is immediately unloaded, there may not be
* FIXME: ...any reason to worry about that!
*********************************************************************/
void clearStartupExtensionsAndLoaderInfo(void)
{
    OSDictionary * startupExtensions = NULL;  // must release
    OSArray      * bootLoaderObjects = NULL;  // must release

    IORegistryEntry      * bootxMemoryMap = NULL;    // must release
    OSDictionary         * propertyDict = NULL;      // must release
    OSCollectionIterator * keyIterator = NULL;       // must release
    OSString             * key = NULL;               // don't release

   /*****
    * Drop any temporarily held data objects.
    */
    bootLoaderObjects = getBootLoaderObjects();
    if (bootLoaderObjects) {
        bootLoaderObjects->release();
    }

   /****
    * If any "code" entries in driver dictionaries are accompanied
    * by "compressedCode" entries, then those data objects were
    * created based of of kmem_alloc()'ed memory, which must be
    * freed specially.
    */
    startupExtensions = getStartupExtensions();
    if (startupExtensions) {
        keyIterator =
            OSCollectionIterator::withCollection(startupExtensions);
        if (!keyIterator) {
            IOLog("Error: Couldn't allocate iterator for startup "
                "extensions.\n");
            LOG_DELAY();
            goto memory_map;  // bail to the memory_map label
        }

        while ( (key = OSDynamicCast(OSString,
                 keyIterator->getNextObject())) ) {

            OSDictionary * driverDict = 0;
            OSData * codeData = 0;

            driverDict = OSDynamicCast(OSDictionary,
                startupExtensions->getObject(key));
            if (driverDict) {
                codeData = OSDynamicCast(OSData,
                    driverDict->getObject("code"));

                if (codeData &&
                    driverDict->getObject("compressedCode")) {

                    kmem_free(kernel_map,
                       (unsigned int)codeData->getBytesNoCopy(),
                        codeData->getLength());
                }
            }
        }

        keyIterator->release();
        startupExtensions->release();
    }

memory_map:

   /****
    * Go through the device tree's memory map and remove any driver
    * data entries.
    */
    bootxMemoryMap =
        IORegistryEntry::fromPath(
            "/chosen/memory-map", // path
            gIODTPlane            // plane
            );
    // return value is retained so be sure to release it

    if (!bootxMemoryMap) {
        IOLog("Error: Couldn't read booter memory map.\n");
        LOG_DELAY();
        goto finish;
    }

    propertyDict = bootxMemoryMap->dictionaryWithProperties();
    if (!propertyDict) {
        IOLog("Error: Couldn't get property dictionary "
            "from memory map.\n");
        LOG_DELAY();
        goto finish;
    }

    keyIterator = OSCollectionIterator::withCollection(propertyDict);
    if (!keyIterator) {
        IOLog("Error: Couldn't allocate iterator for driver images.\n");
        LOG_DELAY();
        goto finish;
    }

    while ( (key = OSDynamicCast(OSString,
             keyIterator->getNextObject())) ) {

        const char * keyValue = key->getCStringNoCopy();

        if ( !strncmp(keyValue, BOOTX_KEXT_PREFIX,
                  strlen(BOOTX_KEXT_PREFIX)) ||
             !strncmp(keyValue, BOOTX_MULTIKEXT_PREFIX,
                  strlen(BOOTX_MULTIKEXT_PREFIX)) ) {

            OSData            * bootxDriverDataObject = NULL;
            MemoryMapFileInfo * driverInfo = 0;

            bootxDriverDataObject = OSDynamicCast(OSData,
                propertyDict->getObject(keyValue));
            // don't release bootxDriverDataObject

            if (!bootxDriverDataObject) {
                continue;
            }
            driverInfo = (MemoryMapFileInfo *)
                bootxDriverDataObject->getBytesNoCopy(0,
                sizeof(MemoryMapFileInfo));
            IODTFreeLoaderInfo((char *)keyValue,
                (void *)driverInfo->paddr,
                (int)driverInfo->length);
        }
    }

finish:
    if (bootxMemoryMap) bootxMemoryMap->release();
    if (propertyDict)   propertyDict->release();
    if (keyIterator)    keyIterator->release();

    return;
}