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
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
 *
 * Copyright (c) 2016 Apple Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The 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, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/resource.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <limits.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <signal.h>
#include <errno.h>
#include <sysexits.h>
#include <sys/uio.h>
#include <unistd.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/resource.h>
#include <dirent.h>
#include <libgen.h>
#include <pthread.h>
#include <fts.h>

#include <vector>
#include <array>
#include <list>
#include <set>
#include <map>
#include <unordered_set>
#include <algorithm>
#include <fstream>
#include <regex>

#include <spawn.h>

#include <Bom/Bom.h>
#include <Foundation/NSData.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSPropertyList.h>
#include <Foundation/NSString.h>

#include "Defines.h"
#include "Diagnostics.h"
#include "DyldSharedCache.h"
#include "FileUtils.h"
#include "JSONReader.h"
#include "JSONWriter.h"
#include "StringUtils.h"
#include "mrm_shared_cache_builder.h"

#if !__has_feature(objc_arc)
#error The use of libdispatch in this files requires it to be compiled with ARC in order to avoid leaks
#endif

extern char** environ;

static dispatch_queue_t build_queue;

static int runCommandAndWait(Diagnostics& diags, const char* args[])
{
    pid_t pid;
    int   status;
    int   res = posix_spawn(&pid, args[0], nullptr, nullptr, (char**)args, environ);
    if (res != 0)
        diags.error("Failed to spawn %s: %s (%d)", args[0], strerror(res), res);

    do {
        res = waitpid(pid, &status, 0);
    } while (res == -1 && errno == EINTR);
    if (res != -1) {
        if (WIFEXITED(status)) {
            res = WEXITSTATUS(status);
        } else {
            res = -1;
        }
    }

    return res;
}

static void processRoots(std::list<std::string>& roots, const char *tempRootsDir)
{
    std::list<std::string>  processedRoots;
    struct stat             sb;
    int                     res = 0;
    const char*             args[8];

    for (const auto& root : roots) {
        res = stat(root.c_str(), &sb);

        if (res == 0 && S_ISDIR(sb.st_mode)) {
            processedRoots.push_back(root);
            continue;
        }

        char tempRootDir[MAXPATHLEN];
        strlcpy(tempRootDir, tempRootsDir, MAXPATHLEN);
        strlcat(tempRootDir, "/XXXXXXXX", MAXPATHLEN);
        mkdtemp(tempRootDir);

        if (endsWith(root, ".cpio") || endsWith(root, ".cpio.gz") || endsWith(root, ".cpgz") || endsWith(root, ".cpio.bz2") || endsWith(root, ".cpbz2") || endsWith(root, ".pax") || endsWith(root, ".pax.gz") || endsWith(root, ".pgz") || endsWith(root, ".pax.bz2") || endsWith(root, ".pbz2")) {
            args[0] = (char*)"/usr/bin/ditto";
            args[1] = (char*)"-x";
            args[2] = (char*)root.c_str();
            args[3] = tempRootDir;
            args[4] = nullptr;
        } else if (endsWith(root, ".tar")) {
            args[0] = (char*)"/usr/bin/tar";
            args[1] = (char*)"xf";
            args[2] = (char*)root.c_str();
            args[3] = (char*)"-C";
            args[4] = tempRootDir;
            args[5] = nullptr;
        } else if (endsWith(root, ".tar.gz") || endsWith(root, ".tgz")) {
            args[0] = (char*)"/usr/bin/tar";
            args[1] = (char*)"xzf";
            args[2] = (char*)root.c_str();
            args[3] = (char*)"-C";
            args[4] = tempRootDir;
            args[5] = nullptr;
        } else if (endsWith(root, ".tar.bz2")
            || endsWith(root, ".tbz2")
            || endsWith(root, ".tbz")) {
            args[0] = (char*)"/usr/bin/tar";
            args[1] = (char*)"xjf";
            args[2] = (char*)root.c_str();
            args[3] = (char*)"-C";
            args[4] = tempRootDir;
            args[5] = nullptr;
        } else if (endsWith(root, ".zip")) {
            args[0] = (char*)"/usr/bin/ditto";
            args[1] = (char*)"-xk";
            args[2] = (char*)root.c_str();
            args[3] = tempRootDir;
            args[4] = nullptr;
        } else {
            fprintf(stderr, "unknown archive type: %s\n", root.c_str());
            exit(EX_DATAERR);
        }

        Diagnostics diags;
        if (res != runCommandAndWait(diags, args)) {
            fprintf(stderr, "could not expand archive %s: %s (%d) because '%s'\n",
                    root.c_str(), strerror(res), res,
                    diags.hasError() ? diags.errorMessageCStr() : "unknown error");
            exit(EX_DATAERR);
        }
        for (auto& existingRoot : processedRoots) {
            if (existingRoot == tempRootDir)
                continue;
        }

        processedRoots.push_back(tempRootDir);
    }

    roots = processedRoots;
}

static void writeRootList(const std::string& dstRoot, const std::list<std::string>& roots)
{
    if (roots.size() == 0)
        return;

    std::string rootFile = dstRoot + "/roots.txt";
    FILE*       froots = ::fopen(rootFile.c_str(), "w");
    if (froots == NULL)
        return;

    for (auto& root : roots) {
        fprintf(froots, "%s\n", root.c_str());
    }

    ::fclose(froots);
}

struct FilteredCopyOptions {
    Diagnostics*            diags               = nullptr;
    std::set<std::string>*  cachePaths          = nullptr;
    std::set<std::string>*  dylibsFoundInRoots  = nullptr;
};

static BOMCopierCopyOperation filteredCopyIncludingPaths(BOMCopier copier, const char* path, BOMFSObjType type, off_t size)
{
    std::string absolutePath = &path[1];
    const FilteredCopyOptions *userData = (const FilteredCopyOptions*)BOMCopierUserData(copier);

    // Don't copy from the artifact if the dylib is actally in a -root
    if ( userData->dylibsFoundInRoots->count(absolutePath) != 0 ) {
        userData->diags->verbose("Skipping copying dylib from shared cache artifact as it is in a -root: '%s'\n", absolutePath.c_str());
        return BOMCopierSkipFile;
    }

    for (const std::string& cachePath : *userData->cachePaths) {
        if (startsWith(cachePath, absolutePath)) {
            userData->diags->verbose("Copying dylib from shared cache artifact: '%s'\n", absolutePath.c_str());
            return BOMCopierContinue;
        }
    }
    if (userData->cachePaths->count(absolutePath)) {
        userData->diags->verbose("Copying dylib from shared cache artifact: '%s'\n", absolutePath.c_str());
        return BOMCopierContinue;
    }
    return BOMCopierSkipFile;
}

static Disposition stringToDisposition(Diagnostics& diags, const std::string& str) {
    if (diags.hasError())
        return Unknown;
    if (str == "Unknown")
        return Unknown;
    if (str == "InternalDevelopment")
        return InternalDevelopment;
    if (str == "Customer")
        return Customer;
    if (str == "InternalMinDevelopment")
        return InternalMinDevelopment;
    if (str == "SymbolsCache")
        return SymbolsCache;
    return Unknown;
}

static Platform stringToPlatform(Diagnostics& diags, const std::string& str) {
    if (diags.hasError())
        return unknown;
    if (str == "unknown")
        return unknown;
    if ( (str == "macOS") || (str == "osx") )
        return macOS;
    if (str == "iOS")
        return iOS;
    if (str == "tvOS")
        return tvOS;
    if (str == "watchOS")
        return watchOS;
    if (str == "bridgeOS")
        return bridgeOS;
    if (str == "iOSMac")
        return iOSMac;
    if (str == "UIKitForMac")
        return iOSMac;
    if (str == "iOS_simulator")
        return iOS_simulator;
    if (str == "tvOS_simulator")
        return tvOS_simulator;
    if (str == "watchOS_simulator")
        return watchOS_simulator;
    if (str == "driverKit")
        return driverKit;
    if (str == "macOSExclaveKit")
        return macOSExclaveKit;
    if (str == "iOSExclaveKit")
        return iOSExclaveKit;
    if ( std::isdigit(str.front()) ) {
        // Also allow platforms to be specified as an integer
        return (Platform)atoi(str.c_str());
    }
    if ( startsWith(str, "platform") ) {
        std::string_view strView = str;
        strView.remove_prefix(8);
        if ( std::isdigit(strView.front()) ) {
            // Also allow platforms to be specified as an integer
            return (Platform)atoi(strView.data());
        }
    }
    return unknown;
}

static FileFlags stringToFileFlags(Diagnostics& diags, const std::string& str) {
    if (diags.hasError())
        return NoFlags;
    if (str == "NoFlags")
        return NoFlags;
    if (str == "MustBeInCache")
        return MustBeInCache;
    if (str == "ShouldBeExcludedFromCacheIfUnusedLeaf")
        return ShouldBeExcludedFromCacheIfUnusedLeaf;
    if (str == "RequiredClosure")
        return RequiredClosure;
    if (str == "DylibOrderFile")
        return DylibOrderFile;
    if (str == "DirtyDataOrderFile")
        return DirtyDataOrderFile;
    if (str == "ObjCOptimizationsFile")
        return ObjCOptimizationsFile;
    if (str == "SwiftGenericMetadataFile")
        return SwiftGenericMetadataFile;
    return NoFlags;
}

struct SharedCacheBuilderOptions {
    Diagnostics                 diags;
    std::list<std::string>      roots;
    std::string                 dylibCacheDir;
    std::string                 artifactDir;
    std::string                 release;
    bool                        emitDevCaches = true;
    bool                        emitCustomerCaches = true;
    bool                        emitElidedDylibs = true;
    bool                        listConfigs = false;
    bool                        copyRoots = false;
    bool                        debug = false;
    bool                        useMRM = false;
    bool                        timePasses = false;
    bool                        printStats = false;
    bool                        printRemovedFiles = false;
    bool                        emitJSONMap = false;
    std::string                 dstRoot;
    std::string                 buildAllPath;
    std::string                 resultPath;
    std::string                 baselineDifferenceResultPath;
    std::list<std::string>      baselineCacheMapPaths;
    bool                        baselineCopyRoots = false;
    bool                        emitMapFiles = false;
    std::set<std::string>       cmdLineArchs;
};

typedef std::tuple<std::string, std::string, FileFlags, std::string> InputFile;

static void loadMRMFiles(Diagnostics& diags,
                         MRMSharedCacheBuilder* sharedCacheBuilder,
                         const std::vector<InputFile>& inputFiles,
                         std::vector<std::pair<const void*, size_t>>& mappedFiles,
                         const std::set<std::string>& baselineCacheFiles) {

    for (const InputFile& inputFile : inputFiles) {
        const std::string& buildPath   = std::get<0>(inputFile);
        const std::string& runtimePath = std::get<1>(inputFile);
        FileFlags          fileFlags   = std::get<2>(inputFile);
        const std::string& projectName = std::get<3>(inputFile);

        struct stat stat_buf;
        int fd = ::open(buildPath.c_str(), O_RDONLY, 0);
        if (fd == -1) {
            if (baselineCacheFiles.count(runtimePath)) {
                diags.error("can't open file '%s', errno=%d\n", buildPath.c_str(), errno);
                return;
            } else {
                // Don't spam with paths we know will be missing
                if ( buildPath.starts_with("./System/Library/Templates/Data/") )
                    continue;
                diags.verbose("can't open file '%s', errno=%d\n", buildPath.c_str(), errno);
                continue;
            }
        }

        if (fstat(fd, &stat_buf) == -1) {
            if (baselineCacheFiles.count(runtimePath)) {
                diags.error("can't stat open file '%s', errno=%d\n", buildPath.c_str(), errno);
                ::close(fd);
                return;
            } else {
                diags.verbose("can't stat open file '%s', errno=%d\n", buildPath.c_str(), errno);
                ::close(fd);
                continue;
            }
        }

        const void* buffer = mmap(NULL, (size_t)stat_buf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
        if (buffer == MAP_FAILED) {
            diags.error("mmap() for file at %s failed, errno=%d\n", buildPath.c_str(), errno);
            ::close(fd);
        }
        ::close(fd);

        mappedFiles.emplace_back(buffer, (size_t)stat_buf.st_size);

        addFile_v2(sharedCacheBuilder, runtimePath.c_str(), (uint8_t*)buffer, (size_t)stat_buf.st_size, fileFlags, projectName.c_str());
    }
}

static void unloadMRMFiles(std::vector<std::pair<const void*, size_t>>& mappedFiles) {
    for (auto mappedFile : mappedFiles)
        ::munmap((void*)mappedFile.first, mappedFile.second);
}

static ssize_t write64(int fildes, const void *buf, size_t nbyte)
{
    unsigned char* uchars = (unsigned char*)buf;
    ssize_t total = 0;

    while (nbyte)
    {
        /*
         * If we were writing socket- or stream-safe code we'd chuck the
         * entire buf to write(2) and then gracefully re-request bytes that
         * didn't get written. But write(2) will return EINVAL if you ask it to
         * write more than 2^31-1 bytes. So instead we actually need to throttle
         * the input to write.
         *
         * Historically code using write(2) to write to disk will assert that
         * that all of the requested bytes were written. It seems harmless to
         * re-request bytes as one does when writing to streams, with the
         * compromise that we will return immediately when write(2) returns 0
         * bytes written.
         */
        size_t limit = 0x7FFFFFFF;
        size_t towrite = nbyte < limit ? nbyte : limit;
        ssize_t wrote = write(fildes, uchars, towrite);
        if (-1 == wrote)
        {
            return -1;
        }
        else if (0 == wrote)
        {
            break;
        }
        else
        {
            nbyte -= wrote;
            uchars += wrote;
            total += wrote;
        }
    }

    return total;
}

static void printRemovedFiles(bool cacheBuildSuccess, MRMSharedCacheBuilder* sharedCacheBuilder,
                              const SharedCacheBuilderOptions& options)
{
    if ( !cacheBuildSuccess || !options.printRemovedFiles )
        return;

    uint64_t fileResultCount = 0;
    if (const char* const* fileResults = getFilesToRemove(sharedCacheBuilder, &fileResultCount)) {
        for (uint64_t i = 0; i != fileResultCount; ++i)
            printf("Removed: %s\n", fileResults[i]);
    }
}

static void writeMRMResults(bool cacheBuildSuccess, MRMSharedCacheBuilder* sharedCacheBuilder,
                            const SharedCacheBuilderOptions& options)
{
    if (!cacheBuildSuccess) {
        uint64_t errorCount = 0;
        if (const char* const* errors = getErrors(sharedCacheBuilder, &errorCount)) {
            for (uint64_t i = 0, e = errorCount; i != e; ++i) {
                const char* errorMessage = errors[i];
                fprintf(stderr, "ERROR: %s\n", errorMessage);
            }
        }
    }

    // Now emit each cache we generated, or the errors for them.
    uint64_t cacheResultCount = 0;
    if (const CacheResult* const* cacheResults = getCacheResults(sharedCacheBuilder, &cacheResultCount)) {
        for (uint64_t i = 0, e = cacheResultCount; i != e; ++i) {
            const CacheResult& result = *(cacheResults[i]);
            // Always print the warnings if we have roots, even if there are errors
            // But not if we have -build_all, as its too noisy
            bool emitWarnings = (result.numErrors == 0) || !options.roots.empty() || options.debug;
            if ( options.dstRoot.empty() )
                emitWarnings = false;
            if ( emitWarnings ) {
                for (uint64_t warningIndex = 0; warningIndex != result.numWarnings; ++warningIndex) {
                    fprintf(stderr, "[%s] WARNING: %s\n", result.loggingPrefix, result.warnings[warningIndex]);
                }
            }
            if (result.numErrors) {
                for (uint64_t errorIndex = 0; errorIndex != result.numErrors; ++errorIndex) {
                    fprintf(stderr, "[%s] ERROR: %s\n", result.loggingPrefix, result.errors[errorIndex]);
                }
                cacheBuildSuccess = false;
            }
        }
    }

    if (!cacheBuildSuccess) {
        return;
    }

    // If we built caches, then write everything out.
    // TODO: Decide if we should we write any good caches anyway?
    if ( cacheBuildSuccess ) {
        uint64_t fileResultCount = 0;
        if (const FileResult* const* fileResults = getFileResults(sharedCacheBuilder, &fileResultCount)) {
            for (uint64_t i = 0, e = fileResultCount; i != e; ++i) {
                const FileResult* fileResultPtr = fileResults[i];

#if SUPPORT_CACHE_BUILDER_MEMORY_BUFFERS
                assert(fileResultPtr->version == 1);
                const FileResult_v1& fileResult = *(const FileResult_v1*)fileResultPtr;
#else
                assert(fileResultPtr->version == 2);
                const FileResult_v2& fileResult = *(const FileResult_v2*)fileResultPtr;
#endif

                switch (fileResult.behavior) {
                    case AddFile:
                        break;
                    case ChangeFile:
                        continue;
                }

                // Use the fd if we have one
#if !SUPPORT_CACHE_BUILDER_MEMORY_BUFFERS
                if ( fileResult.fd != 0 ) {
                    // If are building all caches, then we don't have a dst_root, and instead
                    // want to just drop this file
                    if ( options.dstRoot.empty() )
                        continue;

                    // Try link() the file, which will fail if crossing file systems,
                    // so fall back to the regular write() path in that case
                    const std::string path = options.dstRoot + fileResult.path;

                    // mkstemp() makes file "rw-------", switch it to "rw-r--r--"
                    ::fchmod(fileResult.fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
                    ::unlink(path.c_str());
                    int result = ::link(fileResult.tempFilePath, path.c_str());
                    if ( result == 0 )
                        continue;
                    // Fall though to regular path
                }
#endif

                if ( (fileResult.data != nullptr) && !options.dstRoot.empty() ) {
                    const std::string path = options.dstRoot + fileResult.path;
                    std::string pathTemplate = path + "-XXXXXX";
                    size_t templateLen = strlen(pathTemplate.c_str())+2;
                    char pathTemplateSpace[templateLen];
                    strlcpy(pathTemplateSpace, pathTemplate.c_str(), templateLen);
                    int fd = mkstemp(pathTemplateSpace);
                    if ( fd != -1 ) {
                        ::ftruncate(fd, fileResult.size);
                        uint64_t writtenSize = write64(fd, fileResult.data, fileResult.size);
                        if ( writtenSize == fileResult.size ) {
                            ::fchmod(fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); // mkstemp() makes file "rw-------", switch it to "rw-r--r--"
                            if ( ::rename(pathTemplateSpace, path.c_str()) == 0) {
                                ::close(fd);
                                continue; // success
                            }
                        }
                        else {
                            fprintf(stderr, "ERROR: could not write file %s\n", pathTemplateSpace);
                            cacheBuildSuccess = false;
                        }
                        ::close(fd);
                        ::unlink(pathTemplateSpace);
                    }
                    else {
                        fprintf(stderr, "ERROR: could not open file %s\n", pathTemplateSpace);
                        cacheBuildSuccess = false;
                    }
                }
            }
        }

        // Give up if we couldn't write the caches
        if (!cacheBuildSuccess) {
            return;
        }
    }

    if ( options.emitJSONMap && !options.dstRoot.empty() ) {
        if (const CacheResult* const* cacheResults = getCacheResults(sharedCacheBuilder, &cacheResultCount)) {
            for (uint64_t i = 0, e = cacheResultCount; i != e; ++i) {
                const CacheResult& result = *(cacheResults[i]);

                const std::string path = options.dstRoot + "/" + result.loggingPrefix + ".json";
                std::string pathTemplate = path + "-XXXXXX";
                size_t templateLen = strlen(pathTemplate.c_str())+2;
                char pathTemplateSpace[templateLen];
                strlcpy(pathTemplateSpace, pathTemplate.c_str(), templateLen);
                int fd = mkstemp(pathTemplateSpace);
                if ( fd != -1 ) {
                    size_t jsonLength = strlen(result.mapJSON) + 1;
                    ::ftruncate(fd, jsonLength);
                    uint64_t writtenSize = write64(fd, result.mapJSON, jsonLength);
                    if ( writtenSize == jsonLength ) {
                        ::fchmod(fd, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); // mkstemp() makes file "rw-------", switch it to "rw-r--r--"
                        if ( ::rename(pathTemplateSpace, path.c_str()) == 0) {
                            ::close(fd);
                            continue; // success
                        }
                    }
                    else {
                        fprintf(stderr, "ERROR: could not write map file %s\n", pathTemplateSpace);
                        cacheBuildSuccess = false;
                    }
                    ::close(fd);
                    ::unlink(pathTemplateSpace);
                }
                else {
                    fprintf(stderr, "ERROR: could not open map file %s\n", pathTemplateSpace);
                    cacheBuildSuccess = false;
                }
            }
        }
    }
}

static void buildCacheFromJSONManifest(Diagnostics& diags, const SharedCacheBuilderOptions& options,
                                       const std::string& jsonManifestPath) {
    dyld3::json::Node manifestNode = dyld3::json::readJSON(diags, jsonManifestPath.c_str());
    if (diags.hasError())
        return;

    // Top level node should be a map of the options, files, and symlinks.
    if (manifestNode.map.empty()) {
        diags.error("Expected map for JSON manifest node\n");
        return;
    }

    // Parse the nodes in the top level manifest node
    const dyld3::json::Node& versionNode          = dyld3::json::getRequiredValue(diags, manifestNode, "version");
    uint64_t manifestVersion                      = dyld3::json::parseRequiredInt(diags, versionNode);
    if (diags.hasError())
        return;

    const uint64_t supportedManifestVersion = 1;
    if (manifestVersion != supportedManifestVersion) {
        diags.error("JSON manfiest version of %lld is unsupported.  Supported version is %lld\n",
                    manifestVersion, supportedManifestVersion);
        return;
    }
    const dyld3::json::Node& buildOptionsNode     = dyld3::json::getRequiredValue(diags, manifestNode, "buildOptions");
    const dyld3::json::Node& filesNode            = dyld3::json::getRequiredValue(diags, manifestNode, "files");
    const dyld3::json::Node* symlinksNode         = dyld3::json::getOptionalValue(diags, manifestNode, "symlinks");

    // Parse the archs
    const dyld3::json::Node& archsNode = dyld3::json::getRequiredValue(diags, buildOptionsNode, "archs");
    if (diags.hasError())
        return;
    if (archsNode.array.empty()) {
        diags.error("Build options archs node is not an array\n");
        return;
    }
    std::set<std::string> jsonArchs;
    const char* archs[archsNode.array.size()];
    uint64_t numArchs = 0;
    for (const dyld3::json::Node& archNode : archsNode.array) {
        const char* archName = dyld3::json::parseRequiredString(diags, archNode).c_str();
        jsonArchs.insert(archName);
        if ( options.cmdLineArchs.empty() || options.cmdLineArchs.count(archName) ) {
            archs[numArchs++] = archName;
        }
    }

    // Check that the command line archs are in the JSON list
    if ( !options.cmdLineArchs.empty() ) {
        for (const std::string& cmdLineArch : options.cmdLineArchs) {
            if ( !jsonArchs.count(cmdLineArch) ) {
                std::string validArchs = "";
                for (const std::string& jsonArch : jsonArchs) {
                    if ( !validArchs.empty() ) {
                        validArchs += ", ";
                    }
                    validArchs += jsonArch;
                }
                diags.error("Command line -arch '%s' is not valid for this device.  Valid archs are (%s)\n", cmdLineArch.c_str(), validArchs.c_str());
                return;
            }
        }
    }

    // Parse the rest of the options node.
    BuildOptions_v3 buildOptions;
    buildOptions.version                            = dyld3::json::parseRequiredInt(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "version"));
    buildOptions.updateName                         = dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "updateName")).c_str();
    buildOptions.deviceName                         = dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "deviceName")).c_str();
    buildOptions.disposition                        = stringToDisposition(diags, dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "disposition")));
    buildOptions.platform                           = stringToPlatform(diags, dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "platform")));
    buildOptions.archs                              = archs;
    buildOptions.numArchs                           = numArchs;
    buildOptions.verboseDiagnostics                 = options.debug;
    buildOptions.isLocallyBuiltCache                = true;

    // optimizeForSize was added in version 2
    buildOptions.optimizeForSize = false;
    if ( buildOptions.version >= 2 ) {
        buildOptions.optimizeForSize                = dyld3::json::parseRequiredBool(diags, dyld3::json::getRequiredValue(diags, buildOptionsNode, "optimizeForSize"));
    }

    // timePasses was added in version 3
    buildOptions.filesRemovedFromDisk = true;
    buildOptions.timePasses = false;
    buildOptions.printStats = false;
    if ( buildOptions.version == 2 ) {
        // HACK:! Bump to version 3 so that timePasses/printStats are picked up.
        buildOptions.version = 3;
        buildOptions.timePasses = options.timePasses;
        buildOptions.printStats = options.printStats;
    } else if ( buildOptions.version >= 3 ) {
        const dyld3::json::Node* filesRemovedNode = dyld3::json::getOptionalValue(diags, buildOptionsNode, "filesRemovedFromDisk");
        const dyld3::json::Node* timePassesNode = dyld3::json::getOptionalValue(diags, buildOptionsNode, "timePasses");
        const dyld3::json::Node* printStatsNode = dyld3::json::getOptionalValue(diags, buildOptionsNode, "printStats");
        if ( filesRemovedNode != nullptr )
            buildOptions.filesRemovedFromDisk = dyld3::json::parseRequiredBool(diags, *filesRemovedNode);
        if ( timePassesNode != nullptr )
            buildOptions.timePasses = dyld3::json::parseRequiredBool(diags, *timePassesNode);
        if ( printStatsNode != nullptr )
            buildOptions.printStats = dyld3::json::parseRequiredBool(diags, *printStatsNode);
    }

    if (diags.hasError())
        return;

    // Override the disposition if we don't want certain caches.
    switch (buildOptions.disposition) {
        case Unknown:
            // Nothing we can do here as we can't assume what caches are built here.
            break;
        case InternalDevelopment:
            if (!options.emitDevCaches && !options.emitCustomerCaches) {
                diags.error("both -no_customer_cache and -no_development_cache passed\n");
                break;
            }
            if (!options.emitDevCaches) {
                // This builds both caches, but we don't want dev
                buildOptions.disposition = Customer;
            }
            if (!options.emitCustomerCaches) {
                // This builds both caches, but we don't want customer
                buildOptions.disposition = InternalMinDevelopment;
            }
            break;
        case Customer:
            if (!options.emitCustomerCaches) {
                diags.error("Cannot request no customer cache for Customer as that is already only a customer cache\n");
            }
            break;
        case InternalMinDevelopment:
            if (!options.emitDevCaches) {
                diags.error("Cannot request no dev cache for InternalMinDevelopment as that is already only a dev cache\n");
            }
            break;
        case SymbolsCache:
            break;
    }

    if (diags.hasError())
        return;

    struct MRMSharedCacheBuilder* sharedCacheBuilder = createSharedCacheBuilder((const BuildOptions_v1*)&buildOptions);

    // Parse the files
    if (filesNode.array.empty()) {
        diags.error("Build options files node is not an array\n");
        return;
    }

    std::vector<InputFile> inputFiles;
    std::set<std::string> dylibsFoundInRoots;
    for (const dyld3::json::Node& fileNode : filesNode.array) {
        std::string path = dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, fileNode, "path")).c_str();
        FileFlags fileFlags     = stringToFileFlags(diags, dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, fileNode, "flags")));

        std::string_view projectName;
        if ( const dyld3::json::Node* projectNode = dyld3::json::getOptionalValue(diags, fileNode, "project") )
            projectName = projectNode->value;

        // We can optionally have a sourcePath entry which is the path to get the source content from instead of the install path
        std::string sourcePath;
        const dyld3::json::Node* sourcePathNode = dyld3::json::getOptionalValue(diags, fileNode, "sourcePath");
        if ( sourcePathNode != nullptr ) {
            if (!sourcePathNode->array.empty()) {
                diags.error("sourcePath node cannot be an array\n");
                return;
            }
            if (!sourcePathNode->map.empty()) {
                diags.error("sourcePath node cannot be a map\n");
                return;
            }
            sourcePath = sourcePathNode->value;
        } else {
            sourcePath = path;
        }

        std::string buildPath = sourcePath;

        // Check if one of the -root's has this path
        bool foundInOverlay = false;
        for (const std::string& overlay : options.roots) {
            struct stat sb;
            std::string filePath = overlay + path;
            if (!stat(filePath.c_str(), &sb)) {
                foundInOverlay = true;
                diags.verbose("Taking '%s' from overlay '%s' instead of dylib cache\n", path.c_str(), overlay.c_str());
                inputFiles.push_back({ filePath, path, fileFlags, "" });
                dylibsFoundInRoots.insert(path);
                break;
            }
        }

        if (foundInOverlay)
            continue;

        // Build paths are relative to the build artifact root directory.
        switch (fileFlags) {
            case NoFlags:
            case MustBeInCache:
            case ShouldBeExcludedFromCacheIfUnusedLeaf:
            case RequiredClosure:
            case DylibOrderFile:
            case DirtyDataOrderFile:
            case ObjCOptimizationsFile:
            case SwiftGenericMetadataFile:
                buildPath = "." + buildPath;
                break;
        }
        inputFiles.push_back({ buildPath, path, fileFlags, std::string(projectName) });
    }

    if (diags.hasError())
        return;

    // Parse the baseline from the map(s) if we have it
    std::set<std::string> unionBaselineDylibs;
    for (const std::string& baselineCacheMapPath : options.baselineCacheMapPaths) {
        dyld3::json::Node mapNode = dyld3::json::readJSON(diags, baselineCacheMapPath.c_str());
        if (diags.hasError())
            return;

        // Top level node should be a map of the version and files
        if (mapNode.map.empty()) {
            diags.error("Expected map for JSON cache map node\n");
            return;
        }

        // Parse the nodes in the top level manifest node
        const dyld3::json::Node& versionMapNode  = dyld3::json::getRequiredValue(diags, mapNode, "version");
        uint64_t mapVersion                      = dyld3::json::parseRequiredInt(diags, versionMapNode);
        if (diags.hasError())
            return;

        const uint64_t supportedMapVersion = 1;
        if (mapVersion != supportedMapVersion) {
            diags.error("JSON map version of %lld is unsupported.  Supported version is %lld\n",
                        mapVersion, supportedMapVersion);
            return;
        }

        // Parse the images
        const dyld3::json::Node& imagesNode = dyld3::json::getRequiredValue(diags, mapNode, "images");
        if (diags.hasError())
            return;
        if (imagesNode.array.empty()) {
            diags.error("Images node is not an array\n");
            return;
        }

        for (const dyld3::json::Node& imageNode : imagesNode.array) {
            const dyld3::json::Node& pathNode = dyld3::json::getRequiredValue(diags, imageNode, "path");
            if (pathNode.value.empty()) {
                diags.error("Image path node is not a string\n");
                return;
            }
            unionBaselineDylibs.insert(pathNode.value);
        }
    }

    std::vector<std::pair<const void*, size_t>> mappedFiles;
    {
        uint64_t startTimeNanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);
        loadMRMFiles(diags, sharedCacheBuilder, inputFiles, mappedFiles, unionBaselineDylibs);
        uint64_t endTimeNanos = clock_gettime_nsec_np(CLOCK_UPTIME_RAW);

        if ( options.timePasses ) {
            uint64_t timeMillis = (endTimeNanos - startTimeNanos) / 1000000;
            fprintf(stderr, "loadMRMFiles: time = %lldms\n", timeMillis);
        }
    }

    if (diags.hasError())
        return;

    // Parse the symlinks if we have them
    if (symlinksNode) {
        if (symlinksNode->array.empty()) {
            diags.error("Build options symlinks node is not an array\n");
            return;
        }
        for (const dyld3::json::Node& symlinkNode : symlinksNode->array) {
            std::string fromPath = dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, symlinkNode, "path")).c_str();
            const std::string& toPath   = dyld3::json::parseRequiredString(diags, dyld3::json::getRequiredValue(diags, symlinkNode, "target")).c_str();
            addSymlink(sharedCacheBuilder, fromPath.c_str(), toPath.c_str());
        }
    }

    if (diags.hasError())
        return;

    // Don't create a directory if we are skipping writes, which means we have no dstRoot set
    if (!options.dstRoot.empty()) {
        if ( buildOptions.platform == macOS ) {
            (void)mkpath_np((options.dstRoot + MACOSX_MRM_DYLD_SHARED_CACHE_DIR).c_str(), 0755);
        } else if (buildOptions.platform == driverKit ) {
            (void)mkpath_np((options.dstRoot + DRIVERKIT_DYLD_SHARED_CACHE_DIR).c_str(), 0755);
        } else if ( dyld3::MachOFile::isExclaveKitPlatform((dyld3::Platform)buildOptions.platform) ) {
            (void)mkpath_np((options.dstRoot + EXCLAVEKIT_DYLD_SHARED_CACHE_DIR).c_str(), 0755);
        } else if ( buildOptions.disposition == SymbolsCache ) {
            // symbols cache always uses /System/Library/dyld, even on iOS
            (void)mkpath_np((options.dstRoot + MACOSX_MRM_DYLD_SHARED_CACHE_DIR).c_str(), 0755);
        } else {
            (void)mkpath_np((options.dstRoot + IPHONE_DYLD_SHARED_CACHE_DIR).c_str(), 0755);
        }
    }

    // Actually build the cache.
    bool cacheBuildSuccess = runSharedCacheBuilder(sharedCacheBuilder);

    // Compare this cache to the baseline cache and see if we have any roots to copy over
    if (!options.baselineDifferenceResultPath.empty() || options.baselineCopyRoots) {
        std::set<std::string> dylibsInNewCaches;
        std::set<std::string> simulatorSupportDylibs;
        if (cacheBuildSuccess) {
            uint64_t fileResultCount = 0;
            if (const char* const* fileResults = getFilesToRemove(sharedCacheBuilder, &fileResultCount)) {
                for (uint64_t i = 0; i != fileResultCount; ++i)
                    dylibsInNewCaches.insert(fileResults[i]);
            }
            if ( buildOptions.platform == Platform::macOS ) {
                //FIXME: We should be using MH_SIM_SUPPORT now that all the relevent binaries include it in their headers
                // macOS has to leave the simulator support binaries on disk
                // It won't put them in the result of getFilesToRemove() so we need to manually add them
                simulatorSupportDylibs.insert("/usr/lib/system/libsystem_kernel.dylib");
                simulatorSupportDylibs.insert("/usr/lib/system/libsystem_platform.dylib");
                simulatorSupportDylibs.insert("/usr/lib/system/libsystem_pthread.dylib");
            }
        }

        if (options.baselineCopyRoots) {
            // Work out the set of dylibs in the old caches but not the new ones
            std::set<std::string> dylibsMissingFromNewCaches;
            for (const std::string& baselineDylib : unionBaselineDylibs) {
                if ( !dylibsInNewCaches.count(baselineDylib) && !simulatorSupportDylibs.count(baselineDylib))
                    dylibsMissingFromNewCaches.insert(baselineDylib);
            }

            if (!dylibsMissingFromNewCaches.empty()) {
                BOMCopier copier = BOMCopierNewWithSys(BomSys_default());
                FilteredCopyOptions userData = { &diags, &dylibsMissingFromNewCaches, &dylibsFoundInRoots };
                BOMCopierSetUserData(copier, (void*)&userData);
                BOMCopierSetCopyFileStartedHandler(copier, filteredCopyIncludingPaths);
                std::string dylibCacheRootDir = realFilePath(options.dylibCacheDir);
                if (dylibCacheRootDir == "") {
                    fprintf(stderr, "Could not find dylib Root directory to copy baseline roots from\n");
                    exit(EX_NOINPUT);
                }
                BOMCopierCopy(copier, dylibCacheRootDir.c_str(), options.dstRoot.c_str());
                BOMCopierFree(copier);

                for (const std::string& dylibMissingFromNewCache : dylibsMissingFromNewCaches) {
                    diags.verbose("Dylib missing from new cache: '%s'\n", dylibMissingFromNewCache.c_str());
                }
            }
        }

        if (!options.baselineDifferenceResultPath.empty()) {
            auto cppToObjStr = [](const std::string& str) {
                return [NSString stringWithUTF8String:str.c_str()];
            };

            // Work out the set of dylibs in the cache and taken from any -roots
            NSMutableArray<NSString*>* dylibsFromRoots = [NSMutableArray array];
            for (auto& root : options.roots) {
                for (const std::string& dylibInstallName : dylibsInNewCaches) {
                    struct stat sb;
                    std::string filePath = root + "/" + dylibInstallName;
                    if (!stat(filePath.c_str(), &sb)) {
                        [dylibsFromRoots addObject:cppToObjStr(dylibInstallName)];
                    }
                }
            }

            // Work out the set of dylibs in the new cache but not in the baseline cache.
            NSMutableArray<NSString*>* dylibsMissingFromBaselineCache = [NSMutableArray array];
            for (const std::string& newDylib : dylibsInNewCaches) {
                if (!unionBaselineDylibs.count(newDylib))
                    [dylibsMissingFromBaselineCache addObject:cppToObjStr(newDylib)];
            }

            NSMutableDictionary* cacheDict = [[NSMutableDictionary alloc] init];
            cacheDict[@"root-paths-in-cache"] = dylibsFromRoots;
            cacheDict[@"device-paths-to-delete"] = dylibsMissingFromBaselineCache;

            NSError* error = nil;
            NSData*  outData = [NSPropertyListSerialization dataWithPropertyList:cacheDict
                                                                          format:NSPropertyListBinaryFormat_v1_0
                                                                         options:0
                                                                           error:&error];
            (void)[outData writeToFile:cppToObjStr(options.baselineDifferenceResultPath) atomically:YES];
        }
    }

    printRemovedFiles(cacheBuildSuccess, sharedCacheBuilder, options);

    writeMRMResults(cacheBuildSuccess, sharedCacheBuilder, options);

    destroySharedCacheBuilder(sharedCacheBuilder);

    unloadMRMFiles(mappedFiles);

    // On failure, add an error to the diagnostic so that the caller can see that the build failed
    if ( !cacheBuildSuccess ) {
        diags.error("see other errors");
    }
}

static std::string realPathOrExit(const char* argName, const char* argValue)
{
    std::string realpath = realPath(argValue);
    if ( realpath.empty() || !fileExists(realpath) ) {
        fprintf(stderr, "%s path doesn't exist: %s\n", argName, argValue);
        exit(EX_NOINPUT);
    }
    return realpath;
}

static const char* leafName(std::string_view str)
{
    const char* start = strrchr(str.data(), '/');
    if ( start != nullptr )
        return &start[1];
    else
        return str.data();
}

int main(int argc, const char* argv[])
{
    SharedCacheBuilderOptions options;
    std::string jsonManifestPath;
    char* tempRootsDir = strdup("/tmp/dyld_shared_cache_builder.XXXXXX");

    mkdtemp(tempRootsDir);

    for (int i = 1; i < argc; ++i) {
        const char* arg = argv[i];
        if (arg[0] == '-') {
            if (strcmp(arg, "-debug") == 0) {
                options.debug = true;
            } else if (strcmp(arg, "-list_configs") == 0) {
                options.listConfigs = true;
            } else if (strcmp(arg, "-root") == 0) {
                std::string realpath = realPathOrExit("-root", argv[++i]);
                if ( std::find(options.roots.begin(), options.roots.end(), realpath) == options.roots.end() ) {
                    // Push roots on to the front so that each -root overrides previous entries
                    options.roots.push_front(realpath);
                }
            } else if (strcmp(arg, "-copy_roots") == 0) {
                options.copyRoots = true;
            } else if (strcmp(arg, "-dylib_cache") == 0) {
                options.dylibCacheDir = realPathOrExit("-dylib_cache", argv[++i]);
            } else if (strcmp(arg, "-artifact") == 0) {
                options.artifactDir = realPathOrExit("-artifact", argv[++i]);
            } else if (strcmp(arg, "-no_overflow_dylibs") == 0) {
                options.emitElidedDylibs = false;
            } else if (strcmp(arg, "-no_development_cache") == 0) {
                options.emitDevCaches = false;
            } else if (strcmp(arg, "-development_cache") == 0) {
                options.emitDevCaches = true;
            } else if (strcmp(arg, "-no_customer_cache") == 0) {
                options.emitCustomerCaches = false;
            } else if (strcmp(arg, "-customer_cache") == 0) {
                options.emitCustomerCaches = true;
            } else if (strcmp(arg, "-overflow_dylibs") == 0) {
                options.emitElidedDylibs = true;
            } else if (strcmp(arg, "-mrm") == 0) {
                options.useMRM = true;
            } else if (strcmp(arg, "-time-passes") == 0) {
                options.timePasses = true;
            } else if (strcmp(arg, "-stats") == 0) {
                options.printStats = true;
            } else if (strcmp(arg, "-removed_files") == 0) {
                options.printRemovedFiles = true;
            } else if (strcmp(arg, "-emit_json") == 0) {
                // unused
            } else if (strcmp(arg, "-emit_json_map") == 0) {
                options.emitJSONMap = true;
            } else if (strcmp(arg, "-json_manifest") == 0) {
                jsonManifestPath = realPathOrExit("-json_manifest", argv[++i]);
            } else if (strcmp(arg, "-build_all") == 0) {
                options.buildAllPath = realPathOrExit("-build_all", argv[++i]);
            } else if (strcmp(arg, "-dst_root") == 0) {
                options.dstRoot = realPath(argv[++i]);
            } else if (strcmp(arg, "-release") == 0) {
                options.release = argv[++i];
            } else if (strcmp(arg, "-results") == 0) {
                options.resultPath = realPath(argv[++i]);
            } else if (strcmp(arg, "-baseline_diff_results") == 0) {
                options.baselineDifferenceResultPath = realPath(argv[++i]);
            } else if (strcmp(arg, "-baseline_copy_roots") == 0) {
                options.baselineCopyRoots = true;
            } else if (strcmp(arg, "-baseline_cache_map") == 0) {
                std::string path = realPathOrExit("-baseline_cache_map", argv[++i]);
                options.baselineCacheMapPaths.push_back(path);
            } else if (strcmp(arg, "-arch") == 0) {
                if ( ++i < argc ) {
                    options.cmdLineArchs.insert(argv[i]);
                }
                else {
                    fprintf(stderr, "-arch missing architecture name");
                    exit(EX_USAGE);
                }
            } else if (strcmp(arg, "-help") == 0) {
                // no usage() to show, but having this allows clients to probe
                // whether flags are supported by seeing if `-flag2check -help`
                // exits with EXIT_SUCCESS or EX_USAGE
                exit(EXIT_SUCCESS);
            } else {
                //usage();
                fprintf(stderr, "unknown option: %s\n", arg);
                exit(EX_USAGE);
            }
        } else {
            fprintf(stderr, "unknown option: %s\n", arg);
            exit(EX_USAGE);
        }
    }
    (void)options.emitElidedDylibs; // not implemented yet

    time_t mytime = time(0);
    fprintf(stderr, "Started: %s", asctime(localtime(&mytime)));
    processRoots(options.roots, tempRootsDir);

    struct rlimit rl = { OPEN_MAX, OPEN_MAX };
    (void)setrlimit(RLIMIT_NOFILE, &rl);

    if (options.dylibCacheDir.empty() && options.artifactDir.empty() && options.release.empty()) {
        fprintf(stderr, "you must specify either -dylib_cache, -artifact or -release\n");
        exit(EX_USAGE);
    } else if (!options.dylibCacheDir.empty() && !options.release.empty()) {
        fprintf(stderr, "you may not use -dylib_cache and -release at the same time\n");
        exit(EX_USAGE);
    } else if (!options.dylibCacheDir.empty() && !options.artifactDir.empty()) {
        fprintf(stderr, "you may not use -dylib_cache and -artifact at the same time\n");
        exit(EX_USAGE);
    }

    if (jsonManifestPath.empty() && options.buildAllPath.empty()) {
        fprintf(stderr, "Must specify a -json_manifest path OR a -build_all path\n");
        exit(EX_USAGE);
    }

    if (!options.buildAllPath.empty()) {
        if (!options.dstRoot.empty()) {
            fprintf(stderr, "Cannot combine -dst_root and -build_all\n");
            exit(EX_USAGE);
        }
        if (!jsonManifestPath.empty()) {
            fprintf(stderr, "Cannot combine -json_manifest and -build_all\n");
            exit(EX_USAGE);
        }
        if (!options.baselineDifferenceResultPath.empty()) {
            fprintf(stderr, "Cannot combine -baseline_diff_results and -build_all\n");
            exit(EX_USAGE);
        }
        if (options.baselineCopyRoots) {
            fprintf(stderr, "Cannot combine -baseline_copy_roots and -build_all\n");
            exit(EX_USAGE);
        }
        if (!options.baselineCacheMapPaths.empty()) {
            fprintf(stderr, "Cannot combine -baseline_cache_map and -build_all\n");
            exit(EX_USAGE);
        }
    } else if (!options.listConfigs) {
        if (options.dstRoot.empty()) {
            fprintf(stderr, "Must specify a valid -dst_root OR -list_configs\n");
            exit(EX_USAGE);
        }

        if (jsonManifestPath.empty()) {
            fprintf(stderr, "Must specify a -json_manifest path OR -list_configs\n");
            exit(EX_USAGE);
        }
    }

    // Some options don't work with a JSON manifest
    if (!jsonManifestPath.empty()) {
        if (!options.resultPath.empty()) {
            fprintf(stderr, "Cannot use -results with -json_manifest\n");
            exit(EX_USAGE);
        }
        if (!options.baselineDifferenceResultPath.empty() && options.baselineCacheMapPaths.empty()) {
            fprintf(stderr, "Must use -baseline_cache_map with -baseline_diff_results when using -json_manifest\n");
            exit(EX_USAGE);
        }
        if (options.baselineCopyRoots && options.baselineCacheMapPaths.empty()) {
            fprintf(stderr, "Must use -baseline_cache_map with -baseline_copy_roots when using -json_manifest\n");
            exit(EX_USAGE);
        }
    } else {
        if (!options.baselineCacheMapPaths.empty()) {
            fprintf(stderr, "Cannot use -baseline_cache_map without -json_manifest\n");
            exit(EX_USAGE);
        }
    }

    if (!options.baselineCacheMapPaths.empty()) {
        if (options.baselineDifferenceResultPath.empty() && options.baselineCopyRoots) {
            fprintf(stderr, "Must use -baseline_cache_map with -baseline_diff_results or -baseline_copy_roots\n");
            exit(EX_USAGE);
        }
    }

    // Find all the JSON files if we use -build_all
    __block std::vector<std::string> jsonPaths;
    if (!options.buildAllPath.empty()) {
        struct stat stat_buf;
        if (stat(options.buildAllPath.c_str(), &stat_buf) != 0) {
            fprintf(stderr, "Could not find -build_all path '%s'\n", options.buildAllPath.c_str());
            exit(EX_NOINPUT);
        }

        if ( (stat_buf.st_mode & S_IFMT) != S_IFDIR ) {
            fprintf(stderr, "-build_all path is not a directory '%s'\n", options.buildAllPath.c_str());
            exit(EX_DATAERR);
        }

        auto processFile = ^(const std::string& path, const struct stat& statBuf) {
            if ( !endsWith(path, ".json") )
                return;

            jsonPaths.push_back(path);
        };

        iterateDirectoryTree("", options.buildAllPath,
                             ^(const std::string& dirPath) { return false; },
                             processFile, true /* process files */, true /* recurse */);

        if (jsonPaths.empty()) {
            fprintf(stderr, "Didn't find any .json files inside -build_all path: %s\n", options.buildAllPath.c_str());
            exit(EX_DATAERR);
        }

        if (options.listConfigs) {
            for (const std::string& path : jsonPaths) {
                fprintf(stderr, "Found config: %s\n", path.c_str());
            }
            exit(EXIT_SUCCESS);
        }
    }

    if (!options.artifactDir.empty()) {
        // Find the dylib cache dir from inside the artifact dir
        struct stat stat_buf;
        if (stat(options.artifactDir.c_str(), &stat_buf) != 0) {
            fprintf(stderr, "Could not find artifact path '%s'\n", options.artifactDir.c_str());
            exit(EX_NOINPUT);
        }
        std::string dir = options.artifactDir + "/AppleInternal/Developer/DylibCaches";
        if (stat(dir.c_str(), &stat_buf) != 0) {
            fprintf(stderr, "Could not find artifact path '%s'\n", dir.c_str());
            exit(EX_DATAERR);
        }

        if (!options.release.empty()) {
            // Use the given release
            options.dylibCacheDir = dir + "/" + options.release + ".dlc";
        } else {
            // Find a release directory
            __block std::vector<std::string> subDirectories;
            iterateDirectoryTree("", dir, ^(const std::string& dirPath) {
                subDirectories.push_back(dirPath);
                return false;
            }, nullptr, false, false);

            if (subDirectories.empty()) {
                fprintf(stderr, "Could not find dlc subdirectories inside '%s'\n", dir.c_str());
                exit(EX_DATAERR);
            }

            if (subDirectories.size() > 1) {
                fprintf(stderr, "Found too many subdirectories inside artifact path '%s'.  Use -release to select one\n", dir.c_str());
                exit(EX_DATAERR);
            }

            options.dylibCacheDir = subDirectories.front();
        }
    }

    if (options.dylibCacheDir.empty()) {
        options.dylibCacheDir = std::string("/AppleInternal/Developer/DylibCaches/") + options.release + ".dlc";
    }

    //Move into the dir so we can use relative path manifests
    if ( int result = chdir(options.dylibCacheDir.c_str()); result == -1 ) {
        fprintf(stderr, "Couldn't cd in to dylib cache directory of '%s' because: %s\n",
                options.dylibCacheDir.c_str(), strerror(errno));
    }

    if (!options.buildAllPath.empty()) {
        bool requiresConcurrencyLimit = false;
        dispatch_semaphore_t concurrencyLimit = NULL;
        // Try build 1 cache per 8GB of RAM
        uint64_t memSize = 0;
        size_t sz = sizeof(memSize);
        if ( sysctlbyname("hw.memsize", &memSize, &sz, NULL, 0) == 0 ) {
            uint64_t maxThreads = std::max(memSize / 0x200000000ULL, 1ULL);
            fprintf(stderr, "Detected %lldGb or less of memory, limiting concurrency to %lld threads\n",
                    memSize / (1 << 30), maxThreads);
            requiresConcurrencyLimit = true;
            concurrencyLimit = dispatch_semaphore_create(maxThreads);
        }

        __block int finishedCount = 0;
        std::atomic_bool failedToBuildCache = { false };
        __block auto& failedToBuildCacheRef = failedToBuildCache;
        dispatch_apply(jsonPaths.size(), DISPATCH_APPLY_AUTO, ^(size_t index) {
            // Horrible hack to limit concurrency in low spec build machines.
            if (requiresConcurrencyLimit) { dispatch_semaphore_wait(concurrencyLimit, DISPATCH_TIME_FOREVER); }

            const std::string& jsonPath = jsonPaths[index];
            Diagnostics diags(options.debug);
            buildCacheFromJSONManifest(diags, options, jsonPath);

            if (diags.hasError()) {
                fprintf(stderr, "dyld_shared_cache_builder: error: %s\n", diags.errorMessage().c_str());
                failedToBuildCacheRef = true;
            }

            time_t endTime = time(0);
            std::string timeString = asctime(localtime(&endTime));
            timeString.pop_back();
            fprintf(stderr, "Finished[% 4d/% 4d]: %s %s\n",
                    ++finishedCount, (int)jsonPaths.size(), timeString.c_str(), leafName(jsonPath));

            if (requiresConcurrencyLimit) { dispatch_semaphore_signal(concurrencyLimit); }
        });

        if ( failedToBuildCacheRef )
            return EXIT_FAILURE;
    } else {
        Diagnostics diags(options.debug);
        buildCacheFromJSONManifest(diags, options, jsonManifestPath);

        if (diags.hasError()) {
            fprintf(stderr, "dyld_shared_cache_builder: error: %s\n", diags.errorMessage().c_str());
            return EXIT_FAILURE;
        }
    }

    Diagnostics diags;
    const char* args[8];
    args[0] = (char*)"/bin/rm";
    args[1] = (char*)"-rf";
    args[2] = (char*)tempRootsDir;
    args[3] = nullptr;
    (void)runCommandAndWait(diags, args);

    if (diags.hasError()) {
        // errors from our final rm -rf should just be warnings
        fprintf(stderr, "dyld_shared_cache_builder: warning: %s\n", diags.errorMessage().c_str());
    }

    for (const std::string& warn : diags.warnings()) {
        fprintf(stderr, "dyld_shared_cache_builder: warning: %s\n", warn.c_str());
    }

    // Finally, write the roots.txt to tell us which roots we pulled in
    if (!options.dstRoot.empty())
        writeRootList(options.dstRoot + "/System/Library/Caches/com.apple.dyld", options.roots);

    return EXIT_SUCCESS;
}