Loading...
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
/* Mach virtual memory unit tests
 *
 * The main goal of this code is to facilitate the construction,
 * running, result logging and clean up of a test suite, taking care
 * of all the scaffolding. A test suite is a sequence of very targeted
 * unit tests, each running as a separate process to isolate its
 * address space.
 * A unit test is abstracted as a unit_test_t structure, consisting of
 * a test function and a logging identifier. A test suite is a suite_t
 * structure, consisting of an unit_test_t array, fixture set up and
 * tear down functions.
 * Test suites are created dynamically. Each of its unit test runs in
 * its own fork()d process, with the fixture set up and tear down
 * running before and after each test. The parent process will log a
 * pass result if the child exits normally, and a fail result in any
 * other case (non-zero exit status, abnormal signal). The suite
 * results are then aggregated and logged after the [SUMMARY] keyword,
 * and finally the test suite is destroyed.
 * The included test suites cover the Mach memory allocators,
 * mach_vm_allocate() and mach_vm_map() with various options, and
 * mach_vm_deallocate(), mach_vm_read(), mach_vm_write(),
 * mach_vm_protect(), mach_vm_copy().
 *
 * Author: Renaud Dreyer (rdreyer@apple.com)
 *
 * Transformed to libdarwintest by Tristan Ye (tristan_ye@apple.com) */

#include <darwintest.h>

#include <stdlib.h>
#include <ctype.h>
#include <inttypes.h>
#include <stdio.h>
#include <math.h>
#include <errno.h>
#include <signal.h>
#include <getopt.h>
#include <mach/mach.h>
#include <mach/mach_init.h>
#include <mach/mach_vm.h>
#include <sys/sysctl.h>
#include <time.h>
#include <stdbool.h>

T_GLOBAL_META(
	T_META_NAMESPACE("xnu.vm"),
	T_META_RADAR_COMPONENT_NAME("xnu"),
	T_META_RADAR_COMPONENT_VERSION("VM"));

/**************************/
/**************************/
/* Unit Testing Framework */
/**************************/
/**************************/

/*********************/
/* Private interface */
/*********************/

/* Type for test, fixture set up and fixture tear down functions. */
typedef void (*test_fn_t)();

/* Unit test structure. */
typedef struct {
	const char * name;
	test_fn_t test;
	int expected_signal;
} unit_test_t;

/* Test suite structure. */
typedef struct {
	const char * name;
	int numoftests;
	test_fn_t set_up;
	unit_test_t * tests;
	test_fn_t tear_down;
} suite_t;

int _quietness        = 0;
int _expected_signal  = 0;
int _expected_vm_exc_guard_signal = 0;

struct {
	uintmax_t numoftests;
	uintmax_t passed_tests;
} results = {0, 0};

#define logr(format, ...) \
	do { \
	        if (_quietness <= 1) { \
	                T_LOG(format, ## __VA_ARGS__); \
	        } \
	} while (0)

#define logv(format, ...) \
	do { \
	        if (_quietness == 0) { \
	                T_LOG(format, ## __VA_ARGS__); \
	        } \
	} while (0)

static suite_t *
create_suite(const char * name, int numoftests, test_fn_t set_up, unit_test_t * tests, test_fn_t tear_down)
{
	suite_t * suite = (suite_t *)malloc(sizeof(suite_t));
	T_QUIET; T_WITH_ERRNO; T_ASSERT_NOTNULL(suite, "malloc()");

	suite->name       = name;
	suite->numoftests = numoftests;
	suite->set_up     = set_up;
	suite->tests      = tests;
	suite->tear_down  = tear_down;
	return suite;
}

static void
destroy_suite(suite_t * suite)
{
	free(suite);
}

static void
log_suite_info(suite_t * suite)
{
	logr("[TEST] %s", suite->name);
	logr("Number of tests: %d", suite->numoftests);
}

static void
log_suite_results(suite_t * suite, int passed_tests)
{
	results.numoftests += (uintmax_t)suite->numoftests;
	results.passed_tests += (uintmax_t)passed_tests;
}

static void
log_test_info(unit_test_t * unit_test, unsigned test_num)
{
	if (unit_test->expected_signal) {
		logr("[BEGIN] #%04d: %s, SIGNAL(%d) expected", test_num, unit_test->name, unit_test->expected_signal);
	} else {
		logr("[BEGIN] #%04d: %s", test_num, unit_test->name);
	}
}

static void
log_test_result(unit_test_t * unit_test, boolean_t test_passed, unsigned test_num)
{
	logr("[%s] #%04d: %s", test_passed ? "PASS" : "FAIL", test_num, unit_test->name);
}

/* Run a test with fixture set up and teardown, while enforcing the
 * time out constraint. */
static void
run_test(suite_t * suite, unit_test_t * unit_test, unsigned test_num)
{
	log_test_info(unit_test, test_num);

	suite->set_up();
	unit_test->test();
	suite->tear_down();
}

/* Expected signal for a test, default is 0. */
void
set_expected_signal(int signal)
{
	_expected_signal = signal;
}

int
get_expected_signal()
{
	return _expected_signal;
}

/* Check a child return status. */
static boolean_t
child_terminated_normally(int child_status)
{
	boolean_t normal_exit = FALSE;

	if (WIFEXITED(child_status)) {
		int exit_status = WEXITSTATUS(child_status);
		if (exit_status) {
			T_LOG("Child process unexpectedly exited with code %d.",
			    exit_status);
		} else if (!_expected_signal) {
			normal_exit = TRUE;
		} else {
			T_LOG(
				"Child process unexpectedly exited with zero, "
				"where signal %d is expected.", _expected_signal);
		}
	} else if (WIFSIGNALED(child_status)) {
		int signal = WTERMSIG(child_status);
		if (signal == _expected_signal ||
		    (_expected_signal == -1 && (signal == SIGBUS || signal == SIGSEGV || signal == SIGKILL))) {
			if (_quietness <= 0) {
				T_LOG("Child process died with expected signal "
				    "%d.", signal);
			}
			normal_exit = TRUE;
		} else {
			T_LOG("Child process unexpectedly died with signal %d.",
			    signal);
		}
	} else {
		T_LOG("Child process unexpectedly did not exit nor die");
	}

	return normal_exit;
}

/* Run a test in its own process, and report the result. */
static boolean_t
child_test_passed(suite_t * suite, unit_test_t * unit_test)
{
	int test_status;
	static unsigned test_num = 0;
	boolean_t use_default_expected_signal = FALSE;

	test_num++;

	pid_t test_pid = fork();
	T_QUIET; T_ASSERT_POSIX_SUCCESS(test_pid, "fork()");
	if (!test_pid) {
		run_test(suite, unit_test, test_num);
		exit(0);
	}
	while (waitpid(test_pid, &test_status, 0) != test_pid) {
		continue;
	}

	/*
	 * Allow overriding unit_test's default expected signal
	 */
	if ((get_expected_signal() == 0) &&
	    (unit_test->expected_signal != 0)) {
		set_expected_signal(unit_test->expected_signal);
		use_default_expected_signal = TRUE;
	}
	boolean_t test_result = child_terminated_normally(test_status);
	log_test_result(unit_test, test_result, test_num);
	if (use_default_expected_signal) {
		set_expected_signal(0);
	}

	return test_result;
}

/* Run each test in a suite, and report the results. */
static int
count_passed_suite_tests(suite_t * suite)
{
	int passed_tests = 0;
	int i;

	for (i = 0; i < suite->numoftests; i++) {
		passed_tests += child_test_passed(suite, &(suite->tests[i]));
	}
	return passed_tests;
}

/********************/
/* Public interface */
/********************/

#define DEFAULT_QUIETNESS    0 /* verbose */
#define RESULT_ERR_QUIETNESS 1 /* result and error */
#define ERROR_ONLY_QUIETNESS 2 /* error only */

#define run_suite(set_up, tests, tear_down, ...) \
	_run_suite((sizeof(tests) / sizeof(tests[0])), (set_up), (tests), (tear_down), __VA_ARGS__)

typedef unit_test_t UnitTests[];

void _run_suite(int numoftests, test_fn_t set_up, UnitTests tests, test_fn_t tear_down, const char * format, ...)
__printflike(5, 6);

void
_run_suite(int numoftests, test_fn_t set_up, UnitTests tests, test_fn_t tear_down, const char * format, ...)
{
	va_list ap;
	char * name;

	va_start(ap, format);
	T_QUIET; T_ASSERT_POSIX_SUCCESS(vasprintf(&name, format, ap), "vasprintf()");
	va_end(ap);
	suite_t * suite = create_suite(name, numoftests, set_up, tests, tear_down);
	log_suite_info(suite);
	log_suite_results(suite, count_passed_suite_tests(suite));
	free(name);
	destroy_suite(suite);
}

/* Setters and getters for various test framework global
 * variables. Should only be used outside of the test, set up and tear
 * down functions. */

/* Logging verbosity. */
void
set_quietness(int value)
{
	_quietness = value;
}

int
get_quietness()
{
	return _quietness;
}

/* For fixture set up and tear down functions, and units tests. */
void
do_nothing()
{
}

void
log_aggregated_results()
{
	T_LOG("[SUMMARY] Aggregated Test Results");
	T_LOG("Total: %ju", results.numoftests);
	T_LOG("Passed: %ju", results.passed_tests);
	T_LOG("Failed: %ju", results.numoftests - results.passed_tests);

	T_ASSERT_EQ(results.passed_tests, results.numoftests,
	    "%ju passed of total %ju tests",
	    results.passed_tests, results.numoftests);
}

/*******************************/
/*******************************/
/* Virtual memory unit testing */
/*******************************/
/*******************************/

/* Test exit values:
 * 0: pass
 * 1: fail, generic unexpected failure
 * 2: fail, unexpected Mach return value
 * 3: fail, time out */

#define DEFAULT_VM_SIZE ((mach_vm_size_t)(1024ULL * 4096ULL))

#define POINTER(address) ((char *)(uintptr_t)(address))
#define MACH_VM_ADDRESS_T(address) (*((mach_vm_address_t *)(uintptr_t)(address)))

static int vm_address_size = sizeof(mach_vm_address_t);

/*************************/
/* Mach assert functions */
/*************************/

#define assert_mach_return(kr, expected_kr, format, ...)                \
	do {                                                            \
	/* fixme T_QUIET is not working */                      \
	        if ((kr) != (expected_kr)) {                            \
	                T_QUIET; T_ASSERT_MACH_ERROR(kr, expected_kr, format, ##__VA_ARGS__); \
	        }                                                       \
	} while (0)

#define assert_mach_success(kr, format, ...)                            \
	do {                                                            \
	/* fixme T_QUIET is not working */                      \
	        if (kr != KERN_SUCCESS) {                               \
	                T_QUIET; T_ASSERT_MACH_SUCCESS(kr, format, ##__VA_ARGS__); \
	        }                                                       \
	} while (0)                                                     \

#define assert_mach_failure(kr, format, ...)                            \
	do {                                                            \
	/* fixme T_QUIET is not working */                      \
	        if (kr == KERN_SUCCESS) {                               \
	                T_QUIET; T_ASSERT_NE(kr, KERN_SUCCESS, format, ##__VA_ARGS__); \
	        }                                                       \
	} while (0)                                                     \

/* Determine if TASK_EXC_GUARD_VM_FATAL is enabled for task */
static boolean_t
get_task_exc_guard_vm_fatal(void)
{
	task_exc_guard_behavior_t behavior;

	assert_mach_success(task_get_exc_guard_behavior(mach_task_self(), &behavior), "task_get_exc_guard_behavior");
	if ((behavior & TASK_EXC_GUARD_VM_DELIVER) &&
	    (behavior & TASK_EXC_GUARD_VM_FATAL)) {
		return TRUE;
	} else {
		return FALSE;
	}
}

/*******************************/
/* Arrays for test suite loops */
/*******************************/

/* Memory allocators */
typedef kern_return_t (*allocate_fn_t)(vm_map_t, mach_vm_address_t *, mach_vm_size_t, int);


/*
 * Remember any pre-reserved fixed address, which needs to be released prior to an allocation.
 */
static mach_vm_address_t fixed_vm_address = 0x0;
static mach_vm_size_t fixed_vm_size = 0;

/* forward decl */
void assert_deallocate_success(mach_vm_address_t address, mach_vm_size_t size);

/*
 * If trying to allocate at a fixed address, we need to do the delayed deallocate first.
 */
static void
check_fixed_address(mach_vm_address_t *address, mach_vm_size_t size)
{
	if (fixed_vm_address != 0 &&
	    fixed_vm_address <= *address &&
	    *address + size <= fixed_vm_address + fixed_vm_size) {
		assert_deallocate_success(fixed_vm_address, fixed_vm_size);
		fixed_vm_address = 0;
		fixed_vm_size = 0;
	}
}

kern_return_t
wrapper_mach_vm_allocate(vm_map_t map, mach_vm_address_t * address, mach_vm_size_t size, int flags)
{
	check_fixed_address(address, size);
	return mach_vm_allocate(map, address, size, flags);
}

kern_return_t
wrapper_mach_vm_map(vm_map_t map, mach_vm_address_t * address, mach_vm_size_t size, int flags)
{
	check_fixed_address(address, size);
	return mach_vm_map(map, address, size, (mach_vm_offset_t)0, flags, MACH_PORT_NULL, (memory_object_offset_t)0, FALSE,
	           VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
}

/* Should have the same behavior as when mask is zero. */
kern_return_t
wrapper_mach_vm_map_4kB(vm_map_t map, mach_vm_address_t * address, mach_vm_size_t size, int flags)
{
	check_fixed_address(address, size);
	return mach_vm_map(map, address, size, (mach_vm_offset_t)0xFFF, flags, MACH_PORT_NULL, (memory_object_offset_t)0, FALSE,
	           VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
}

kern_return_t
wrapper_mach_vm_map_2MB(vm_map_t map, mach_vm_address_t * address, mach_vm_size_t size, int flags)
{
	check_fixed_address(address, size);
	return mach_vm_map(map, address, size, (mach_vm_offset_t)0x1FFFFF, flags, MACH_PORT_NULL, (memory_object_offset_t)0, FALSE,
	           VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
}

kern_return_t
memory_entry(mach_vm_size_t * size, mach_port_t *object_handle)
{
	mach_vm_size_t original_size = *size;
	kern_return_t kr;

	kr = mach_make_memory_entry_64(mach_task_self(), size,
	    (memory_object_offset_t)0, (MAP_MEM_NAMED_CREATE | VM_PROT_ALL),
	    object_handle, 0);
	if (kr != KERN_SUCCESS) {
		return kr;
	}
	T_QUIET; T_ASSERT_EQ(*size, round_page(original_size),
	    "mach_make_memory_entry_64() unexpectedly returned a named "
	    "entry of size 0x%jx (%ju). "
	    "Should have returned a "
	    "named entry of size 0x%jx (%ju).",
	    (uintmax_t)*size, (uintmax_t)*size, (uintmax_t)original_size, (uintmax_t)original_size);
	return KERN_SUCCESS;
}

kern_return_t
wrapper_mach_vm_map_named_entry(vm_map_t map, mach_vm_address_t * address, mach_vm_size_t size, int flags)
{
	mach_port_t object_handle = MACH_PORT_NULL;
	kern_return_t kr = memory_entry(&size, &object_handle);

	if (kr != KERN_SUCCESS) {
		return kr;
	}
	check_fixed_address(address, size);
	kr = mach_vm_map(map, address, size, (mach_vm_offset_t)0, flags, object_handle, (memory_object_offset_t)0, FALSE,
	    VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT);
	assert_mach_success(mach_port_deallocate(mach_task_self(), object_handle), "mach_port_deallocate()");
	return kr;
}

static struct {
	allocate_fn_t allocate;
	const char * description;
} allocators[] = {
	{wrapper_mach_vm_allocate, "mach_vm_allocate()"},
	{wrapper_mach_vm_map, "mach_vm_map() (zero mask)"},
	{wrapper_mach_vm_map_4kB,
	 "mach_vm_map() "
	 "(4 kB address alignment)"},
	{wrapper_mach_vm_map_2MB,
	 "mach_vm_map() "
	 "(2 MB address alignment)"},
	{wrapper_mach_vm_map_named_entry,
	 "mach_vm_map() (named "
	 "entry, zero mask)"},
};
static int numofallocators = sizeof(allocators) / sizeof(allocators[0]);
static int allocators_idx;
enum { MACH_VM_ALLOCATE, MACH_VM_MAP, MACH_VM_MAP_4kB, MACH_VM_MAP_2MB, MACH_VM_MAP_NAMED_ENTRY };

/* VM size */
static struct {
	mach_vm_size_t size;
	const char * description;
} vm_sizes[] = {
	{DEFAULT_VM_SIZE, "default/input"},
	{0, "zero"},
	{4096ULL, "aligned"},
	{1ULL, "unaligned"},
	{4095ULL, "unaligned"},
	{4097ULL, "unaligned"},
};
static int numofsizes = sizeof(vm_sizes) / sizeof(vm_sizes[0]);
static int sizes_idx;
static int buffer_sizes_idx;
enum { DEFAULT_INPUT, ZERO_BYTES, ONE_PAGE, ONE_BYTE, ONE_PAGE_MINUS_ONE_BYTE, ONE_PAGE_AND_ONE_BYTE };

/* Unspecified/fixed address */
static struct {
	int flag;
	const char * description;
} address_flags[] = {
	{VM_FLAGS_ANYWHERE, "unspecified"}, {VM_FLAGS_FIXED, "fixed"},
};
static int numofflags = sizeof(address_flags) / sizeof(address_flags[0]);
static int flags_idx;
enum { ANYWHERE, FIXED };

/* Address alignment */
static struct {
	boolean_t alignment;
	const char * description;
} address_alignments[] = {
	{TRUE, " aligned"}, {FALSE, " unaligned"},
};
static int numofalignments = sizeof(address_alignments) / sizeof(*address_alignments);
static int alignments_idx;
enum { ALIGNED, UNALIGNED };

/* Buffer offset */
static struct {
	int offset;
	const char * description;
} buffer_offsets[] = {
	{0, ""}, {1, ""}, {2, ""},
};
static int numofoffsets = sizeof(buffer_offsets) / sizeof(buffer_offsets[0]);
static int offsets_idx;
enum { ZERO, ONE, TWO };

/* mach_vm_copy() post actions */
enum { VMCOPY_MODIFY_SRC, VMCOPY_MODIFY_DST, VMCOPY_MODIFY_SHARED_COPIED };

static struct {
	int action;
	const char * description;
} vmcopy_actions[] = {
	{VMCOPY_MODIFY_SRC, "modify vm_copy() source"},
	{VMCOPY_MODIFY_DST, "modify vm_copy() destination"},
	{VMCOPY_MODIFY_SHARED_COPIED,
	 "modify vm_copy source's shared "
	 "or copied from/to region"},
};
static int numofvmcopyactions = sizeof(vmcopy_actions) / sizeof(vmcopy_actions[0]);
static int vmcopy_action_idx;

/************************************/
/* Setters and getters for fixtures */
/************************************/

/* Allocation memory range. */
static allocate_fn_t _allocator      = wrapper_mach_vm_allocate;
static mach_vm_size_t _vm_size       = DEFAULT_VM_SIZE;
static int _address_flag             = VM_FLAGS_ANYWHERE;
static boolean_t _address_alignment  = TRUE;
static mach_vm_address_t _vm_address = 0x0;
static mach_vm_address_t _already_deallocated_vm_page = 0x0;

/* Buffer for mach_vm_write(). */
static mach_vm_size_t _buffer_size       = DEFAULT_VM_SIZE;
static mach_vm_address_t _buffer_address = 0x0;
static int _buffer_offset                = 0;
static mach_vm_address_t _already_deallocated_buffer_page = 0x0;

/* Post action for mach_vm_copy(). */
static int _vmcopy_post_action = VMCOPY_MODIFY_SRC;

static void
set_allocator(allocate_fn_t allocate)
{
	_allocator = allocate;
}

static allocate_fn_t
get_allocator()
{
	return _allocator;
}

static void
set_vm_size(mach_vm_size_t size)
{
	_vm_size = size;
}

static mach_vm_size_t
get_vm_size()
{
	return _vm_size;
}

static void
set_address_flag(int flag)
{
	_address_flag = flag;
}

static int
get_address_flag()
{
	return _address_flag;
}

static void
set_address_alignment(boolean_t alignment)
{
	_address_alignment = alignment;
}

static boolean_t
get_address_alignment()
{
	return _address_alignment;
}

static void
set_vm_address(mach_vm_address_t address)
{
	_vm_address = address;
}

static mach_vm_address_t
get_vm_address()
{
	return _vm_address;
}

static void
set_already_deallocated_vm_page(mach_vm_address_t address)
{
	_already_deallocated_vm_page = address;
}

static mach_vm_address_t
get_already_deallocated_vm_page()
{
	return _already_deallocated_vm_page;
}

static void
set_buffer_size(mach_vm_size_t size)
{
	_buffer_size = size;
}

static mach_vm_size_t
get_buffer_size()
{
	return _buffer_size;
}

static void
set_buffer_address(mach_vm_address_t address)
{
	_buffer_address = address;
}

static mach_vm_address_t
get_buffer_address()
{
	return _buffer_address;
}

static void
set_buffer_offset(int offset)
{
	_buffer_offset = offset;
}

static int
get_buffer_offset()
{
	return _buffer_offset;
}

static void
set_already_deallocated_buffer_page(mach_vm_address_t address)
{
	_already_deallocated_buffer_page = address;
}

static mach_vm_address_t
get_already_deallocated_buffer_page()
{
	return _already_deallocated_buffer_page;
}

static void
set_vmcopy_post_action(int action)
{
	_vmcopy_post_action = action;
}

static int
get_vmcopy_post_action()
{
	return _vmcopy_post_action;
}

/*******************************/
/* Usage and option processing */
/*******************************/
static boolean_t flag_run_allocate_test = FALSE;
static boolean_t flag_run_deallocate_test = FALSE;
static boolean_t flag_run_read_test = FALSE;
static boolean_t flag_run_write_test = FALSE;
static boolean_t flag_run_protect_test = FALSE;
static boolean_t flag_run_copy_test = FALSE;

#define VM_TEST_ALLOCATE   0x00000001
#define VM_TEST_DEALLOCATE 0x00000002
#define VM_TEST_READ       0x00000004
#define VM_TEST_WRITE      0x00000008
#define VM_TEST_PROTECT    0x00000010
#define VM_TEST_COPY       0x00000020

typedef struct test_option {
	uint32_t        to_flags;
	int             to_quietness;
	mach_vm_size_t  to_vmsize;
} test_option_t;

typedef struct test_info {
	char            *ti_name;
	boolean_t       *ti_flag;
} test_info_t;

static test_option_t test_options;

enum {ALLOCATE = 0, DEALLOCATE, READ, WRITE, PROTECT, COPY};

static test_info_t test_info[] = {
	{"allocate", &flag_run_allocate_test},
	{"deallocate", &flag_run_deallocate_test},
	{"read", &flag_run_read_test},
	{"write", &flag_run_write_test},
	{"protect", &flag_run_protect_test},
	{"copy", &flag_run_copy_test},
	{NULL, NULL}
};

static void
process_options(test_option_t options)
{
	test_info_t *tp;

	setvbuf(stdout, NULL, _IONBF, 0);

	set_vm_size(DEFAULT_VM_SIZE);
	set_quietness(DEFAULT_QUIETNESS);
	if (get_task_exc_guard_vm_fatal()) {
		_expected_vm_exc_guard_signal = SIGKILL;
	}

	if (NULL != getenv("LTERDOS")) {
		logr("LTERDOS=YES this is LeanTestEnvironment. Increasing quietness by 1.");
		set_quietness(get_quietness() + 1);
	} else {
		if (options.to_quietness > 0) {
			set_quietness(options.to_quietness);
		}
	}

	if (options.to_vmsize != 0) {
		vm_sizes[0].size = options.to_vmsize;
	}

	if (options.to_flags == 0) {
		for (tp = test_info; tp->ti_name != NULL; ++tp) {
			*tp->ti_flag = TRUE;
		}
	} else {
		if (options.to_flags & VM_TEST_ALLOCATE) {
			*(test_info[ALLOCATE].ti_flag) = TRUE;
		}

		if (options.to_flags & VM_TEST_DEALLOCATE) {
			*(test_info[DEALLOCATE].ti_flag) = TRUE;
		}

		if (options.to_flags & VM_TEST_READ) {
			*(test_info[READ].ti_flag) = TRUE;
		}

		if (options.to_flags & VM_TEST_WRITE) {
			*(test_info[WRITE].ti_flag) = TRUE;
		}

		if (options.to_flags & VM_TEST_PROTECT) {
			*(test_info[PROTECT].ti_flag) = TRUE;
		}

		if (options.to_flags & VM_TEST_COPY) {
			*(test_info[COPY].ti_flag) = TRUE;
		}
	}
}

/*****************/
/* Various tools */
/*****************/

/* Find the allocator address alignment mask. */
mach_vm_address_t
get_mask()
{
	mach_vm_address_t mask;

	if (get_allocator() == wrapper_mach_vm_map_2MB) {
		mask = (mach_vm_address_t)0x1FFFFF;
	} else {
		mask = vm_page_size - 1;
	}
	return mask;
}

/* Find the size of the smallest aligned region containing a given
 * memory range. */
mach_vm_size_t
aligned_size(mach_vm_address_t address, mach_vm_size_t size)
{
	return round_page(address - mach_vm_trunc_page(address) + size);
}

/********************/
/* Assert functions */
/********************/

/* Address is aligned on allocator boundary. */
static inline void
assert_aligned_address(mach_vm_address_t address)
{
	T_QUIET; T_ASSERT_EQ((address & get_mask()), 0ull,
	    "Address 0x%jx is unexpectedly "
	    "unaligned.",
	    (uintmax_t)address);
}

/* Address is truncated to allocator boundary. */
static inline void
assert_trunc_address(mach_vm_address_t address, mach_vm_address_t trunc_address)
{
	T_QUIET; T_ASSERT_EQ(trunc_address, (address & ~get_mask()),
	    "Address "
	    "0x%jx is unexpectedly not truncated to address 0x%jx.",
	    (uintmax_t)address, (uintmax_t)trunc_address);
}

static inline void
assert_address_value(mach_vm_address_t address, mach_vm_address_t marker)
{
	/* this assert is used so frequently so that we simply judge on
	 * its own instead of leaving this to LD macro for efficiency
	 */
	if (MACH_VM_ADDRESS_T(address) != marker) {
		T_ASSERT_FAIL("Address 0x%jx unexpectedly has value 0x%jx, "
		    "instead of 0x%jx.", (uintmax_t)address,
		    (uintmax_t)MACH_VM_ADDRESS_T(address), (uintmax_t)marker);
	}
}

void
assert_allocate_return(mach_vm_address_t * address, mach_vm_size_t size, int address_flag, kern_return_t expected_kr)
{
	assert_mach_return(get_allocator()(mach_task_self(), address, size, address_flag), expected_kr, "Allocator");
}

void
assert_allocate_success(mach_vm_address_t * address, mach_vm_size_t size, int address_flag)
{
	assert_allocate_return(address, size, address_flag, KERN_SUCCESS);
}

void
assert_deallocate_return(mach_vm_address_t address, mach_vm_size_t size, kern_return_t expected_kr)
{
	assert_mach_return(mach_vm_deallocate(mach_task_self(), address, size), expected_kr, "mach_vm_deallocate()");
}

void
assert_deallocate_success(mach_vm_address_t address, mach_vm_size_t size)
{
	assert_deallocate_return(address, size, KERN_SUCCESS);
}

void
assert_read_return(mach_vm_address_t address,
    mach_vm_size_t size,
    vm_offset_t * data,
    mach_msg_type_number_t * data_size,
    kern_return_t expected_kr)
{
	assert_mach_return(mach_vm_read(mach_task_self(), address, size, data, data_size), expected_kr, "mach_vm_read()");
}

void
assert_read_success(mach_vm_address_t address, mach_vm_size_t size, vm_offset_t * data, mach_msg_type_number_t * data_size)
{
	assert_read_return(address, size, data, data_size, KERN_SUCCESS);
	T_QUIET; T_ASSERT_EQ((mach_vm_size_t)*data_size, size,
	    "Returned buffer size 0x%jx "
	    "(%ju) is unexpectedly different from source size 0x%jx "
	    "(%ju).",
	    (uintmax_t)*data_size, (uintmax_t)*data_size, (uintmax_t)size, (uintmax_t)size);
}

void
assert_write_return(mach_vm_address_t address, vm_offset_t data, mach_msg_type_number_t data_size, kern_return_t expected_kr)
{
	assert_mach_return(mach_vm_write(mach_task_self(), address, data, data_size), expected_kr, "mach_vm_write()");
}

void
assert_write_success(mach_vm_address_t address, vm_offset_t data, mach_msg_type_number_t data_size)
{
	assert_write_return(address, data, data_size, KERN_SUCCESS);
}

void
assert_allocate_copy_return(mach_vm_address_t source, mach_vm_size_t size, mach_vm_address_t * dest, kern_return_t expected_kr)
{
	assert_allocate_success(dest, size, VM_FLAGS_ANYWHERE);
	assert_mach_return(mach_vm_copy(mach_task_self(), source, size, *dest), expected_kr, "mach_vm_copy()");
}
void
assert_allocate_copy_success(mach_vm_address_t source, mach_vm_size_t size, mach_vm_address_t * dest)
{
	assert_allocate_copy_return(source, size, dest, KERN_SUCCESS);
}

void
assert_copy_return(mach_vm_address_t source, mach_vm_size_t size, mach_vm_address_t dest, kern_return_t expected_kr)
{
	assert_mach_return(mach_vm_copy(mach_task_self(), source, size, dest), expected_kr, "mach_vm_copy()");
}

void
assert_copy_success(mach_vm_address_t source, mach_vm_size_t size, mach_vm_address_t dest)
{
	assert_copy_return(source, size, dest, KERN_SUCCESS);
}

void
assert_copy_failure(mach_vm_address_t source, mach_vm_size_t size, mach_vm_address_t dest)
{
	assert_mach_failure(mach_vm_copy(mach_task_self(), source, size, dest), "mach_vm_copy()");
}


/*******************/
/* Memory patterns */
/*******************/

typedef boolean_t (*address_filter_t)(mach_vm_address_t);
typedef void (*address_action_t)(mach_vm_address_t, mach_vm_address_t);

/* Map over a memory region pattern and its complement, through a
 * (possibly reversed) boolean filter and a starting value. */
void
filter_addresses_do_else(address_filter_t filter,
    boolean_t reversed,
    mach_vm_address_t address,
    mach_vm_size_t size,
    address_action_t if_action,
    address_action_t else_action,
    mach_vm_address_t start_value)
{
	mach_vm_address_t i;
	for (i = 0; i + vm_address_size < size; i += vm_address_size) {
		if (filter(address + i) != reversed) {
			if_action(address + i, start_value + i);
		} else {
			else_action(address + i, start_value + i);
		}
	}
}

/* Various pattern actions. */
void
no_action(mach_vm_address_t i, mach_vm_address_t value)
{
}

void
read_zero(mach_vm_address_t i, mach_vm_address_t value)
{
	assert_address_value(i, 0);
}

void
verify_address(mach_vm_address_t i, mach_vm_address_t value)
{
	assert_address_value(i, value);
}

void
write_address(mach_vm_address_t i, mach_vm_address_t value)
{
	MACH_VM_ADDRESS_T(i) = value;
}

/* Various patterns. */
boolean_t
empty(mach_vm_address_t i)
{
	return FALSE;
}

boolean_t
checkerboard(mach_vm_address_t i)
{
	return !((i / vm_address_size) & 0x1);
}

boolean_t
page_ends(mach_vm_address_t i)
{
	mach_vm_address_t residue = i % vm_page_size;

	return residue == 0 || residue == vm_page_size - vm_address_size;
}

/*************************************/
/* Global variables set up functions */
/*************************************/

void
set_up_allocator()
{
	T_QUIET; T_ASSERT_TRUE(allocators_idx >= 0 && allocators_idx < numofallocators, "Invalid allocators[] index: %d.", allocators_idx);
	set_allocator(allocators[allocators_idx].allocate);
}

/* Find a fixed allocatable address by retrieving the address
 * populated by mach_vm_allocate() with VM_FLAGS_ANYWHERE. */
mach_vm_address_t
get_fixed_address(mach_vm_size_t size)
{
	/* mach_vm_map() starts looking for an address at 0x0. */
	mach_vm_address_t address = 0x0;

	/*
	 * The tests seem to have some funky off by one allocations. To avoid problems, we'll bump anything
	 * non-zero to have at least an extra couple pages.
	 */
	if (size != 0) {
		size = round_page(size + 2 * vm_page_size);
	}

	assert_allocate_success(&address, size, VM_FLAGS_ANYWHERE);

	/*
	 * Keep the memory allocated, otherwise the logv()/printf() activity sprinkled in these tests can
	 * cause malloc() to use the desired range and tests will randomly fail. The allocate routines will
	 * do the delayed vm_deallocate() to free the fixed memory just before allocation testing in the wrapper.
	 */
	T_QUIET; T_ASSERT_EQ(fixed_vm_address, 0ull, "previous fixed address not used");
	T_QUIET; T_ASSERT_EQ(fixed_vm_size, 0ull, "previous fixed size not used");
	fixed_vm_address = address;
	fixed_vm_size = size;

	assert_aligned_address(address);
	return address;
}

/* If needed, find an address at which a region of the specified size
 * can be allocated. Otherwise, set the address to 0x0. */
void
set_up_vm_address(mach_vm_size_t size)
{
	T_QUIET; T_ASSERT_TRUE(flags_idx >= 0 && flags_idx < numofflags, "Invalid address_flags[] index: %d.", flags_idx);
	T_QUIET; T_ASSERT_TRUE(alignments_idx >= 0 && alignments_idx < numofalignments, "Invalid address_alignments[] index: %d.", alignments_idx);
	set_address_flag(address_flags[flags_idx].flag);
	set_address_alignment(address_alignments[alignments_idx].alignment);

	if (!(get_address_flag() & VM_FLAGS_ANYWHERE)) {
		boolean_t aligned = get_address_alignment();
		logv(
			"Looking for fixed %saligned address for allocation "
			"of 0x%jx (%ju) byte%s...",
			aligned ? "" : "un", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s");
		mach_vm_address_t address = get_fixed_address(size);
		if (!aligned) {
			address++;
		}
		set_vm_address(address);
		logv("Found %saligned fixed address 0x%jx.", aligned ? "" : "un", (uintmax_t)address);
	} else {
		/* mach_vm_map() with VM_FLAGS_ANYWHERE starts looking for
		 *  an address at the one supplied and goes up, without
		 *  wrapping around. */
		set_vm_address(0x0);
	}
}

void
set_up_vm_size()
{
	T_QUIET; T_ASSERT_TRUE(sizes_idx >= 0 && sizes_idx < numofsizes, "Invalid vm_sizes[] index: %d.", sizes_idx);
	set_vm_size(vm_sizes[sizes_idx].size);
}

void
set_up_buffer_size()
{
	T_QUIET; T_ASSERT_TRUE(buffer_sizes_idx >= 0 && buffer_sizes_idx < numofsizes, "Invalid vm_sizes[] index: %d.", buffer_sizes_idx);
	set_buffer_size(vm_sizes[buffer_sizes_idx].size);
}

void
set_up_buffer_offset()
{
	T_QUIET; T_ASSERT_TRUE(offsets_idx >= 0 && offsets_idx < numofoffsets, "Invalid buffer_offsets[] index: %d.", offsets_idx);
	set_buffer_offset(buffer_offsets[offsets_idx].offset);
}

void
set_up_vmcopy_action()
{
	T_QUIET; T_ASSERT_TRUE(vmcopy_action_idx >= 0 && vmcopy_action_idx < numofvmcopyactions, "Invalid vmcopy_actions[] index: %d.",
	    vmcopy_action_idx);
	set_vmcopy_post_action(vmcopy_actions[vmcopy_action_idx].action);
}

void
set_up_allocator_and_vm_size()
{
	set_up_allocator();
	set_up_vm_size();
}

void
set_up_vm_variables()
{
	set_up_vm_size();
	set_up_vm_address(get_vm_size());
}

void
set_up_allocator_and_vm_variables()
{
	set_up_allocator();
	set_up_vm_variables();
}

void
set_up_buffer_variables()
{
	set_up_buffer_size();
	set_up_buffer_offset();
}

void
set_up_copy_shared_mode_variables()
{
	set_up_vmcopy_action();
}

/*******************************/
/* Allocation set up functions */
/*******************************/

static void
log_allocation(mach_vm_size_t size, int flags, mach_vm_address_t address, const char *message)
{
	if (flags & VM_FLAGS_ANYWHERE) {
		logv("Allocating 0x%jx (%ju) byte%s %s...",
		    (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", message);
	} else {
		logv("Allocating 0x%jx (%ju) byte%s at address 0x%jx %s...",
		    (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", (uintmax_t)address, message);
	}
}

/* Allocate VM region of given size. */
void
allocate(mach_vm_size_t size)
{
	mach_vm_address_t address = get_vm_address();
	int flag                  = get_address_flag();

	log_allocation(size, flag, address, "");
	assert_allocate_success(&address, size, flag);
	logv(
		"Memory of rounded size 0x%jx (%ju) allocated at "
		"address 0x%jx.",
		(uintmax_t)round_page(size), (uintmax_t)round_page(size), (uintmax_t)address);
	/* Fixed allocation address is truncated to the allocator
	 *  boundary. */
	if (!(flag & VM_FLAGS_ANYWHERE)) {
		mach_vm_address_t old_address = get_vm_address();
		assert_trunc_address(old_address, address);
		logv(
			"Address 0x%jx is correctly truncated to allocated "
			"address 0x%jx.",
			(uintmax_t)old_address, (uintmax_t)address);
	}
	set_vm_address(address);
	set_already_deallocated_vm_page(0x0);
}

void
allocate_buffer(mach_vm_size_t buffer_size)
{
	mach_vm_address_t data = 0x0;

	log_allocation(buffer_size, VM_FLAGS_ANYWHERE, 0, "");
	assert_allocate_success(&data, buffer_size, VM_FLAGS_ANYWHERE);
	logv(
		"Memory of rounded size 0x%jx (%ju) allocated at "
		"address 0x%jx.",
		(uintmax_t)round_page(buffer_size), (uintmax_t)round_page(buffer_size), (uintmax_t)data);
	data += get_buffer_offset();
	T_QUIET; T_ASSERT_EQ((mach_vm_address_t)(vm_offset_t)data, data,
	    "Address 0x%jx "
	    "unexpectedly overflows to 0x%jx when cast as "
	    "vm_offset_t type.",
	    (uintmax_t)data, (uintmax_t)(vm_offset_t)data);
	set_buffer_address(data);
	set_already_deallocated_buffer_page(0x0);
}

/****************************************************/
/* Global variables and allocation set up functions */
/****************************************************/

void
set_up_vm_variables_and_allocate()
{
	set_up_vm_variables();
	allocate(get_vm_size());
}

void
set_up_allocator_and_vm_variables_and_allocate()
{
	set_up_allocator();
	set_up_vm_variables_and_allocate();
}

void
set_up_vm_variables_and_allocate_extra_page()
{
	set_up_vm_size();
	/* Increment the size to insure we get an extra allocated page
	 *  for unaligned start addresses. */
	mach_vm_size_t allocation_size = get_vm_size() + 1;
	set_up_vm_address(allocation_size);

	allocate(allocation_size);
	/* In the fixed unaligned address case, restore the returned
	*  (truncated) allocation address to its unaligned value. */
	if (!get_address_alignment()) {
		set_vm_address(get_vm_address() + 1);
	}
}

void
set_up_buffer_variables_and_allocate_extra_page()
{
	set_up_buffer_variables();
	/* Increment the size to insure we get an extra allocated page
	 *  for unaligned start addresses. */
	allocate_buffer(get_buffer_size() + get_buffer_offset());
}

/* Allocate some destination and buffer memory for subsequent
 * writing, including extra pages for non-aligned start addresses. */
void
set_up_vm_and_buffer_variables_allocate_for_writing()
{
	set_up_vm_variables_and_allocate_extra_page();
	set_up_buffer_variables_and_allocate_extra_page();
}

/* Allocate some destination and source regions for subsequent
 * copying, including extra pages for non-aligned start addresses. */
void
set_up_vm_and_buffer_variables_allocate_for_copying()
{
	set_up_vm_and_buffer_variables_allocate_for_writing();
}

/************************************/
/* Deallocation tear down functions */
/************************************/

void
deallocate_range(mach_vm_address_t address, mach_vm_size_t size)
{
	logv("Deallocating 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	assert_deallocate_success(address, size);
}

/*
 * Same as deallocate_range, buf if already_deallocated_address
 * is not zero then that page of memory is not deallocated.
 */
void
deallocate_range_except_page(mach_vm_address_t address, mach_vm_size_t size,
    mach_vm_address_t already_deallocated_address)
{
	if (already_deallocated_address != 0) {
		mach_vm_address_t end = mach_vm_round_page(address + size);
		mach_vm_address_t already_deallocated_end = already_deallocated_address + vm_page_size;
		deallocate_range(address, already_deallocated_address - address);
		logv("Skipping already-deallocated page at 0x%jx (%ju bytes)",
		    (uintmax_t)already_deallocated_address, (uintmax_t)vm_page_size);
		deallocate_range(already_deallocated_end, end - already_deallocated_end);
	} else {
		deallocate_range(address, size);
	}
}

void
deallocate()
{
	deallocate_range_except_page(get_vm_address(), get_vm_size(), get_already_deallocated_vm_page());
	set_already_deallocated_vm_page(0x0);
}

/* Deallocate source memory, including the extra page for unaligned
 * start addresses. */
void
deallocate_extra_page()
{
	/* Set the address and size to their original allocation
	 *  values. */
	deallocate_range_except_page(
		mach_vm_trunc_page(get_vm_address()),
		get_vm_size() + 1,
		get_already_deallocated_vm_page());
	set_already_deallocated_vm_page(0x0);
}

/* Deallocate buffer and destination memory for mach_vm_write(),
 * including the extra page for unaligned start addresses. */
void
deallocate_vm_and_buffer()
{
	deallocate_range_except_page(
		mach_vm_trunc_page(get_vm_address()),
		get_vm_size() + 1,
		get_already_deallocated_vm_page());
	set_already_deallocated_vm_page(0x0);

	deallocate_range_except_page(
		mach_vm_trunc_page(get_buffer_address()),
		get_buffer_size() + get_buffer_offset(),
		get_already_deallocated_buffer_page());
	set_already_deallocated_buffer_page(0x0);
}

/*
 * Deallocate vm_page_size bytes within the source memory.
 * Later deallocate() or deallocate_extra_page() or deallocate_vm_and_buffer()
 * will not deallocate it again.
 */
void
deallocate_vm_page_early(mach_vm_address_t address)
{
	mach_vm_address_t vm_start = mach_vm_trunc_page(get_vm_address());
	mach_vm_address_t vm_end = mach_vm_round_page(vm_start + get_vm_size() + 1);
	T_QUIET; T_ASSERT_EQ(get_already_deallocated_vm_page(), 0ull,
	    "deallocate_vm_page_early can only be used once per test");
	T_QUIET; T_ASSERT_EQ(address, mach_vm_trunc_page(address),
	    "deallocate_vm_page_early address must be page aligned");
	T_QUIET; T_ASSERT_TRUE(address >= vm_start && address + vm_page_size <= vm_end,
	    "deallocate_vm_page_early address must be within source memory");

	assert_deallocate_success(address, vm_page_size);
	set_already_deallocated_vm_page(address);
}

/*
 * Deallocate vm_page_size bytes within the mach_vm_write() buffer.
 * Later deallocate_vm_and_buffer() will not deallocate it again.
 */
void
deallocate_buffer_page_early(mach_vm_address_t address)
{
	mach_vm_address_t buffer_start = mach_vm_trunc_page(get_buffer_address());
	mach_vm_address_t buffer_end = mach_vm_round_page(buffer_start + get_buffer_size() + get_buffer_offset());
	T_QUIET; T_ASSERT_EQ(get_already_deallocated_buffer_page(), 0ull,
	    "deallocate_buffer_page_early can only be used once per test");
	T_QUIET; T_ASSERT_EQ(address, mach_vm_trunc_page(address),
	    "deallocate_buffer_page_early address must be page aligned");
	T_QUIET; T_ASSERT_TRUE(address >= buffer_start && address + vm_page_size <= buffer_end,
	    "deallocate_buffer_page_early address must be within buffer memory");

	assert_deallocate_success(address, vm_page_size);
	set_already_deallocated_buffer_page(address);
}

/***********************************/
/* mach_vm_read() set up functions */
/***********************************/

/* Read the source memory into a buffer, deallocate the source, set
 * the global address and size from the buffer's. */
void
read_deallocate()
{
	mach_vm_size_t size       = get_vm_size();
	mach_vm_address_t address = get_vm_address();
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	logv("Reading 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	assert_read_success(address, size, &read_address, &read_size);
	logv(
		"Memory of size 0x%jx (%ju) read into buffer of "
		"address 0x%jx.",
		(uintmax_t)read_size, (uintmax_t)read_size, (uintmax_t)read_address);
	/* Deallocate the originally allocated memory, including the
	 *  extra allocated page in
	 *  set_up_vm_variables_and_allocate_extra_page(). */
	deallocate_range(mach_vm_trunc_page(address), size + 1);

	/* Promoting to mach_vm types after checking for overflow, and
	 *  setting the global address from the buffer's. */
	T_QUIET; T_ASSERT_EQ((vm_offset_t)(mach_vm_address_t)read_address, read_address,
	    "Address 0x%jx unexpectedly overflows to 0x%jx when cast "
	    "as mach_vm_address_t type.",
	    (uintmax_t)read_address, (uintmax_t)(mach_vm_address_t)read_address);
	T_QUIET; T_ASSERT_EQ((mach_msg_type_number_t)(mach_vm_size_t)read_size, read_size,
	    "Size 0x%jx (%ju) unexpectedly overflows to 0x%jx (%ju) "
	    "when cast as mach_vm_size_t type.",
	    (uintmax_t)read_size, (uintmax_t)read_size, (uintmax_t)(mach_vm_size_t)read_size, (uintmax_t)(mach_vm_size_t)read_size);
	set_vm_address((mach_vm_address_t)read_address);
	set_vm_size((mach_vm_size_t)read_size);
}

/* Allocate some source memory, read it into a buffer, deallocate the
 * source, set the global address and size from the buffer's. */
void
set_up_vm_variables_allocate_read_deallocate()
{
	set_up_vm_variables_and_allocate_extra_page();
	read_deallocate();
}

/************************************/
/* mach_vm_write() set up functions */
/************************************/

/* Write the buffer into the destination memory. */
void
write_buffer()
{
	mach_vm_address_t address          = get_vm_address();
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_write_success(address, data, buffer_size);
	logv("Buffer written.");
}

/* Allocate some destination and buffer memory, and write the buffer
 * into the destination memory. */
void
set_up_vm_and_buffer_variables_allocate_write()
{
	set_up_vm_and_buffer_variables_allocate_for_writing();
	write_buffer();
}

/***********************************/
/* mach_vm_copy() set up functions */
/***********************************/

void
copy_deallocate(void)
{
	mach_vm_size_t size      = get_vm_size();
	mach_vm_address_t source = get_vm_address();
	mach_vm_address_t dest   = 0;

	logv("Copying 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)source);
	assert_allocate_copy_success(source, size, &dest);
	logv(
		"Memory of size 0x%jx (%ju) copy into region of "
		"address 0x%jx.",
		(uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);
	/* Deallocate the originally allocated memory, including the
	 *  extra allocated page in
	 *  set_up_vm_variables_and_allocate_extra_page(). */
	deallocate_range(mach_vm_trunc_page(source), size + 1);
	/* Promoting to mach_vm types after checking for overflow, and
	 *  setting the global address from the buffer's. */
	T_QUIET; T_ASSERT_EQ((mach_vm_address_t)(vm_offset_t)dest, dest,
	    "Address 0x%jx unexpectedly overflows to 0x%jx when cast "
	    "as mach_vm_address_t type.",
	    (uintmax_t)dest, (uintmax_t)(vm_offset_t)dest);
	set_vm_address(dest);
	set_vm_size(size);
}

/* Copy the source region into the destination region. */
void
copy_region()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Copying memory region of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);
	assert_copy_success(source, size, dest);
	logv("Buffer written.");
}

/* Allocate some source memory, copy it to another region, deallocate the
* source, set the global address and size from the designation region. */
void
set_up_vm_variables_allocate_copy_deallocate()
{
	set_up_vm_variables_and_allocate_extra_page();
	copy_deallocate();
}

/* Allocate some destination and source memory, and copy the source
 * into the destination memory. */
void
set_up_source_and_dest_variables_allocate_copy()
{
	set_up_vm_and_buffer_variables_allocate_for_copying();
	copy_region();
}

/**************************************/
/* mach_vm_protect() set up functions */
/**************************************/

void
set_up_vm_variables_allocate_protect(vm_prot_t protection, const char * protection_name)
{
	set_up_vm_variables_and_allocate_extra_page();
	mach_vm_size_t size       = get_vm_size();
	mach_vm_address_t address = get_vm_address();

	logv(
		"Setting %s-protection on 0x%jx (%ju) byte%s at address "
		"0x%jx...",
		protection_name, (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", (uintmax_t)address);
	assert_mach_success(mach_vm_protect(mach_task_self(), address, size, FALSE, protection), "mach_vm_protect()");
	logv("Region %s-protected.", protection_name);
}

void
set_up_vm_variables_allocate_readprotect()
{
	set_up_vm_variables_allocate_protect(VM_PROT_WRITE, "read");
}

void
set_up_vm_variables_allocate_writeprotect()
{
	set_up_vm_variables_allocate_protect(VM_PROT_READ, "write");
}

/*****************/
/* Address tests */
/*****************/

/* Allocated address is nonzero iff size is nonzero. */
void
test_nonzero_address_iff_nonzero_size()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();

	T_QUIET; T_ASSERT_TRUE((address && size) || (!address && !size), "Address 0x%jx is unexpectedly %szero.", (uintmax_t)address,
	    address ? "non" : "");
	logv("Address 0x%jx is %szero as expected.", (uintmax_t)address, size ? "non" : "");
}

/* Allocated address is aligned. */
void
test_aligned_address()
{
	mach_vm_address_t address = get_vm_address();

	assert_aligned_address(address);
	logv("Address 0x%jx is aligned.", (uintmax_t)address);
}

/************************/
/* Read and write tests */
/************************/

void
verify_pattern(
	address_filter_t filter, boolean_t reversed, mach_vm_address_t address, mach_vm_size_t size, const char * pattern_name)
{
	logv(
		"Verifying %s pattern on region of address 0x%jx "
		"and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)address, (uintmax_t)size, (uintmax_t)size);
	filter_addresses_do_else(filter, reversed, address, size, verify_address, read_zero, address);
	logv("Pattern verified.");
}

void
write_pattern(
	address_filter_t filter, boolean_t reversed, mach_vm_address_t address, mach_vm_size_t size, const char * pattern_name)
{
	logv(
		"Writing %s pattern on region of address 0x%jx "
		"and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)address, (uintmax_t)size, (uintmax_t)size);
	filter_addresses_do_else(filter, reversed, address, size, write_address, no_action, address);
	logv("Pattern written.");
}

void
write_and_verify_pattern(
	address_filter_t filter, boolean_t reversed, mach_vm_address_t address, mach_vm_size_t size, const char * pattern_name)
{
	logv(
		"Writing and verifying %s pattern on region of "
		"address 0x%jx and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)address, (uintmax_t)size, (uintmax_t)size);
	filter_addresses_do_else(filter, reversed, address, size, write_address, no_action, address);
	filter_addresses_do_else(filter, reversed, address, size, verify_address, read_zero, address);
	logv("Pattern written and verified.");
}

/* Verify that the smallest aligned region containing the
 * given range is zero-filled. */
void
test_zero_filled()
{
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_vm_address()), aligned_size(get_vm_address(), get_vm_size()),
	    "zero-filled");
}

void
test_write_address_filled()
{
	write_and_verify_pattern(empty, TRUE, get_vm_address(), round_page(get_vm_size()), "address-filled");
}

void
test_write_checkerboard()
{
	write_and_verify_pattern(checkerboard, FALSE, get_vm_address(), round_page(get_vm_size()), "checkerboard");
}

void
test_write_reverse_checkerboard()
{
	write_and_verify_pattern(checkerboard, TRUE, get_vm_address(), round_page(get_vm_size()), "reverse checkerboard");
}

void
test_write_page_ends()
{
	write_and_verify_pattern(page_ends, FALSE, get_vm_address(), round_page(get_vm_size()), "page ends");
}

void
test_write_page_interiors()
{
	write_and_verify_pattern(page_ends, TRUE, get_vm_address(), round_page(get_vm_size()), "page interiors");
}

/*********************************/
/* Allocation error return tests */
/*********************************/

/* Reallocating a page in the smallest aligned region containing the
 * given allocated range fails. */
void
test_reallocate_pages()
{
	allocate_fn_t allocator   = get_allocator();
	vm_map_t this_task        = mach_task_self();
	mach_vm_address_t address = mach_vm_trunc_page(get_vm_address());
	mach_vm_size_t size       = aligned_size(get_vm_address(), get_vm_size());
	mach_vm_address_t i;
	kern_return_t kr;

	logv(
		"Reallocating pages in allocated region of address 0x%jx "
		"and size 0x%jx (%ju)...",
		(uintmax_t)address, (uintmax_t)size, (uintmax_t)size);
	for (i = address; i < address + size; i += vm_page_size) {
		kr = allocator(this_task, &i, vm_page_size, VM_FLAGS_FIXED);
		assert_mach_return(kr, KERN_NO_SPACE,
		    "Allocator at address 0x%jx expected KERN_NO_SPACE",
		    (uintmax_t)address);
	}
	logv("Returned expected error at each page: %s.", mach_error_string(KERN_NO_SPACE));
}

/* Allocating in VM_MAP_NULL fails. */
void
test_allocate_in_null_map()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();
	int flag                  = get_address_flag();

	log_allocation(size, flag, address, "in NULL VM map");
	assert_mach_return(get_allocator()(VM_MAP_NULL, &address, size, flag), MACH_SEND_INVALID_DEST, "Allocator");
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_DEST));
}

/* Allocating with non-user flags fails. */
void
test_allocate_with_kernel_flags()
{
	allocate_fn_t allocator   = get_allocator();
	vm_map_t this_task        = mach_task_self();
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();
	int flag                  = get_address_flag();
	int bad_flag, i;
	kern_return_t kr;
	int valid_flags = VM_FLAGS_USER_ALLOCATE | VM_FLAGS_USER_MAP | VM_FLAGS_USER_REMAP | VM_FLAGS_ALIAS_MASK;

	log_allocation(size, flag, address, "with various invalid flags");
	for (i = 0; i < sizeof(int) * 8; i++) {
		int test_flag = 1 << i;

		/* Skip user valid flags */
		if (valid_flags & test_flag) {
			continue;
		}

		bad_flag = test_flag | flag;
		kr = allocator(this_task, &address, size, bad_flag);
		assert_mach_return(kr, KERN_INVALID_ARGUMENT,
		    "Allocator with invalid flag 0x%x expected KERN_INVALID_ARGUMENT.",
		    bad_flag);
	}
	logv("Returned expected error with each invalid flag: %s.", mach_error_string(KERN_INVALID_ARGUMENT));
}

/* Allocating super-page with incompatible flags fails. */
void
test_allocate_superpage_with_incompatible_flags()
{
}

/*****************************/
/* mach_vm_map() error tests */
/*****************************/

/* mach_vm_map() fails with invalid protection or inheritance
 *  arguments. */
void
test_mach_vm_map_protection_inheritance_error()
{
	kern_return_t kr;
	vm_map_t my_task          = mach_task_self();
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();
	vm_map_offset_t mask = (get_allocator() == wrapper_mach_vm_map || get_allocator() == wrapper_mach_vm_map_named_entry)
	    ? (mach_vm_offset_t)0
	    : (mach_vm_offset_t)get_mask();
	int flag                    = get_address_flag();
	mach_port_t object_handle   = MACH_PORT_NULL;
	vm_prot_t cur_protections[] = {VM_PROT_DEFAULT, (VM_PROT_ALL | VM_PROT_ALLEXEC) + 1, ~VM_PROT_IS_MASK, INT_MAX};
	vm_prot_t max_protections[] = {VM_PROT_ALL, (VM_PROT_ALL | VM_PROT_ALLEXEC) + 1, ~VM_PROT_IS_MASK, INT_MAX};
	vm_inherit_t inheritances[] = {VM_INHERIT_DEFAULT, VM_INHERIT_LAST_VALID + 1, UINT_MAX};
	int i, j, k;

	if (get_allocator() == wrapper_mach_vm_map_named_entry) {
		assert_mach_success(memory_entry(&size, &object_handle), "mach_make_memory_entry_64()");
	}
	log_allocation(size, flag, address, "with various invalid protection/inheritance arguments");

	for (i = 0; i < 4; i++) {
		for (j = 0; j < 4; j++) {
			for (k = 0; k < 3; k++) {
				/* Skip the case with all valid arguments. */
				if (i == (j == (k == 0))) {
					continue;
				}
				kr = mach_vm_map(my_task, &address, size, mask, flag, object_handle, (memory_object_offset_t)0, FALSE,
				    cur_protections[i], max_protections[j], inheritances[k]);
				assert_mach_return(kr, KERN_INVALID_ARGUMENT,
				    "mach_vm_map() "
				    "with cur_protection 0x%x, max_protection 0x%x, "
				    "inheritance 0x%x expected KERN_INVALID_ARGUMENT",
				    cur_protections[i], max_protections[j], inheritances[k]);
			}
		}
	}
	logv("Returned expected error in each case: %s.", mach_error_string(KERN_INVALID_ARGUMENT));
}

/* mach_vm_map() with unspecified address fails if the starting
 *  address overflows when rounded up to a boundary value. */
void
test_mach_vm_map_large_mask_overflow_error()
{
	mach_vm_address_t address = 0x1;
	mach_vm_size_t size       = get_vm_size();
	mach_vm_offset_t mask     = (mach_vm_offset_t)UINTMAX_MAX;
	/* mach_vm_map() cannot allocate 0 bytes at an unspecified
	 *  address, see 8003930. */
	kern_return_t kr_expected = size ? KERN_NO_SPACE : KERN_INVALID_ARGUMENT;

	logv(
		"Allocating 0x%jx (%ju) byte%s at an unspecified address "
		"starting at 0x%jx with mask 0x%jx...",
		(uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", (uintmax_t)address, (uintmax_t)mask);
	assert_mach_return(mach_vm_map(mach_task_self(), &address, size, mask, VM_FLAGS_ANYWHERE, MACH_PORT_NULL,
	    (memory_object_offset_t)0, FALSE, VM_PROT_DEFAULT, VM_PROT_ALL, VM_INHERIT_DEFAULT),
	    kr_expected, "mach_vm_map()");
	logv("Returned expected error: %s.", mach_error_string(kr_expected));
}

/************************/
/* Size edge case tests */
/************************/

void
allocate_edge_size(mach_vm_address_t * address, mach_vm_size_t size, kern_return_t expected_kr)
{
	logv("Allocating 0x%jx (%ju) bytes...", (uintmax_t)size, (uintmax_t)size);
	assert_allocate_return(address, size, VM_FLAGS_ANYWHERE, expected_kr);
	logv("Returned expected value: %s.", mach_error_string(expected_kr));
}

void
test_allocate_zero_size()
{
	mach_vm_address_t address = 0x0;
	/* mach_vm_map() cannot allocate 0 bytes at an unspecified
	 *  address, see 8003930. Other allocators succeed. */
	kern_return_t kr_expected = (get_allocator() != wrapper_mach_vm_allocate) ? KERN_INVALID_ARGUMENT : KERN_SUCCESS;

	allocate_edge_size(&address, 0, kr_expected);
	if (kr_expected == KERN_SUCCESS) {
		deallocate_range(address, 0);
	}
}

/* Testing the allocation of the largest size that does not overflow
 * when rounded up to a page-aligned value. */
void
test_allocate_invalid_large_size()
{
	mach_vm_size_t size = (mach_vm_size_t)UINTMAX_MAX - vm_page_size + 1;
	if (get_allocator() != wrapper_mach_vm_map_named_entry) {
		mach_vm_address_t address = 0x0;
		allocate_edge_size(&address, size, KERN_NO_SPACE);
	} else {
		/* Named entries cannot currently be bigger than 4 GB
		 *  - 4 kb. */
		mach_port_t object_handle = MACH_PORT_NULL;
		logv("Creating named entry of 0x%jx (%ju) bytes...", (uintmax_t)size, (uintmax_t)size);
		assert_mach_return(mach_make_memory_entry_64(mach_task_self(), &size, (memory_object_offset_t)0,
		    (MAP_MEM_NAMED_CREATE | VM_PROT_ALL), &object_handle, 0),
		    KERN_FAILURE, "mach_make_memory_entry_64()");
		logv("Returned expected error: %s.", mach_error_string(KERN_FAILURE));
	}
}

/* A UINTMAX_MAX VM size will overflow to 0 when rounded up to a
 * page-aligned value. */
void
test_allocate_overflowing_size()
{
	mach_vm_address_t address = 0x0;

	allocate_edge_size(&address, (mach_vm_size_t)UINTMAX_MAX, KERN_INVALID_ARGUMENT);
}

/****************************/
/* Address allocation tests */
/****************************/

/* Allocation at address zero fails iff size is nonzero. */
void
test_allocate_at_zero()
{
	mach_vm_address_t address = 0x0;
	mach_vm_size_t size       = get_vm_size();

	kern_return_t kr_expected =
	    size ? KERN_INVALID_ADDRESS : (get_allocator() != wrapper_mach_vm_allocate) ? KERN_INVALID_ARGUMENT : KERN_SUCCESS;

	logv("Allocating 0x%jx (%ju) byte%s at address 0x0...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s");
	assert_allocate_return(&address, size, VM_FLAGS_FIXED, kr_expected);
	logv("Returned expected value: %s.", mach_error_string(kr_expected));
	if (kr_expected == KERN_SUCCESS) {
		T_QUIET; T_ASSERT_EQ(address, 0ull,
		    "Address 0x%jx is unexpectedly "
		    "nonzero.",
		    (uintmax_t)address);
		logv("Allocated address 0x%jx is zero.", (uintmax_t)address);
		deallocate_range(address, size);
	}
}

/* Allocation at page-aligned but 2 MB boundary-unaligned address
 *  fails with KERN_NO_SPACE. */
void
test_allocate_2MB_boundary_unaligned_page_aligned_address()
{
	mach_vm_size_t size = get_vm_size();

	mach_vm_address_t address = get_fixed_address(size + vm_page_size) + vm_page_size;
	logv(
		"Found 2 MB boundary-unaligned, page aligned address "
		"0x%jx.",
		(uintmax_t)address);

	/* mach_vm_allocate() cannot allocate 0 bytes, and fails with a
	 *  fixed boundary-unaligned truncated address. */
	kern_return_t kr_expected = (!size && get_allocator() != wrapper_mach_vm_allocate)
	    ? KERN_INVALID_ARGUMENT
	    : (get_allocator() == wrapper_mach_vm_map_2MB) ? KERN_NO_SPACE : KERN_SUCCESS;
	logv("Allocating 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	assert_allocate_return(&address, size, VM_FLAGS_FIXED, kr_expected);
	logv("Returned expected value: %s.", mach_error_string(kr_expected));
	if (kr_expected == KERN_SUCCESS) {
		deallocate_range(address, size);
	}
}

/* With VM_FLAGS_ANYWHERE set, mach_vm_allocate() starts looking for
 *  an allocation address at 0x0, while mach_vm_map() starts at the
 *  supplied address and does not wrap around. See 8016663. */
void
test_allocate_page_with_highest_address_hint()
{
	/* Highest valid page-aligned address. */
	mach_vm_address_t address = (mach_vm_size_t)UINTMAX_MAX - vm_page_size + 1;

	logv(
		"Allocating one page with unspecified address, but hint at "
		"0x%jx...",
		(uintmax_t)address);
	if (get_allocator() == wrapper_mach_vm_allocate) {
		/* mach_vm_allocate() starts from 0x0 and succeeds. */
		assert_allocate_success(&address, vm_page_size, VM_FLAGS_ANYWHERE);
		logv("Memory allocated at address 0x%jx.", (uintmax_t)address);
		assert_aligned_address(address);
		deallocate_range(address, vm_page_size);
	} else {
		/* mach_vm_map() starts from the supplied address, and fails
		 *  with KERN_NO_SPACE, see 8016663. */
		assert_allocate_return(&address, vm_page_size, VM_FLAGS_ANYWHERE, KERN_NO_SPACE);
		logv("Returned expected error: %s.", mach_error_string(KERN_NO_SPACE));
	}
}

/* Allocators find an allocation address with a first fit strategy. */
void
test_allocate_first_fit_pages()
{
	allocate_fn_t allocator    = get_allocator();
	mach_vm_address_t address1 = 0x0;
	mach_vm_address_t i;
	kern_return_t kr;
	vm_map_t this_task = mach_task_self();

	logv(
		"Looking for first fit address for allocating one "
		"page...");
	assert_allocate_success(&address1, vm_page_size, VM_FLAGS_ANYWHERE);
	logv("Found address 0x%jx.", (uintmax_t)address1);
	assert_aligned_address(address1);
	mach_vm_address_t address2 = address1;
	logv(
		"Looking for next higher first fit address for allocating "
		"one page...");
	assert_allocate_success(&address2, vm_page_size, VM_FLAGS_ANYWHERE);
	logv("Found address 0x%jx.", (uintmax_t)address2);
	assert_aligned_address(address2);
	T_QUIET; T_ASSERT_GT(address2, address1,
	    "Second address 0x%jx is "
	    "unexpectedly not higher than first address 0x%jx.",
	    (uintmax_t)address2, (uintmax_t)address1);

	logv("Allocating pages between 0x%jx and 0x%jx...", (uintmax_t)address1, (uintmax_t)address2);
	for (i = address1; i <= address2; i += vm_page_size) {
		kr = allocator(this_task, &i, vm_page_size, VM_FLAGS_FIXED);
		assert_mach_failure(kr,
		    "Allocator at address 0x%jx "
		    "unexpectedly succeeded.",
		    (uintmax_t)i);
	}
	logv("Expectedly returned error at each page.");
	deallocate_range(address1, vm_page_size);
	deallocate_range(address2, vm_page_size);
}

/*******************************/
/* Deallocation segfault tests */
/*******************************/

/* mach_vm_deallocate() deallocates the smallest aligned region
 * (integral number of pages) containing the given range. */

/* Addresses in deallocated range are inaccessible. */
void
access_deallocated_range_address(mach_vm_address_t address, const char * position)
{
	logv("Will deallocate and read from %s 0x%jx of deallocated range...", position, (uintmax_t)address);
	deallocate();
	mach_vm_address_t bad_value = MACH_VM_ADDRESS_T(address);
	T_ASSERT_FAIL("Unexpectedly read value 0x%jx at address 0x%jx. "
	    "Should have died with signal SIGSEGV.",
	    (uintmax_t)bad_value, (uintmax_t)address);
}

/* Start of deallocated range is inaccessible. */
void
test_access_deallocated_range_start()
{
	access_deallocated_range_address(get_vm_address(), "start");
}

/* Middle of deallocated range is inaccessible. */
void
test_access_deallocated_range_middle()
{
	access_deallocated_range_address(get_vm_address() + (round_page(get_vm_size()) >> 1), "middle");
}

/* End of deallocated range is inaccessible. */
void
test_access_deallocated_range_end()
{
	access_deallocated_range_address(round_page(get_vm_size()) - vm_address_size + get_vm_address(), "end");
}

/* Deallocating almost the whole address space causes a SIGSEGV or SIGBUS. We
 * deallocate the largest valid aligned size to avoid overflowing when
 * rounding up. */
void
test_deallocate_suicide()
{
	mach_vm_address_t address = 0x0;
	mach_vm_size_t size       = (mach_vm_size_t)UINTMAX_MAX - vm_page_size + 1;

	logv("Deallocating 0x%jx (%ju) bytes at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (uintmax_t)address);
	kern_return_t kr = mach_vm_deallocate(mach_task_self(), address, size);
	T_ASSERT_FAIL("mach_vm_deallocate() with address 0x%jx and "
	    "size 0x%jx (%ju) unexpectedly returned: %s. "
	    "Should have died with signal SIGSEGV or SIGBUS.",
	    (uintmax_t)address, (uintmax_t)size, (uintmax_t)size, mach_error_string(kr));
}

/***************************************/
/* Deallocation and reallocation tests */
/***************************************/

/* Deallocating memory twice succeeds. */
void
test_deallocate_twice()
{
	deallocate();
	deallocate();
}

/* Deallocated and reallocated memory is zero-filled. Deallocated
 * memory is inaccessible since it can be reallocated. */
void
test_write_pattern_deallocate_reallocate_zero_filled()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();

	write_pattern(page_ends, FALSE, address, size, "page ends");
	logv("Deallocating, then Allocating 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	deallocate();
	assert_allocate_success(&address, size, VM_FLAGS_FIXED);
	logv("Memory allocated.");
	verify_pattern(empty, FALSE, address, size, "zero-filled");
	deallocate();
}

/********************************/
/* Deallocation edge case tests */
/********************************/

/* Zero size deallocation always succeeds. */
void
test_deallocate_zero_size_ranges()
{
	int i;
	kern_return_t kr;
	vm_map_t this_task            = mach_task_self();
	mach_vm_address_t addresses[] = {0x0,
		                         0x1,
		                         vm_page_size - 1,
		                         vm_page_size,
		                         vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX,
		                         (mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINTMAX_MAX};
	int numofaddresses = sizeof(addresses) / sizeof(addresses[0]);

	logv("Deallocating 0x0 (0) bytes at various addresses...");
	for (i = 0; i < numofaddresses; i++) {
		kr = mach_vm_deallocate(this_task, addresses[i], 0);
		assert_mach_success(kr, "mach_vm_deallocate() at "
		    "address 0x%jx unexpectedly failed",
		    (uintmax_t)addresses[i]);
	}
	logv("Deallocations successful.");
}

/* Deallocating a range wrapped around the address space fails. */
void
test_deallocate_wrapped_around_ranges()
{
	int i;
	kern_return_t kr;
	vm_map_t this_task = mach_task_self();
	struct {
		mach_vm_address_t address;
		mach_vm_size_t size;
	} ranges[] = {
		{0x1, (mach_vm_size_t)UINTMAX_MAX},
		{vm_page_size, (mach_vm_size_t)UINTMAX_MAX - vm_page_size + 1},
		{(mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1, vm_page_size},
		{(mach_vm_address_t)UINTMAX_MAX, 1},
	};
	int numofranges = sizeof(ranges) / sizeof(ranges[0]);

	logv(
		"Deallocating various memory ranges wrapping around the "
		"address space...");

	for (i = 0; i < numofranges; i++) {
		kr = mach_vm_deallocate(this_task, ranges[i].address, ranges[i].size);
		assert_mach_return(kr, KERN_INVALID_ARGUMENT,
		    "mach_vm_deallocate() with address 0x%jx and size "
		    "0x%jx (%ju) expected KERN_INVALID_ARGUMENT",
		    (uintmax_t)ranges[i].address, (uintmax_t)ranges[i].size,
		    (uintmax_t)ranges[i].size);
	}
	logv("Returned expected error on each range: %s.", mach_error_string(KERN_INVALID_ARGUMENT));
}

/* Deallocating in VM_MAP_NULL fails. */
void
test_deallocate_in_null_map()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();

	logv("Deallocating 0x%jx (%ju) byte%s at address 0x%jx in NULL VM map...",
	    (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", (uintmax_t)address);
	assert_mach_return(mach_vm_deallocate(VM_MAP_NULL, address, size), MACH_SEND_INVALID_DEST, "mach_vm_deallocate()");
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_DEST));
}

/*****************************/
/* mach_vm_read() main tests */
/*****************************/

/* Read memory of size less than a page has aligned starting
 * address. Otherwise, the destination buffer's starting address has
 * the same boundary offset as the source region's. */
void
test_read_address_offset()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();

	if (size < vm_page_size * 2 || get_address_alignment()) {
		assert_aligned_address(address);
		logv("Buffer address 0x%jx is aligned as expected.", (uintmax_t)address);
	} else {
		T_QUIET; T_ASSERT_EQ(((address - 1) & (vm_page_size - 1)), 0ull,
		    "Buffer "
		    "address 0x%jx does not have the expected boundary "
		    "offset of 1.",
		    (uintmax_t)address);
		logv(
			"Buffer address 0x%jx has the expected boundary "
			"offset of 1.",
			(uintmax_t)address);
	}
}

/* Reading from VM_MAP_NULL fails. */
void
test_read_null_map()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	logv(
		"Reading 0x%jx (%ju) byte%s at address 0x%jx in NULL VM "
		"map...",
		(uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s", (uintmax_t)address);
	assert_mach_return(mach_vm_read(VM_MAP_NULL, address, size, &read_address, &read_size),
	    MACH_SEND_INVALID_DEST, "mach_vm_read()");
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_DEST));
}

/* Reading partially deallocated memory fails. */
void
test_read_partially_deallocated_range()
{
	mach_vm_address_t address   = get_vm_address();
	mach_vm_size_t size         = get_vm_size();
	mach_vm_address_t mid_point = mach_vm_trunc_page(address + size / 2);
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	logv("Deallocating a mid-range page at address 0x%jx...", (uintmax_t)mid_point);
	deallocate_vm_page_early(mid_point);
	logv("Page deallocated.");

	logv("Reading 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	assert_read_return(address, size, &read_address, &read_size, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Reading partially read-protected memory fails. */
void
test_read_partially_unreadable_range()
{
	mach_vm_address_t address   = get_vm_address();
	mach_vm_size_t size         = get_vm_size();
	mach_vm_address_t mid_point = mach_vm_trunc_page(address + size / 2);
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	/*  For sizes < msg_ool_size_small, vm_map_copyin_common() uses
	 *  vm_map_copyin_kernel_buffer() to read in the memory,
	 *  returning different errors, see 8182239. */
	kern_return_t kr_expected = (size < vm_page_size * 2) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv("Read-protecting a mid-range page at address 0x%jx...", (uintmax_t)mid_point);
	assert_mach_success(mach_vm_protect(mach_task_self(), mid_point, vm_page_size, FALSE, VM_PROT_WRITE), "mach_vm_protect()");
	logv("Page read-protected.");

	logv("Reading 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)address);
	assert_read_return(address, size, &read_address, &read_size, kr_expected);
	logv("Returned expected error: %s.", mach_error_string(kr_expected));
}

/**********************************/
/* mach_vm_read() edge case tests */
/**********************************/

void
read_edge_size(mach_vm_size_t size, kern_return_t expected_kr)
{
	int i;
	kern_return_t kr;
	vm_map_t this_task            = mach_task_self();
	mach_vm_address_t addresses[] = {vm_page_size - 1,
		                         vm_page_size,
		                         vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX,
		                         (mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINTMAX_MAX};
	int numofaddresses = sizeof(addresses) / sizeof(addresses[0]);
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	logv("Reading 0x%jx (%ju) bytes at various addresses...", (uintmax_t)size, (uintmax_t)size);
	for (i = 0; i < numofaddresses; i++) {
		kr = mach_vm_read(this_task, addresses[i], size, &read_address, &read_size);
		assert_mach_return(kr, expected_kr,
		    "mach_vm_read() at "
		    "address 0x%jx expected %s",
		    (uintmax_t)addresses[i], mach_error_string(expected_kr));
	}
	logv(
		"mach_vm_read() returned expected value in each case: "
		"%s.",
		mach_error_string(expected_kr));
}

/* Reading 0 bytes always succeeds. */
void
test_read_zero_size()
{
	read_edge_size(0, KERN_SUCCESS);
}

/* Reading 4GB or higher always fails. */
void
test_read_invalid_large_size()
{
	read_edge_size((mach_vm_size_t)UINT_MAX + 1, KERN_INVALID_ARGUMENT);
}

/* Reading a range wrapped around the address space fails. */
void
test_read_wrapped_around_ranges()
{
	int i;
	kern_return_t kr;
	vm_map_t this_task = mach_task_self();
	struct {
		mach_vm_address_t address;
		mach_vm_size_t size;
	} ranges[] = {
		{(mach_vm_address_t)(UINTMAX_MAX - UINT_MAX + 1), (mach_vm_size_t)UINT_MAX},
		{(mach_vm_address_t)(UINTMAX_MAX - UINT_MAX + vm_page_size), (mach_vm_size_t)(UINT_MAX - vm_page_size + 1)},
		{(mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1, vm_page_size},
		{(mach_vm_address_t)UINTMAX_MAX, 1},
	};
	int numofranges = sizeof(ranges) / sizeof(ranges[0]);
	vm_offset_t read_address;
	mach_msg_type_number_t read_size;

	logv(
		"Reading various memory ranges wrapping around the "
		"address space...");
	for (i = 0; i < numofranges; i++) {
		kr = mach_vm_read(this_task, ranges[i].address, ranges[i].size, &read_address, &read_size);
		assert_mach_return(kr, KERN_INVALID_ADDRESS,
		    "mach_vm_read() at address 0x%jx with size "
		    "0x%jx (%ju) expected KERN_INVALID_ADDRESS",
		    (uintmax_t)ranges[i].address, (uintmax_t)ranges[i].size, (uintmax_t)ranges[i].size);
	}
	logv("Returned expected error on each range: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/********************************/
/* mach_vm_read() pattern tests */
/********************************/

/* Write a pattern on pre-allocated memory, read into a buffer and
 * verify the pattern on the buffer. */
void
write_read_verify_pattern(address_filter_t filter, boolean_t reversed, const char * pattern_name)
{
	mach_vm_address_t address = get_vm_address();

	write_pattern(filter, reversed, address, get_vm_size(), pattern_name);
	read_deallocate();
	/* Getting the address and size of the read buffer. */
	mach_vm_address_t read_address = get_vm_address();
	mach_vm_size_t read_size = get_vm_size();
	logv(
		"Verifying %s pattern on buffer of "
		"address 0x%jx and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)read_address, (uintmax_t)read_size, (uintmax_t)read_size);
	filter_addresses_do_else(filter, reversed, read_address, read_size, verify_address, read_zero, address);
	logv("Pattern verified on destination buffer.");
}

void
test_read_address_filled()
{
	write_read_verify_pattern(empty, TRUE, "address-filled");
}

void
test_read_checkerboard()
{
	write_read_verify_pattern(checkerboard, FALSE, "checkerboard");
}

void
test_read_reverse_checkerboard()
{
	write_read_verify_pattern(checkerboard, TRUE, "reverse checkerboard");
}

/***********************************/
/* mach_vm_write() edge case tests */
/***********************************/

/* Writing in VM_MAP_NULL fails. */
void
test_write_null_map()
{
	mach_vm_address_t address          = get_vm_address();
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx in NULL VM MAP...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_mach_return(mach_vm_write(VM_MAP_NULL, address, data, buffer_size), MACH_SEND_INVALID_DEST, "mach_vm_write()");
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_DEST));
}

/* Writing 0 bytes always succeeds. */
void
test_write_zero_size()
{
	set_buffer_size(0);
	write_buffer();
}

/*****************************************/
/* mach_vm_write() inaccessibility tests */
/*****************************************/

/* Writing a partially deallocated buffer fails. */
void
test_write_partially_deallocated_buffer()
{
	mach_vm_address_t address          = get_vm_address();
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t buffer_mid_point = (mach_vm_address_t)mach_vm_trunc_page(data + buffer_size / 2);

	logv(
		"Deallocating a mid-range buffer page at address "
		"0x%jx...",
		(uintmax_t)buffer_mid_point);
	deallocate_buffer_page_early(buffer_mid_point);
	logv("Page deallocated.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_write_return(address, data, buffer_size, MACH_SEND_INVALID_MEMORY);
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_MEMORY));
}

/* Writing a partially read-protected buffer fails. */
void
test_write_partially_unreadable_buffer()
{
	mach_vm_address_t address          = get_vm_address();
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t buffer_mid_point = (mach_vm_address_t)mach_vm_trunc_page(data + buffer_size / 2);

	logv(
		"Read-protecting a mid-range buffer page at address "
		"0x%jx...",
		(uintmax_t)buffer_mid_point);
	assert_mach_success(mach_vm_protect(mach_task_self(), buffer_mid_point, vm_page_size, FALSE, VM_PROT_WRITE),
	    "mach_vm_protect()");
	logv("Page read-protected.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_write_return(address, data, buffer_size, MACH_SEND_INVALID_MEMORY);
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_MEMORY));
}

/* Writing on partially deallocated memory fails. */
void
test_write_on_partially_deallocated_range()
{
	mach_vm_address_t address          = get_vm_address();
	mach_vm_address_t start            = mach_vm_trunc_page(address);
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Deallocating the first destination page at address "
		"0x%jx...",
		(uintmax_t)start);
	deallocate_vm_page_early(start);
	logv("Page deallocated.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_write_return(address, data, buffer_size, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Writing on partially unwritable memory fails. */
void
test_write_on_partially_unwritable_range()
{
	mach_vm_address_t address          = get_vm_address();
	mach_vm_address_t start            = mach_vm_trunc_page(address);
	vm_offset_t data                   = (vm_offset_t)get_buffer_address();
	mach_msg_type_number_t buffer_size = (mach_msg_type_number_t)get_buffer_size();

	/*  For sizes < msg_ool_size_small,
	 *  vm_map_copy_overwrite_nested() uses
	 *  vm_map_copyout_kernel_buffer() to read in the memory,
	 *  returning different errors, see 8217123. */
	kern_return_t kr_expected = (buffer_size < vm_page_size * 2) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv(
		"Write-protecting the first destination page at address "
		"0x%jx...",
		(uintmax_t)start);
	assert_mach_success(mach_vm_protect(mach_task_self(), start, vm_page_size, FALSE, VM_PROT_READ), "mach_vm_protect()");
	logv("Page write-protected.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)data, (uintmax_t)buffer_size, (uintmax_t)buffer_size, (uintmax_t)address);
	assert_write_return(address, data, buffer_size, kr_expected);
	logv("Returned expected error: %s.", mach_error_string(kr_expected));
}

/*********************************/
/* mach_vm_write() pattern tests */
/*********************************/

/* Verify that a zero-filled buffer and destination memory are still
 * zero-filled after writing. */
void
test_zero_filled_write()
{
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_vm_address()), round_page(get_vm_size() + 1), "zero-filled");
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_buffer_address()),
	    round_page(get_buffer_size() + get_buffer_offset()), "zero-filled");
}

/* Write a pattern on a buffer, write the buffer into some destination
 * memory, and verify the pattern on both buffer and destination. */
void
pattern_write(address_filter_t filter, boolean_t reversed, const char * pattern_name)
{
	mach_vm_address_t address        = get_vm_address();
	mach_vm_size_t size              = get_vm_size();
	mach_vm_address_t buffer_address = get_buffer_address();
	mach_vm_size_t buffer_size       = get_buffer_size();

	write_pattern(filter, reversed, buffer_address, buffer_size, pattern_name);
	write_buffer();
	verify_pattern(filter, reversed, buffer_address, buffer_size, pattern_name);
	logv(
		"Verifying %s pattern on destination of "
		"address 0x%jx and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)address, (uintmax_t)buffer_size, (uintmax_t)size);
	filter_addresses_do_else(filter, reversed, address, buffer_size, verify_address, read_zero, buffer_address);
	logv("Pattern verified on destination.");
}

void
test_address_filled_write()
{
	pattern_write(empty, TRUE, "address-filled");
}

void
test_checkerboard_write()
{
	pattern_write(checkerboard, FALSE, "checkerboard");
}

void
test_reverse_checkerboard_write()
{
	pattern_write(checkerboard, TRUE, "reverse checkerboard");
}

/**********************************/
/* mach_vm_copy() edge case tests */
/**********************************/

/* Copying in VM_MAP_NULL fails. */
void
test_copy_null_map()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Copying buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx in NULL VM MAP...",
		(uintmax_t)dest, (uintmax_t)size, (uintmax_t)size, (uintmax_t)source);
	assert_mach_return(mach_vm_copy(VM_MAP_NULL, source, size, dest), MACH_SEND_INVALID_DEST, "mach_vm_copy()");
	logv("Returned expected error: %s.", mach_error_string(MACH_SEND_INVALID_DEST));
}

void
copy_edge_size(mach_vm_size_t size, kern_return_t expected_kr)
{
	int i;
	kern_return_t kr;
	vm_map_t this_task            = mach_task_self();
	mach_vm_address_t addresses[] = {0x0,
		                         0x1,
		                         vm_page_size - 1,
		                         vm_page_size,
		                         vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX,
		                         (mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINTMAX_MAX};
	int numofaddresses     = sizeof(addresses) / sizeof(addresses[0]);
	mach_vm_address_t dest = 0;

	logv("Allocating 0x%jx (%ju) byte%s...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s");
	assert_allocate_success(&dest, 4096, VM_FLAGS_ANYWHERE);
	logv("Copying 0x%jx (%ju) bytes at various addresses...", (uintmax_t)size, (uintmax_t)size);
	for (i = 0; i < numofaddresses; i++) {
		kr = mach_vm_copy(this_task, addresses[i], size, dest);
		assert_mach_return(kr, expected_kr,
		    "mach_vm_copy() at "
		    "address 0x%jx expected %s",
		    (uintmax_t)addresses[i], mach_error_string(expected_kr));
	}
	logv(
		"mach_vm_copy() returned expected value in each case: "
		"%s.",
		mach_error_string(expected_kr));

	deallocate_range(dest, 4096);
}

/* Copying 0 bytes always succeeds. */
void
test_copy_zero_size()
{
	copy_edge_size(0, KERN_SUCCESS);
}

/* Copying 4GB or higher always fails. */
void
test_copy_invalid_large_size()
{
	copy_edge_size((mach_vm_size_t)UINT_MAX - 1, KERN_INVALID_ADDRESS);
}

/* Reading a range wrapped around the address space fails. */
void
test_copy_wrapped_around_ranges()
{
	int i;
	kern_return_t kr;
	vm_map_t this_task = mach_task_self();
	struct {
		mach_vm_address_t address;
		mach_vm_size_t size;
	} ranges[] = {
		{(mach_vm_address_t)(UINTMAX_MAX - UINT_MAX + 1), (mach_vm_size_t)UINT_MAX},
		{(mach_vm_address_t)(UINTMAX_MAX - UINT_MAX + vm_page_size), (mach_vm_size_t)(UINT_MAX - vm_page_size + 1)},
		{(mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1, vm_page_size},
		{(mach_vm_address_t)UINTMAX_MAX, 1},
	};
	int numofranges        = sizeof(ranges) / sizeof(ranges[0]);
	mach_vm_address_t dest = 0;

	logv("Allocating 0x1000 (4096) bytes...");
	assert_allocate_success(&dest, 4096, VM_FLAGS_ANYWHERE);

	logv(
		"Copying various memory ranges wrapping around the "
		"address space...");
	for (i = 0; i < numofranges; i++) {
		kr = mach_vm_copy(this_task, ranges[i].address, ranges[i].size, dest);
		assert_mach_return(kr, KERN_INVALID_ADDRESS,
		    "mach_vm_copy() at address 0x%jx with size "
		    "0x%jx (%ju) expected KERN_INVALID_ADDRESS",
		    (uintmax_t)ranges[i].address, (uintmax_t)ranges[i].size, (uintmax_t)ranges[i].size);
	}
	logv("Returned expected error on each range: %s.", mach_error_string(KERN_INVALID_ADDRESS));

	deallocate_range(dest, 4096);
}

/********************************/
/* mach_vm_copy() pattern tests */
/********************************/

/* Write a pattern on pre-allocated region, copy into another region
 * and verify the pattern in the region. */
void
write_copy_verify_pattern(address_filter_t filter, boolean_t reversed, const char * pattern_name)
{
	mach_vm_address_t source = get_vm_address();
	mach_vm_size_t src_size = get_vm_size();
	write_pattern(filter, reversed, source, src_size, pattern_name);
	/* Getting the address and size of the dest region */
	mach_vm_address_t dest  = get_buffer_address();
	mach_vm_size_t dst_size = get_buffer_size();

	logv(
		"Copying memory region of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)dst_size, (uintmax_t)dst_size, (uintmax_t)dest);
	assert_copy_success(source, dst_size, dest);
	logv(
		"Verifying %s pattern in region of "
		"address 0x%jx and size 0x%jx (%ju)...",
		pattern_name, (uintmax_t)dest, (uintmax_t)dst_size, (uintmax_t)dst_size);
	filter_addresses_do_else(filter, reversed, dest, dst_size, verify_address, read_zero, source);
	logv("Pattern verified on destination region.");
}

void
test_copy_address_filled()
{
	write_copy_verify_pattern(empty, TRUE, "address-filled");
}

void
test_copy_checkerboard()
{
	write_copy_verify_pattern(checkerboard, FALSE, "checkerboard");
}

void
test_copy_reverse_checkerboard()
{
	write_copy_verify_pattern(checkerboard, TRUE, "reverse checkerboard");
}

/* Verify that a zero-filled source and destination memory are still
 * zero-filled after writing. */
void
test_zero_filled_copy_dest()
{
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_vm_address()), round_page(get_vm_size() + 1), "zero-filled");
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_buffer_address()),
	    round_page(get_buffer_size() + get_buffer_offset()), "zero-filled");
}

/****************************************/
/* mach_vm_copy() inaccessibility tests */
/****************************************/

/* Copying partially deallocated memory fails. */
void
test_copy_partially_deallocated_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_size_t size         = get_vm_size();
	mach_vm_address_t mid_point = mach_vm_trunc_page(source + size / 2);
	mach_vm_address_t dest      = 0;

	logv("Deallocating a mid-range page at address 0x%jx...", (uintmax_t)mid_point);
	deallocate_vm_page_early(mid_point);
	logv("Page deallocated.");

	logv("Copying 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)source);

	assert_allocate_copy_return(source, size, &dest, KERN_INVALID_ADDRESS);

	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));

	deallocate_range(dest, size);
}

/* Copy partially read-protected memory fails. */
void
test_copy_partially_unreadable_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_size_t size         = get_vm_size();
	mach_vm_address_t mid_point = mach_vm_trunc_page(source + size / 2);
	mach_vm_address_t dest      = 0;

	/*  For sizes < 1 page, vm_map_copyin_common() uses
	 *  vm_map_copyin_kernel_buffer() to read in the memory,
	 *  returning different errors, see 8182239. */
	kern_return_t kr_expected = (size < vm_page_size) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv("Read-protecting a mid-range page at address 0x%jx...", (uintmax_t)mid_point);
	assert_mach_success(mach_vm_protect(mach_task_self(), mid_point, vm_page_size, FALSE, VM_PROT_WRITE), "mach_vm_protect()");
	logv("Page read-protected.");

	logv("Copying 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size, (size == 1) ? "" : "s",
	    (uintmax_t)source);
	assert_allocate_copy_return(source, size, &dest, kr_expected);
	logv("Returned expected error: %s.", mach_error_string(kr_expected));

	deallocate_range(dest, size);
}

/* Copying to a partially deallocated region fails. */
void
test_copy_dest_partially_deallocated_region()
{
	mach_vm_address_t dest             = get_vm_address();
	mach_vm_address_t source           = get_buffer_address();
	mach_msg_type_number_t size        = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t source_mid_point = (mach_vm_address_t)mach_vm_trunc_page(dest + size / 2);

	logv(
		"Deallocating a mid-range source page at address "
		"0x%jx...",
		(uintmax_t)source_mid_point);
	deallocate_vm_page_early(source_mid_point);
	logv("Page deallocated.");

	logv(
		"Copying region of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);
	assert_copy_return(source, size, dest, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Copying from a partially deallocated region fails. */
void
test_copy_source_partially_deallocated_region()
{
	mach_vm_address_t source           = get_vm_address();
	mach_vm_address_t dest             = get_buffer_address();
	mach_msg_type_number_t size        = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t source_mid_point = (mach_vm_address_t)mach_vm_trunc_page(source + size / 2);

	logv(
		"Deallocating a mid-range source page at address "
		"0x%jx...",
		(uintmax_t)source_mid_point);
	deallocate_vm_page_early(source_mid_point);
	logv("Page deallocated.");

	logv(
		"Copying region of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);
	assert_copy_return(source, size, dest, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Copying from a partially read-protected region fails. */
void
test_copy_source_partially_unreadable_region()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t mid_point = (mach_vm_address_t)mach_vm_trunc_page(source + size / 2);
	kern_return_t kr            = (size < vm_page_size * 2) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv(
		"Read-protecting a mid-range buffer page at address "
		"0x%jx...",
		(uintmax_t)mid_point);
	assert_mach_success(mach_vm_protect(mach_task_self(), mid_point, vm_page_size, FALSE, VM_PROT_WRITE), "mach_vm_protect()");
	logv("Page read-protected.");

	logv(
		"Copying region at address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);

	assert_copy_return(source, size, dest, kr);
	logv("Returned expected error: %s.", mach_error_string(kr));
}

/* Copying to a partially write-protected region fails. */
void
test_copy_dest_partially_unwriteable_region()
{
	mach_vm_address_t dest      = get_vm_address();
	mach_vm_address_t source    = get_buffer_address();
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();
	mach_vm_address_t mid_point = (mach_vm_address_t)mach_vm_trunc_page(dest + size / 2);

	logv(
		"Read-protecting a mid-range buffer page at address "
		"0x%jx...",
		(uintmax_t)mid_point);
	assert_mach_success(mach_vm_protect(mach_task_self(), mid_point, vm_page_size, FALSE, VM_PROT_READ), "mach_vm_protect()");
	logv("Page read-protected.");
	logv(
		"Copying region at address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)source, (uintmax_t)size, (uintmax_t)size, (uintmax_t)dest);

	// The type of failure is not guaranteed to be consistent between architectures, so we just make sure it fails.
	assert_copy_failure(source, size, dest);
	logv("Returned expected error.");
}

/* Copying on partially deallocated memory fails. */
void
test_copy_source_on_partially_deallocated_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_vm_address_t start     = mach_vm_trunc_page(source);
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Deallocating the first source page at address "
		"0x%jx...",
		(uintmax_t)start);
	deallocate_vm_page_early(start);
	logv("Page deallocated.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)dest, (uintmax_t)size, (uintmax_t)size, (uintmax_t)source);
	assert_copy_return(source, size, dest, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Copying on partially deallocated memory fails. */
void
test_copy_dest_on_partially_deallocated_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_vm_address_t start     = mach_vm_trunc_page(dest);
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	logv(
		"Deallocating the first destination page at address "
		"0x%jx...",
		(uintmax_t)start);
	deallocate_buffer_page_early(start);
	logv("Page deallocated.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)dest, (uintmax_t)size, (uintmax_t)size, (uintmax_t)source);
	assert_copy_return(source, size, dest, KERN_INVALID_ADDRESS);
	logv("Returned expected error: %s.", mach_error_string(KERN_INVALID_ADDRESS));
}

/* Copying on partially unwritable memory fails. */
void
test_copy_dest_on_partially_unwritable_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_vm_address_t start     = mach_vm_trunc_page(dest);
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	/*  For sizes < msg_ool_size_small,
	 *  vm_map_copy_overwrite_nested() uses
	 *  vm_map_copyout_kernel_buffer() to read in the memory,
	 *  returning different errors, see 8217123. */
	kern_return_t kr_expected = (size < vm_page_size * 2) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv(
		"Write-protecting the first destination page at address "
		"0x%jx...",
		(uintmax_t)start);
	assert_mach_success(mach_vm_protect(mach_task_self(), start, vm_page_size, FALSE, VM_PROT_READ), "mach_vm_protect()");
	logv("Page write-protected.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)dest, (uintmax_t)size, (uintmax_t)size, (uintmax_t)source);
	assert_copy_return(source, size, dest, kr_expected);
	logv("Returned expected error: %s.", mach_error_string(kr_expected));
}

/* Copying on partially unreadable memory fails. */
void
test_copy_source_on_partially_unreadable_range()
{
	mach_vm_address_t source    = get_vm_address();
	mach_vm_address_t dest      = get_buffer_address();
	mach_vm_address_t start     = mach_vm_trunc_page(source);
	mach_msg_type_number_t size = (mach_msg_type_number_t)get_buffer_size();

	/*  For sizes < msg_ool_size_small,
	 *  vm_map_copy_overwrite_nested() uses
	 *  vm_map_copyout_kernel_buffer() to read in the memory,
	 *  returning different errors, see 8217123. */
	kern_return_t kr_expected = (size < vm_page_size * 2) ? KERN_INVALID_ADDRESS : KERN_PROTECTION_FAILURE;

	logv(
		"Read-protecting the first destination page at address "
		"0x%jx...",
		(uintmax_t)start);
	assert_mach_success(mach_vm_protect(mach_task_self(), start, vm_page_size, FALSE, VM_PROT_WRITE), "mach_vm_protect()");
	logv("Page read-protected.");

	logv(
		"Writing buffer of address 0x%jx and size 0x%jx (%ju), on "
		"memory at address 0x%jx...",
		(uintmax_t)dest, (uintmax_t)size, (uintmax_t)size, (uintmax_t)source);
	assert_copy_return(source, size, dest, kr_expected);
	logv("Returned expected error: %s.", mach_error_string(kr_expected));
}

/********************************/
/* mach_vm_protect() main tests */
/********************************/

void
test_zero_filled_extended()
{
	verify_pattern(empty, FALSE, mach_vm_trunc_page(get_vm_address()), round_page(get_vm_size() + 1), "zero-filled");
}

/* Allocated region is still zero-filled after read-protecting it and
 * then restoring read-access. */
void
test_zero_filled_readprotect()
{
	mach_vm_address_t address = get_vm_address();
	mach_vm_size_t size       = get_vm_size();

	logv("Setting read access on 0x%jx (%ju) byte%s at address 0x%jx...", (uintmax_t)size, (uintmax_t)size,
	    (size == 1) ? "" : "s", (uintmax_t)address);
	assert_mach_success(mach_vm_protect(mach_task_self(), address, size, FALSE, VM_PROT_DEFAULT), "mach_vm_protect()");
	logv("Region has read access.");
	test_zero_filled_extended();
}

void
verify_protection(vm_prot_t protection, const char * protection_name)
{
	mach_vm_address_t address    = get_vm_address();
	mach_vm_size_t size          = get_vm_size();
	mach_vm_size_t original_size = size;
	vm_region_basic_info_data_64_t info;
	mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
	mach_port_t unused;

	logv(
		"Verifying %s-protection on region of address 0x%jx and "
		"size 0x%jx (%ju) with mach_vm_region()...",
		protection_name, (uintmax_t)address, (uintmax_t)size, (uintmax_t)size);
	assert_mach_success(
		mach_vm_region(mach_task_self(), &address, &size, VM_REGION_BASIC_INFO_64, (vm_region_info_t)&info, &count, &unused),
		"mach_vm_region()");
	if (original_size) {
		T_QUIET; T_ASSERT_EQ((info.protection & protection), 0,
		    "Region "
		    "is unexpectedly %s-unprotected.",
		    protection_name);
		logv("Region is %s-protected as expected.", protection_name);
	} else {
		T_QUIET; T_ASSERT_NE(info.protection & protection, 0,
		    "Region is "
		    "unexpectedly %s-protected.",
		    protection_name);
		logv("Region is %s-unprotected as expected.", protection_name);
	}
}

void
test_verify_readprotection()
{
	verify_protection(VM_PROT_READ, "read");
}

void
test_verify_writeprotection()
{
	verify_protection(VM_PROT_WRITE, "write");
}

/******************************/
/* Protection bus error tests */
/******************************/

/* mach_vm_protect() affects the smallest aligned region (integral
 * number of pages) containing the given range. */

/* Addresses in read-protected range are inaccessible. */
void
access_readprotected_range_address(mach_vm_address_t address, const char * position)
{
	logv("Reading from %s 0x%jx of read-protected range...", position, (uintmax_t)address);
	mach_vm_address_t bad_value = MACH_VM_ADDRESS_T(address);
	T_ASSERT_FAIL("Unexpectedly read value 0x%jx at address 0x%jx. "
	    "Should have died with signal SIGBUS.",
	    (uintmax_t)bad_value, (uintmax_t)address);
}

/* Start of read-protected range is inaccessible. */
void
test_access_readprotected_range_start()
{
	access_readprotected_range_address(mach_vm_trunc_page(get_vm_address()), "start");
}

/* Middle of read-protected range is inaccessible. */
void
test_access_readprotected_range_middle()
{
	mach_vm_address_t address = get_vm_address();
	access_readprotected_range_address(mach_vm_trunc_page(address) + (aligned_size(address, get_vm_size()) >> 1), "middle");
}

/* End of read-protected range is inaccessible. */
void
test_access_readprotected_range_end()
{
	access_readprotected_range_address(round_page(get_vm_address() + get_vm_size()) - vm_address_size, "end");
}

/* Addresses in write-protected range are unwritable. */
void
write_writeprotected_range_address(mach_vm_address_t address, const char * position)
{
	logv("Writing on %s 0x%jx of write-protected range...", position, (uintmax_t)address);
	MACH_VM_ADDRESS_T(address) = 0x0;
	T_ASSERT_FAIL("Unexpectedly wrote value 0x0 value at address 0x%jx. "
	    "Should have died with signal SIGBUS.",
	    (uintmax_t)address);
}

/* Start of write-protected range is unwritable. */
void
test_write_writeprotected_range_start()
{
	write_writeprotected_range_address(mach_vm_trunc_page(get_vm_address()), "start");
}

/* Middle of write-protected range is unwritable. */
void
test_write_writeprotected_range_middle()
{
	mach_vm_address_t address = get_vm_address();
	write_writeprotected_range_address(mach_vm_trunc_page(address) + (aligned_size(address, get_vm_size()) >> 1), "middle");
}

/* End of write-protected range is unwritable. */
void
test_write_writeprotected_range_end()
{
	write_writeprotected_range_address(round_page(get_vm_address() + get_vm_size()) - vm_address_size, "end");
}

/*************************************/
/* mach_vm_protect() edge case tests */
/*************************************/

void
protect_zero_size(vm_prot_t protection, const char * protection_name)
{
	int i;
	kern_return_t kr;
	vm_map_t this_task            = mach_task_self();
	mach_vm_address_t addresses[] = {0x0,
		                         0x1,
		                         vm_page_size - 1,
		                         vm_page_size,
		                         vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINT_MAX,
		                         (mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1,
		                         (mach_vm_address_t)UINTMAX_MAX};
	int numofaddresses = sizeof(addresses) / sizeof(addresses[0]);

	logv("%s-protecting 0x0 (0) bytes at various addresses...", protection_name);
	for (i = 0; i < numofaddresses; i++) {
		kr = mach_vm_protect(this_task, addresses[i], 0, FALSE, protection);
		assert_mach_success(kr,
		    "mach_vm_protect() at "
		    "address 0x%jx unexpectedly failed: %s.",
		    (uintmax_t)addresses[i], mach_error_string(kr));
	}
	logv("Protection successful.");
}

void
test_readprotect_zero_size()
{
	protect_zero_size(VM_PROT_READ, "Read");
}

void
test_writeprotect_zero_size()
{
	protect_zero_size(VM_PROT_WRITE, "Write");
}

/* Protecting a range wrapped around the address space fails. */
void
protect_wrapped_around_ranges(vm_prot_t protection, const char * protection_name)
{
	int i;
	kern_return_t kr;
	vm_map_t this_task = mach_task_self();
	struct {
		mach_vm_address_t address;
		mach_vm_size_t size;
	} ranges[] = {
		{0x1, (mach_vm_size_t)UINTMAX_MAX},
		{vm_page_size, (mach_vm_size_t)UINTMAX_MAX - vm_page_size + 1},
		{(mach_vm_address_t)UINTMAX_MAX - vm_page_size + 1, vm_page_size},
		{(mach_vm_address_t)UINTMAX_MAX, 1},
	};
	int numofranges = sizeof(ranges) / sizeof(ranges[0]);

	logv(
		"%s-protecting various memory ranges wrapping around the "
		"address space...",
		protection_name);
	for (i = 0; i < numofranges; i++) {
		kr = mach_vm_protect(this_task, ranges[i].address, ranges[i].size, FALSE, protection);
		assert_mach_return(kr, KERN_INVALID_ARGUMENT,
		    "mach_vm_protect() with address 0x%jx and size "
		    "0x%jx (%ju) expected KERN_INVALID_ARGUMENT",
		    (uintmax_t)ranges[i].address, (uintmax_t)ranges[i].size, (uintmax_t)ranges[i].size);
	}
	logv("Returned expected error on each range: %s.", mach_error_string(KERN_INVALID_ARGUMENT));
}

void
test_readprotect_wrapped_around_ranges()
{
	protect_wrapped_around_ranges(VM_PROT_READ, "Read");
}

void
test_writeprotect_wrapped_around_ranges()
{
	protect_wrapped_around_ranges(VM_PROT_WRITE, "Write");
}

/*******************/
/* vm_copy() tests */
/*******************/

/* Verify the address space is being shared. */
void
assert_share_mode(mach_vm_address_t address, unsigned share_mode, const char * share_mode_name)
{
}

/* Do the vm_copy() and verify its success. */
void
assert_vmcopy_success(vm_address_t src, vm_address_t dst, const char * source_name)
{
	kern_return_t kr;
	mach_vm_size_t size = get_vm_size();

	logv("Copying (using mach_vm_copy()) from a %s source...", source_name);
	kr = mach_vm_copy(mach_task_self(), src, size, dst);
	assert_mach_success(kr,
	    "mach_vm_copy() with the source address "
	    "0x%jx, designation address 0x%jx, and size 0x%jx (%ju) "
	    "unexpectedly failed.",
	    (uintmax_t)src, (uintmax_t)dst, (uintmax_t)size, (uintmax_t)size);
	logv("Copy (mach_vm_copy()) was successful as expected.");
}

void
write_region(mach_vm_address_t address, mach_vm_size_t start)
{
	mach_vm_size_t size = get_vm_size();

	filter_addresses_do_else(empty, FALSE, address, size, write_address, write_address, start);
}

void
verify_region(mach_vm_address_t address, mach_vm_address_t start)
{
	mach_vm_size_t size = get_vm_size();

	filter_addresses_do_else(empty, FALSE, address, size, verify_address, verify_address, start);
}

/* Perform the post vm_copy() action and verify its results. */
void
modify_one_and_verify_all_regions(vm_address_t src, vm_address_t dst, vm_address_t shared_copied, boolean_t shared)
{
	int action          = get_vmcopy_post_action();

	/* Do the post vm_copy() action. */
	switch (action) {
	case VMCOPY_MODIFY_SRC:
		logv("Modifying: source%s...", shared ? " (shared with other region)" : "");
		write_region(src, 1);
		break;

	case VMCOPY_MODIFY_DST:
		logv("Modifying: destination...");
		write_region(dst, 1);
		break;

	case VMCOPY_MODIFY_SHARED_COPIED:
		/* If no shared_copied then no need to verify (nothing changed). */
		if (!shared_copied) {
			return;
		}
		logv("Modifying: shared/copied%s...", shared ? " (shared with source region)" : "");
		write_region(shared_copied, 1);
		break;

	default:
		T_ASSERT_FAIL("Unknown post vm_copy() action (%d)", action);
	}
	logv("Modification was successful as expected.");

	/* Verify all the regions with what is expected. */
	logv("Verifying: source... ");
	verify_region(src, (VMCOPY_MODIFY_SRC == action || (shared && VMCOPY_MODIFY_SHARED_COPIED == action)) ? 1 : 0);
	logv("destination... ");
	verify_region(dst, (VMCOPY_MODIFY_DST == action) ? 1 : 0);
	if (shared_copied) {
		logv("shared/copied... ");
		verify_region(shared_copied, (VMCOPY_MODIFY_SHARED_COPIED == action || (shared && VMCOPY_MODIFY_SRC == action)) ? 1 : 0);
	}
	logv("Verification was successful as expected.");
}

/* Test source being a simple fresh region. */
void
test_vmcopy_fresh_source()
{
	mach_vm_size_t size = get_vm_size();
	mach_vm_address_t src, dst;

	if (get_vmcopy_post_action() == VMCOPY_MODIFY_SHARED_COPIED) {
		/* No shared/copied region to modify so just return. */
		logv("No shared/copied region as expected.");
		return;
	}

	assert_allocate_success(&src, size, TRUE);

	assert_share_mode(src, SM_EMPTY, "SM_EMPTY");

	write_region(src, 0);

	assert_allocate_success(&dst, size, TRUE);

	assert_vmcopy_success(src, dst, "freshly allocated");

	modify_one_and_verify_all_regions(src, dst, 0, FALSE);

	assert_deallocate_success(src, size);
	assert_deallocate_success(dst, size);
}

/* Test source copied from a shared region. */
void
test_vmcopy_shared_source()
{
	mach_vm_size_t size = get_vm_size();
	mach_vm_address_t src, dst, shared;
	int action = get_vmcopy_post_action();
	int pid, status;

	assert_allocate_success(&src, size, TRUE);

	assert_mach_success(mach_vm_inherit(mach_task_self(), src, size, VM_INHERIT_SHARE), "mach_vm_inherit()");

	write_region(src, 0);

	pid = fork();
	if (pid == 0) {
		/* Verify that the child's 'src' is shared with the
		 *  parent's src */
		assert_share_mode(src, SM_SHARED, "SM_SHARED");
		assert_allocate_success(&dst, size, TRUE);
		assert_vmcopy_success(src, dst, "shared");
		if (VMCOPY_MODIFY_SHARED_COPIED == action) {
			logv("Modifying: shared...");
			write_region(src, 1);
			logv("Modification was successsful as expected.");
			logv("Verifying: source... ");
			verify_region(src, 1);
			logv("destination...");
			verify_region(dst, (VMCOPY_MODIFY_DST == action) ? 1 : 0);
			logv("Verification was successful as expected.");
		} else {
			modify_one_and_verify_all_regions(src, dst, 0, TRUE);
		}
		assert_deallocate_success(dst, size);
		exit(0);
	} else if (pid > 0) {
		/* In the parent the src becomes the shared */
		shared = src;
		wait(&status);
		if (WEXITSTATUS(status) != 0) {
			exit(status);
		}
		/* verify shared (shared with child's src) */
		logv("Verifying: shared...");
		verify_region(shared, (VMCOPY_MODIFY_SHARED_COPIED == action || VMCOPY_MODIFY_SRC == action) ? 1 : 0);
		logv("Verification was successful as expected.");
	} else {
		T_WITH_ERRNO; T_ASSERT_FAIL("fork failed");
	}

	assert_deallocate_success(src, size);
}

/* Test source copied from another mapping. */
void
test_vmcopy_copied_from_source()
{
	mach_vm_size_t size = get_vm_size();
	mach_vm_address_t src, dst, copied;

	assert_allocate_success(&copied, size, TRUE);
	write_region(copied, 0);

	assert_allocate_success(&src, size, TRUE);

	assert_mach_success(mach_vm_copy(mach_task_self(), copied, size, src), "mach_vm_copy()");

	assert_share_mode(src, SM_COW, "SM_COW");

	assert_allocate_success(&dst, size, TRUE);

	assert_vmcopy_success(src, dst, "copied from");

	modify_one_and_verify_all_regions(src, dst, copied, FALSE);

	assert_deallocate_success(src, size);
	assert_deallocate_success(dst, size);
	assert_deallocate_success(copied, size);
}

/* Test source copied to another mapping. */
void
test_vmcopy_copied_to_source()
{
	mach_vm_size_t size = get_vm_size();
	mach_vm_address_t src, dst, copied;

	assert_allocate_success(&src, size, TRUE);
	write_region(src, 0);

	assert_allocate_success(&copied, size, TRUE);

	assert_mach_success(mach_vm_copy(mach_task_self(), src, size, copied), "mach_vm_copy()");

	assert_share_mode(src, SM_COW, "SM_COW");

	assert_allocate_success(&dst, size, TRUE);

	assert_vmcopy_success(src, dst, "copied to");

	modify_one_and_verify_all_regions(src, dst, copied, FALSE);

	assert_deallocate_success(src, size);
	assert_deallocate_success(dst, size);
	assert_deallocate_success(copied, size);
}

/* Test a truedshared source copied. */
void
test_vmcopy_trueshared_source()
{
	mach_vm_size_t size   = get_vm_size();
	mach_vm_address_t src = 0x0, dst, shared;
	vm_prot_t cur_protect = (VM_PROT_READ | VM_PROT_WRITE);
	vm_prot_t max_protect = (VM_PROT_READ | VM_PROT_WRITE);
	mem_entry_name_port_t mem_obj;

	assert_allocate_success(&shared, size, TRUE);
	write_region(shared, 0);

	assert_mach_success(mach_make_memory_entry_64(mach_task_self(), &size, (memory_object_offset_t)shared, cur_protect, &mem_obj,
	    (mem_entry_name_port_t)NULL),
	    "mach_make_memory_entry_64()");
	assert_mach_success(
		mach_vm_map(mach_task_self(), &src, size, 0, TRUE, mem_obj, 0, FALSE, cur_protect, max_protect, VM_INHERIT_NONE),
		"mach_vm_map()");

	assert_share_mode(src, SM_TRUESHARED, "SM_TRUESHARED");

	assert_allocate_success(&dst, size, TRUE);

	assert_vmcopy_success(src, dst, "true shared");

	modify_one_and_verify_all_regions(src, dst, shared, TRUE);

	assert_deallocate_success(src, size);
	assert_deallocate_success(dst, size);
	assert_deallocate_success(shared, size);
}

/* Test a private aliazed source copied. */
void
test_vmcopy_private_aliased_source()
{
	mach_vm_size_t size   = get_vm_size();
	mach_vm_address_t src = 0x0, dst, shared;
	vm_prot_t cur_protect = (VM_PROT_READ | VM_PROT_WRITE);
	vm_prot_t max_protect = (VM_PROT_READ | VM_PROT_WRITE);

	assert_allocate_success(&shared, size, TRUE);
	write_region(shared, 0);

	assert_mach_success(mach_vm_remap(mach_task_self(), &src, size, 0, TRUE, mach_task_self(), shared, FALSE, &cur_protect,
	    &max_protect, VM_INHERIT_NONE),
	    "mach_vm_remap()");

	assert_share_mode(src, SM_PRIVATE_ALIASED, "SM_PRIVATE_ALIASED");

	assert_allocate_success(&dst, size, TRUE);

	assert_vmcopy_success(src, dst, "true shared");

	modify_one_and_verify_all_regions(src, dst, shared, TRUE);

	assert_deallocate_success(src, size);
	assert_deallocate_success(dst, size);
	assert_deallocate_success(shared, size);
}

/*************/
/* VM Suites */
/*************/

void
run_allocate_test_suites()
{
	UnitTests allocate_main_tests = {
		{"Allocated address is nonzero iff size is nonzero", test_nonzero_address_iff_nonzero_size, 0},
		{"Allocated address is page-aligned", test_aligned_address, 0},
		{"Allocated memory is zero-filled", test_zero_filled, 0},
		{"Write and verify address-filled pattern", test_write_address_filled, 0},
		{"Write and verify checkerboard pattern", test_write_checkerboard, 0},
		{"Write and verify reverse checkerboard pattern", test_write_reverse_checkerboard, 0},
		{"Write and verify page ends pattern", test_write_page_ends, 0},
		{"Write and verify page interiors pattern", test_write_page_interiors, 0},
		{"Reallocate allocated pages", test_reallocate_pages, 0},
	};
	UnitTests allocate_address_error_tests = {
		{"Allocate at address zero", test_allocate_at_zero, 0},
		{"Allocate at a 2 MB boundary-unaligned, page-aligned "
		 "address",
		 test_allocate_2MB_boundary_unaligned_page_aligned_address, 0},
	};
	UnitTests allocate_argument_error_tests = {
		{"Allocate in NULL VM map", test_allocate_in_null_map, 0},
		{"Allocate with kernel flags", test_allocate_with_kernel_flags, 0},
		{"Allocate super-page with incompatible flags", test_allocate_superpage_with_incompatible_flags, 0},
	};
	UnitTests allocate_fixed_size_tests = {
		{"Allocate zero size", test_allocate_zero_size, 0},
		{"Allocate overflowing size", test_allocate_overflowing_size, 0},
		{"Allocate a page with highest address hint", test_allocate_page_with_highest_address_hint, 0},
		{"Allocate two pages and verify first fit strategy", test_allocate_first_fit_pages, 0},
	};
	UnitTests allocate_invalid_large_size_test = {
		{"Allocate invalid large size", test_allocate_invalid_large_size, 0},
	};
	UnitTests mach_vm_map_protection_inheritance_error_test = {
		{"mach_vm_map() with invalid protection/inheritance "
		 "arguments",
		 test_mach_vm_map_protection_inheritance_error, 0},
	};
	UnitTests mach_vm_map_large_mask_overflow_error_test = {
		{"mach_vm_map() with large address mask", test_mach_vm_map_large_mask_overflow_error, 0},
	};

	/* Run the test suites with various allocators and VM sizes, and
	 *  unspecified or fixed (page-aligned or page-unaligned),
	 *  addresses. */
	for (allocators_idx = 0; allocators_idx < numofallocators; allocators_idx++) {
		for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
			for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
				for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
					/* An allocated address will be page-aligned. */
					/* Only run the zero size mach_vm_map() error tests in the
					 *  unspecified address case, since we won't be able to retrieve a
					 *  fixed address for allocation. See 8003930. */
					if ((flags_idx == ANYWHERE && alignments_idx == UNALIGNED) ||
					    (allocators_idx != MACH_VM_ALLOCATE && sizes_idx == ZERO_BYTES && flags_idx == FIXED)) {
						continue;
					}
					run_suite(set_up_allocator_and_vm_variables, allocate_argument_error_tests, do_nothing,
					    "%s argument error tests, %s%s address, "
					    "%s size: 0x%jx (%ju)",
					    allocators[allocators_idx].description, address_flags[flags_idx].description,
					    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
					    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
					    (uintmax_t)vm_sizes[sizes_idx].size);
					/* mach_vm_map() only protection and inheritance error
					 *  tests. */
					if (allocators_idx != MACH_VM_ALLOCATE) {
						run_suite(set_up_allocator_and_vm_variables, mach_vm_map_protection_inheritance_error_test, do_nothing,
						    "%s protection and inheritance "
						    "error test, %s%s address, %s size: 0x%jx "
						    "(%ju)",
						    allocators[allocators_idx].description, address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size);
					}
					/* mach_vm_map() cannot allocate 0 bytes, see 8003930. */
					if (allocators_idx == MACH_VM_ALLOCATE || sizes_idx != ZERO_BYTES) {
						run_suite(set_up_allocator_and_vm_variables_and_allocate, allocate_main_tests, deallocate,
						    "%s main "
						    "allocation tests, %s%s address, %s size: 0x%jx "
						    "(%ju)",
						    allocators[allocators_idx].description, address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size);
					}
				}
			}
			run_suite(set_up_allocator_and_vm_size, allocate_address_error_tests, do_nothing,
			    "%s address "
			    "error allocation tests, %s size: 0x%jx (%ju)",
			    allocators[allocators_idx].description, vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
			    (uintmax_t)vm_sizes[sizes_idx].size);
		}
		run_suite(set_up_allocator, allocate_fixed_size_tests, do_nothing, "%s fixed size allocation tests",
		    allocators[allocators_idx].description);
		run_suite(set_up_allocator, allocate_invalid_large_size_test, do_nothing, "%s invalid large size allocation test",
		    allocators[allocators_idx].description);
	}
	/* mach_vm_map() only large mask overflow tests. */
	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		run_suite(set_up_vm_size, mach_vm_map_large_mask_overflow_error_test, do_nothing,
		    "mach_vm_map() large mask overflow "
		    "error test, size: 0x%jx (%ju)",
		    (uintmax_t)vm_sizes[sizes_idx].size, (uintmax_t)vm_sizes[sizes_idx].size);
	}
}

void
run_deallocate_test_suites()
{
	UnitTests access_deallocated_memory_tests = {
		{"Read start of deallocated range", test_access_deallocated_range_start, SIGSEGV},
		{"Read middle of deallocated range", test_access_deallocated_range_middle, SIGSEGV},
		{"Read end of deallocated range", test_access_deallocated_range_end, SIGSEGV},
	};
	UnitTests deallocate_reallocate_tests = {
		{"Deallocate twice", test_deallocate_twice},
		{"Write pattern, deallocate, reallocate (deallocated "
		 "memory is inaccessible), and verify memory is "
		 "zero-filled",
		 test_write_pattern_deallocate_reallocate_zero_filled, 0},
	};
	UnitTests deallocate_null_map_test = {
		{"Deallocate in NULL VM map", test_deallocate_in_null_map, 0},
	};
	UnitTests deallocate_edge_case_tests = {
		{"Deallocate zero size ranges", test_deallocate_zero_size_ranges, 0},
		{"Deallocate wrapped around memory ranges", test_deallocate_wrapped_around_ranges, 0},
	};
	UnitTests deallocate_suicide_test = {
		{"Deallocate whole address space", test_deallocate_suicide, -1},
	};

	/* All allocations done with mach_vm_allocate(). */
	set_allocator(wrapper_mach_vm_allocate);

	/* Run the test suites with various VM sizes, and unspecified or
	 *  fixed (page-aligned or page-unaligned), addresses. */
	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
			for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
				/* An allocated address will be page-aligned. */
				if (flags_idx == ANYWHERE && alignments_idx == UNALIGNED) {
					continue;
				}
				/* Accessing deallocated memory should cause a segmentation
				 *  fault. */
				/* Nothing gets deallocated if size is zero. */
				if (sizes_idx != ZERO_BYTES) {
					run_suite(set_up_vm_variables_and_allocate, access_deallocated_memory_tests, do_nothing,
					    "Deallocated memory access tests, "
					    "%s%s address, %s size: 0x%jx (%ju)",
					    address_flags[flags_idx].description,
					    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
					    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
					    (uintmax_t)vm_sizes[sizes_idx].size);
				}
				/* Deallocating zero size range should pass */
				if (vm_sizes[sizes_idx].size == 0) {
					deallocate_reallocate_tests[0].expected_signal = 0;
				} else {
					deallocate_reallocate_tests[0].expected_signal = _expected_vm_exc_guard_signal;
				}
				run_suite(set_up_vm_variables_and_allocate, deallocate_reallocate_tests, do_nothing,
				    "Deallocation and reallocation tests, %s%s "
				    "address, %s size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				run_suite(set_up_vm_variables, deallocate_null_map_test, do_nothing,
				    "mach_vm_deallocate() null map test, "
				    "%s%s address, %s size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
			}
		}
	}
	run_suite(do_nothing, deallocate_edge_case_tests, do_nothing, "Edge case deallocation tests");
	run_suite(do_nothing, deallocate_suicide_test, do_nothing, "Whole address space deallocation test");
}

void
run_read_test_suites()
{
	UnitTests read_main_tests = {
		{"Read address is nonzero iff size is nonzero", test_nonzero_address_iff_nonzero_size, 0},
		{"Read address has the correct boundary offset", test_read_address_offset, 0},
		{"Reallocate read pages", test_reallocate_pages, 0},
		{"Read and verify zero-filled memory", test_zero_filled, 0},
	};
	UnitTests read_pattern_tests = {
		{"Read address-filled pattern", test_read_address_filled, 0},
		{"Read checkerboard pattern", test_read_checkerboard, 0},
		{"Read reverse checkerboard pattern", test_read_reverse_checkerboard, 0},
	};
	UnitTests read_null_map_test = {
		{"Read from NULL VM map", test_read_null_map, 0},
	};
	UnitTests read_edge_case_tests = {
		{"Read zero size", test_read_zero_size, 0},
		{"Read invalid large size", test_read_invalid_large_size, 0},
		{"Read wrapped around memory ranges", test_read_wrapped_around_ranges, 0},
	};
	UnitTests read_inaccessible_tests = {
		{"Read partially deallocated memory", test_read_partially_deallocated_range, 0},
		{"Read partially read-protected memory", test_read_partially_unreadable_range, 0},
	};

	/* All allocations done with mach_vm_allocate(). */
	set_allocator(wrapper_mach_vm_allocate);

	/* Run the test suites with various VM sizes, and unspecified or
	 *  fixed (page-aligned or page-unaligned) addresses. */
	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
			for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
				/* An allocated address will be page-aligned. */
				if (flags_idx == ANYWHERE && alignments_idx == UNALIGNED) {
					continue;
				}
				run_suite(set_up_vm_variables_allocate_read_deallocate, read_main_tests, deallocate,
				    "mach_vm_read() "
				    "main tests, %s%s address, %s size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				run_suite(set_up_vm_variables_and_allocate_extra_page, read_pattern_tests, deallocate,
				    "mach_vm_read() pattern tests, %s%s address, %s "
				    "size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				run_suite(set_up_vm_variables_and_allocate_extra_page, read_null_map_test, deallocate_extra_page,
				    "mach_vm_read() null map test, "
				    "%s%s address, %s size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				/* A zero size range is always accessible. */
				if (sizes_idx != ZERO_BYTES) {
					run_suite(set_up_vm_variables_and_allocate_extra_page, read_inaccessible_tests, deallocate_extra_page,
					    "mach_vm_read() inaccessibility tests, %s%s "
					    "address, %s size: 0x%jx (%ju)",
					    address_flags[flags_idx].description,
					    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
					    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
					    (uintmax_t)vm_sizes[sizes_idx].size);
				}
			}
		}
	}
	run_suite(do_nothing, read_edge_case_tests, do_nothing, "mach_vm_read() fixed size tests");
}

void
run_write_test_suites()
{
	UnitTests write_main_tests = {
		{"Write and verify zero-filled memory", test_zero_filled_write, 0},
	};
	UnitTests write_pattern_tests = {
		{"Write address-filled pattern", test_address_filled_write, 0},
		{"Write checkerboard pattern", test_checkerboard_write, 0},
		{"Write reverse checkerboard pattern", test_reverse_checkerboard_write, 0},
	};
	UnitTests write_edge_case_tests = {
		{"Write into NULL VM map", test_write_null_map, 0}, {"Write zero size", test_write_zero_size, 0},
	};
	UnitTests write_inaccessible_tests = {
		{"Write partially deallocated buffer", test_write_partially_deallocated_buffer, 0},
		{"Write partially read-protected buffer", test_write_partially_unreadable_buffer, 0},
		{"Write on partially deallocated range", test_write_on_partially_deallocated_range, 0},
		{"Write on partially write-protected range", test_write_on_partially_unwritable_range, 0},
	};

	/* All allocations done with mach_vm_allocate(). */
	set_allocator(wrapper_mach_vm_allocate);

	/* Run the test suites with various destination sizes and
	 *  unspecified or fixed (page-aligned or page-unaligned)
	 *  addresses, and various buffer sizes and boundary offsets. */
	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
			for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
				for (buffer_sizes_idx = 0; buffer_sizes_idx < numofsizes; buffer_sizes_idx++) {
					for (offsets_idx = 0; offsets_idx < numofoffsets; offsets_idx++) {
						/* An allocated address will be page-aligned. */
						if ((flags_idx == ANYWHERE && alignments_idx == UNALIGNED)) {
							continue;
						}
						run_suite(set_up_vm_and_buffer_variables_allocate_for_writing, write_edge_case_tests,
						    deallocate_vm_and_buffer,
						    "mach_vm_write() edge case tests, %s%s address, %s "
						    "size: 0x%jx (%ju), buffer %s size: 0x%jx (%ju), "
						    "buffer boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
						/* A zero size buffer is always accessible. */
						if (buffer_sizes_idx != ZERO_BYTES) {
							run_suite(set_up_vm_and_buffer_variables_allocate_for_writing, write_inaccessible_tests,
							    deallocate_vm_and_buffer,
							    "mach_vm_write() inaccessibility tests, "
							    "%s%s address, %s size: 0x%jx (%ju), buffer "
							    "%s size: 0x%jx (%ju), buffer boundary "
							    "offset: %d",
							    address_flags[flags_idx].description,
							    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
							    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
							    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
							    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
							    buffer_offsets[offsets_idx].offset);
						}
						/* The buffer cannot be larger than the destination. */
						if (vm_sizes[sizes_idx].size < vm_sizes[buffer_sizes_idx].size) {
							continue;
						}
						run_suite(set_up_vm_and_buffer_variables_allocate_write, write_main_tests, deallocate_vm_and_buffer,
						    "mach_vm_write() main tests, %s%s address, %s "
						    "size: 0x%jx (%ju), buffer %s size: 0x%jx (%ju), "
						    "buffer boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
						run_suite(set_up_vm_and_buffer_variables_allocate_for_writing, write_pattern_tests,
						    deallocate_vm_and_buffer,
						    "mach_vm_write() pattern tests, %s%s address, %s "
						    "size: 0x%jx (%ju), buffer %s size: 0x%jx (%ju), "
						    "buffer boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
					}
				}
			}
		}
	}
}

void
run_protect_test_suites()
{
	UnitTests readprotection_main_tests = {
		{"Read-protect, read-allow and verify zero-filled memory", test_zero_filled_readprotect, 0},
		{"Verify that region is read-protected iff size is "
		 "nonzero",
		 test_verify_readprotection, 0},
	};
	UnitTests access_readprotected_memory_tests = {
		{"Read start of read-protected range", test_access_readprotected_range_start, SIGBUS},
		{"Read middle of read-protected range", test_access_readprotected_range_middle, SIGBUS},
		{"Read end of read-protected range", test_access_readprotected_range_end, SIGBUS},
	};
	UnitTests writeprotection_main_tests = {
		{"Write-protect and verify zero-filled memory", test_zero_filled_extended, 0},
		{"Verify that region is write-protected iff size is nonzero",
		 test_verify_writeprotection, 0},
	};
	UnitTests write_writeprotected_memory_tests = {
		{"Write at start of write-protected range", test_write_writeprotected_range_start, SIGBUS},
		{"Write in middle of write-protected range", test_write_writeprotected_range_middle, SIGBUS},
		{"Write at end of write-protected range", test_write_writeprotected_range_end, SIGBUS},
	};
	UnitTests protect_edge_case_tests = {
		{"Read-protect zero size ranges", test_readprotect_zero_size, 0},
		{"Write-protect zero size ranges", test_writeprotect_zero_size, 0},
		{"Read-protect wrapped around memory ranges", test_readprotect_wrapped_around_ranges, 0},
		{"Write-protect wrapped around memory ranges", test_writeprotect_wrapped_around_ranges, 0},
	};

	/* All allocations done with mach_vm_allocate(). */
	set_allocator(wrapper_mach_vm_allocate);

	/* Run the test suites with various VM sizes, and unspecified or
	 *  fixed (page-aligned or page-unaligned), addresses. */
	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
			for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
				/* An allocated address will be page-aligned. */
				if (flags_idx == ANYWHERE && alignments_idx == UNALIGNED) {
					continue;
				}
				run_suite(set_up_vm_variables_allocate_readprotect, readprotection_main_tests, deallocate_extra_page,
				    "Main read-protection tests, %s%s address, %s "
				    "size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				run_suite(set_up_vm_variables_allocate_writeprotect, writeprotection_main_tests, deallocate_extra_page,
				    "Main write-protection tests, %s%s address, %s "
				    "size: 0x%jx (%ju)",
				    address_flags[flags_idx].description,
				    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
				    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
				    (uintmax_t)vm_sizes[sizes_idx].size);
				/* Nothing gets protected if size is zero. */
				if (sizes_idx != ZERO_BYTES) {
					/* Accessing read-protected memory should cause a bus
					 *  error. */
					run_suite(set_up_vm_variables_allocate_readprotect, access_readprotected_memory_tests, deallocate_extra_page,
					    "Read-protected memory access tests, %s%s "
					    "address, %s size: 0x%jx (%ju)",
					    address_flags[flags_idx].description,
					    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
					    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
					    (uintmax_t)vm_sizes[sizes_idx].size);
					/* Writing on write-protected memory should cause a bus
					 *  error. */
					run_suite(set_up_vm_variables_allocate_writeprotect, write_writeprotected_memory_tests, deallocate_extra_page,
					    "Write-protected memory writing tests, %s%s "
					    "address, %s size: 0x%jx (%ju)",
					    address_flags[flags_idx].description,
					    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
					    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
					    (uintmax_t)vm_sizes[sizes_idx].size);
				}
			}
		}
	}
	run_suite(do_nothing, protect_edge_case_tests, do_nothing, "Edge case protection tests");
}

void
run_copy_test_suites()
{
	/* Copy tests */
	UnitTests copy_main_tests = {
		{"Copy and verify zero-filled memory", test_zero_filled_copy_dest, 0},
	};
	UnitTests copy_pattern_tests = {
		{"Copy address-filled pattern", test_copy_address_filled, 0},
		{"Copy checkerboard pattern", test_copy_checkerboard, 0},
		{"Copy reverse checkerboard pattern", test_copy_reverse_checkerboard, 0},
	};
	UnitTests copy_edge_case_tests = {
		{"Copy with NULL VM map", test_copy_null_map, 0},
		{"Copy zero size", test_copy_zero_size, 0},
		{"Copy invalid large size", test_copy_invalid_large_size, 0},
		{"Read wrapped around memory ranges", test_copy_wrapped_around_ranges, 0},
	};
	UnitTests copy_inaccessible_tests = {
		{"Copy source partially deallocated region", test_copy_source_partially_deallocated_region, 0},
		/* XXX */
		{"Copy destination partially deallocated region", test_copy_dest_partially_deallocated_region, 0},
		{"Copy source partially read-protected region", test_copy_source_partially_unreadable_region, 0},
		/* XXX */
		{"Copy destination partially write-protected region", test_copy_dest_partially_unwriteable_region, 0},
		{"Copy source on partially deallocated range", test_copy_source_on_partially_deallocated_range, 0},
		{"Copy destination on partially deallocated range", test_copy_dest_on_partially_deallocated_range, 0},
		{"Copy source on partially read-protected range", test_copy_source_on_partially_unreadable_range, 0},
		{"Copy destination on partially write-protected range", test_copy_dest_on_partially_unwritable_range, 0},
	};

	UnitTests copy_shared_mode_tests = {
		{"Copy using freshly allocated source", test_vmcopy_fresh_source, 0},
		{"Copy using shared source", test_vmcopy_shared_source, 0},
		{"Copy using a \'copied from\' source", test_vmcopy_copied_from_source, 0},
		{"Copy using a \'copied to\' source", test_vmcopy_copied_to_source, 0},
		{"Copy using a true shared source", test_vmcopy_trueshared_source, 0},
		{"Copy using a private aliased source", test_vmcopy_private_aliased_source, 0},
	};

	/* All allocations done with mach_vm_allocate(). */
	set_allocator(wrapper_mach_vm_allocate);

	/* All the tests are done with page size regions. */
	set_vm_size(vm_page_size);

	/* Run the test suites with various shared modes for source */
	for (vmcopy_action_idx = 0; vmcopy_action_idx < numofvmcopyactions; vmcopy_action_idx++) {
		run_suite(set_up_copy_shared_mode_variables, copy_shared_mode_tests, do_nothing, "Copy shared mode tests, %s",
		    vmcopy_actions[vmcopy_action_idx].description);
	}

	for (sizes_idx = 0; sizes_idx < numofsizes; sizes_idx++) {
		for (flags_idx = 0; flags_idx < numofflags; flags_idx++) {
			for (alignments_idx = 0; alignments_idx < numofalignments; alignments_idx++) {
				for (buffer_sizes_idx = 0; buffer_sizes_idx < numofsizes; buffer_sizes_idx++) {
					for (offsets_idx = 0; offsets_idx < numofoffsets; offsets_idx++) {
						/* An allocated address will be page-aligned. */
						if ((flags_idx == ANYWHERE && alignments_idx == UNALIGNED)) {
							continue;
						}
						run_suite(set_up_vm_and_buffer_variables_allocate_for_copying, copy_edge_case_tests,
						    deallocate_vm_and_buffer,
						    "mach_vm_copy() edge case tests, %s%s address, %s "
						    "size: 0x%jx (%ju), buffer %s size: 0x%jx (%ju), "
						    "buffer boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
						/* The buffer cannot be larger than the destination. */
						if (vm_sizes[sizes_idx].size < vm_sizes[buffer_sizes_idx].size) {
							continue;
						}

						/* A zero size buffer is always accessible. */
						if (buffer_sizes_idx != ZERO_BYTES) {
							run_suite(set_up_vm_and_buffer_variables_allocate_for_copying, copy_inaccessible_tests,
							    deallocate_vm_and_buffer,
							    "mach_vm_copy() inaccessibility tests, "
							    "%s%s address, %s size: 0x%jx (%ju), buffer "
							    "%s size: 0x%jx (%ju), buffer boundary "
							    "offset: %d",
							    address_flags[flags_idx].description,
							    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
							    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
							    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
							    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
							    buffer_offsets[offsets_idx].offset);
						}
						run_suite(set_up_source_and_dest_variables_allocate_copy, copy_main_tests, deallocate_vm_and_buffer,
						    "mach_vm_copy() main tests, %s%s address, %s "
						    "size: 0x%jx (%ju), destination %s size: 0x%jx (%ju), "
						    "destination boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
						run_suite(set_up_source_and_dest_variables_allocate_copy, copy_pattern_tests, deallocate_vm_and_buffer,
						    "mach_vm_copy() pattern tests, %s%s address, %s "
						    "size: 0x%jx (%ju) destination %s size: 0x%jx (%ju), "
						    "destination boundary offset: %d",
						    address_flags[flags_idx].description,
						    (flags_idx == ANYWHERE) ? "" : address_alignments[alignments_idx].description,
						    vm_sizes[sizes_idx].description, (uintmax_t)vm_sizes[sizes_idx].size,
						    (uintmax_t)vm_sizes[sizes_idx].size, vm_sizes[buffer_sizes_idx].description,
						    (uintmax_t)vm_sizes[buffer_sizes_idx].size, (uintmax_t)vm_sizes[buffer_sizes_idx].size,
						    buffer_offsets[offsets_idx].offset);
					}
				}
			}
		}
	}
}

static int
set_disable_vm_sanitize_telemetry_via_sysctl(uint32_t val)
{
	int ret = sysctlbyname("debug.disable_vm_sanitize_telemetry", NULL, NULL, &val, sizeof(uint32_t));
	if (ret != 0) {
		T_LOG("telemetry sysctl failed with errno %d.", errno);
	}
	return ret;
}

static int
disable_vm_sanitize_telemetry(void)
{
	return set_disable_vm_sanitize_telemetry_via_sysctl(1);
}

static int
reenable_vm_sanitize_telemetry(void)
{
	return set_disable_vm_sanitize_telemetry_via_sysctl(0);
}

void
perform_test_with_options(test_option_t options)
{
	disable_vm_sanitize_telemetry();

	process_options(options);

	if (flag_run_allocate_test) {
		run_allocate_test_suites();
	}

	if (flag_run_deallocate_test) {
		run_deallocate_test_suites();
	}

	if (flag_run_read_test) {
		run_read_test_suites();
	}

	if (flag_run_write_test) {
		run_write_test_suites();
	}

	if (flag_run_protect_test) {
		run_protect_test_suites();
	}

	if (flag_run_copy_test) {
		run_copy_test_suites();
	}

	log_aggregated_results();
	reenable_vm_sanitize_telemetry();
}

T_DECL(vm_test_allocate, "Allocate VM unit test")
{
	test_options.to_flags = VM_TEST_ALLOCATE;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}

T_DECL(vm_test_deallocate, "Deallocate VM unit test",
    T_META_ENABLED(!TARGET_OS_BRIDGE),  /* disabled on bridgeOS due to failures, rdar://137493917 */
    T_META_IGNORECRASHES(".*vm_allocation.*"))
{
	test_options.to_flags = VM_TEST_DEALLOCATE;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}

T_DECL(vm_test_read, "Read VM unit test")
{
	test_options.to_flags = VM_TEST_READ;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}

T_DECL(vm_test_write, "Write VM unit test")
{
	test_options.to_flags = VM_TEST_WRITE;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}

T_DECL(vm_test_protect, "Protect VM unit test",
    T_META_IGNORECRASHES(".*vm_allocation.*"))
{
	test_options.to_flags = VM_TEST_PROTECT;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}

T_DECL(vm_test_copy, "Copy VM unit test")
{
	test_options.to_flags = VM_TEST_COPY;
	test_options.to_vmsize = 0;
	test_options.to_quietness = ERROR_ONLY_QUIETNESS;

	perform_test_with_options(test_options);
}