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
/*
 * Copyright (c) 2024 Apple Inc. All rights reserved.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. The rights granted to you under the License
 * may not be used to create, or enable the creation or redistribution of,
 * unlawful or unlicensed copies of an Apple operating system, or to
 * circumvent, violate, or enable the circumvention or violation of, any
 * terms of an Apple operating system software license agreement.
 *
 * Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
 */

#include <mach/memory_entry.h>
#include <mach/memory_entry_server.h>
#include <mach/vm_map_server.h>
#include <mach/mach_vm_server.h>
#include <vm/vm_purgeable_internal.h>
#include <mach/mach_host_server.h>
#include <IOKit/IOBSD.h>
#include <vm/vm_fault_internal.h>
#include <vm/vm_memory_entry_xnu.h>
#include <vm/vm_map_internal.h>
#include <vm/memory_object_internal.h>
#include <vm/vm_protos_internal.h>
#include <vm/vm_object_internal.h>
#include <vm/vm_iokit.h>
#include <vm/vm_map_lock_internal.h>

static void mach_memory_entry_no_senders(ipc_port_t, mach_port_mscount_t);

IPC_KOBJECT_DEFINE(IKOT_NAMED_ENTRY,
    .iko_op_movable_send = true,
    .iko_op_stable     = true,
    .iko_op_no_senders = mach_memory_entry_no_senders);

/*
 * mach_make_memory_entry_64
 *
 * Think of it as a two-stage vm_remap() operation.  First
 * you get a handle.  Second, you get map that handle in
 * somewhere else. Rather than doing it all at once (and
 * without needing access to the other whole map).
 */
kern_return_t
mach_make_memory_entry_64(
	vm_map_t                target_map,
	memory_object_size_ut  *size_u,
	memory_object_offset_ut offset_u,
	vm_prot_ut              permission_u,
	ipc_port_t              *object_handle,
	ipc_port_t              parent_handle)
{
	return mach_make_memory_entry_internal(target_map,
	           size_u,
	           offset_u,
	           permission_u,
	           VM_NAMED_ENTRY_KERNEL_FLAGS_NONE,
	           object_handle,
	           parent_handle);
}

static inline void
vm_memory_entry_decode_perm(
	vm_prot_t                       permission,
	unsigned int                   *access,
	vm_prot_t                      *protections,
	bool                           *mask_protections,
	bool                           *use_data_addr,
	bool                           *use_4K_compat)
{
	*protections = permission & VM_PROT_ALL;
	*mask_protections = permission & VM_PROT_IS_MASK;
	*access = GET_MAP_MEM(permission);
	*use_data_addr = ((permission & MAP_MEM_USE_DATA_ADDR) != 0);
	*use_4K_compat = ((permission & MAP_MEM_4K_DATA_ADDR) != 0);
}

static inline vm_map_offset_t
vm_memory_entry_get_offset_in_page(
	vm_map_offset_t                 offset,
	vm_map_offset_t                 map_start,
	bool                            use_data_addr,
	bool                            use_4K_compat)
{
	vm_map_offset_t         offset_in_page;

	if (use_data_addr || use_4K_compat) {
		offset_in_page = offset - map_start;
		if (use_4K_compat) {
			offset_in_page &= ~((signed)(0xFFF));
		}
	} else {
		offset_in_page = 0;
	}

	return offset_in_page;
}

static inline kern_return_t
mach_make_memory_entry_cleanup(
	kern_return_t           kr,
	vm_map_t                target_map __unused,
	memory_object_size_ut  *size_u,
	vm_map_offset_ut        offset_u __unused,
	vm_prot_t               permission __unused,
	vm_named_entry_t        user_entry __unused,
	ipc_port_t             *object_handle)
{
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> entry "
	    "%p kr 0x%x\n", target_map, VM_SANITIZE_UNSAFE_UNWRAP(offset_u),
	    VM_SANITIZE_UNSAFE_UNWRAP(*size_u), permission, user_entry,
	    vm_sanitize_get_kr(kr));
	/*
	 * Set safe size and object_handle value on failed return
	 */
	*size_u = vm_sanitize_wrap_size(0);
	*object_handle = IPC_PORT_NULL;
	return vm_sanitize_get_kr(kr);
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_make_memory_entry_mem_only_sanitize(
	vm_map_t                target_map,
	memory_object_size_ut   size_u,
	vm_map_offset_ut        offset_u,
	vm_map_offset_t        *map_start,
	vm_map_offset_t        *map_end,
	vm_map_size_t          *map_size)
{
	/*
	 * This code path doesn't use offset and size. They don't need to be
	 * validated. However inorder to maintain backward compatibility some
	 * checks on offset and size have been left.
	 */
	return vm_sanitize_addr_size(offset_u, size_u,
	           VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	           target_map, VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH,
	           map_start, map_end, map_size);
}

static kern_return_t
mach_make_memory_entry_mem_only(
	vm_map_t                        target_map,
	memory_object_size_ut          *size_u,
	memory_object_offset_ut         offset_u,
	vm_prot_t                       permission,
	ipc_port_t                     *object_handle,
	vm_named_entry_t                parent_entry)
{
	boolean_t               parent_is_object;
	vm_object_t             object;
	unsigned int            access;
	vm_prot_t               protections;
	bool                    mask_protections;
	uint8_t                 wimg_mode;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	vm_named_entry_t        user_entry __unused = NULL;
	kern_return_t           kr;
	vm_map_size_t           map_size;
	vm_map_offset_t         map_start, map_end;

	/*
	 * Sanitize addr and size. Permimssions have been sanitized prior to
	 * dispatch
	 */
	kr = mach_make_memory_entry_mem_only_sanitize(target_map,
	    *size_u,
	    offset_u,
	    &map_start,
	    &map_end,
	    &map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	if (use_data_addr || use_4K_compat || parent_entry == NULL) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	parent_is_object = parent_entry->is_object;
	if (!parent_is_object) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	if ((access != parent_entry->access) &&
	    !(parent_entry->protection & VM_PROT_WRITE)) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_RIGHT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	object = vm_named_entry_to_vm_object(parent_entry);
	if (parent_is_object && object != VM_OBJECT_NULL) {
		wimg_mode = object->wimg_bits;
	} else {
		wimg_mode = VM_WIMG_USE_DEFAULT;
	}
	vm_prot_to_wimg(access, &wimg_mode);
	if (parent_is_object && object &&
	    (access != MAP_MEM_NOOP) &&
	    (!(object->nophyscache))) {
		if (object->wimg_bits != wimg_mode) {
			vm_object_lock(object);
#if HAS_MTE
			if (vm_object_is_mte_mappable(object)) {
				vm_object_unlock(object);
				return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT,
				           target_map, size_u, offset_u, permission, user_entry,
				           object_handle);
			}
#endif /* HAS_MTE */
			vm_object_change_wimg_mode(object, wimg_mode);
			vm_object_unlock(object);
		}
	}
	if (access != MAP_MEM_NOOP) {
		parent_entry->access = access;
	}
	if (object_handle) {
		*object_handle = IP_NULL;
	}
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> entry "
	    "%p kr 0x%x\n", target_map, VM_SANITIZE_UNSAFE_UNWRAP(offset_u),
	    VM_SANITIZE_UNSAFE_UNWRAP(*size_u), permission, user_entry, KERN_SUCCESS);
	/*
	 * TODO: Size isn't being set in this path
	 */
	return KERN_SUCCESS;
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_make_memory_entry_generic_sanitize(
	vm_map_t                target_map,
	memory_object_size_ut   size_u,
	vm_map_offset_ut        offset_u,
	vm_map_offset_t        *map_start,
	vm_map_offset_t        *map_end,
	vm_map_size_t          *map_size,
	vm_map_offset_t        *offset)
{
	kern_return_t           kr;

	/*
	 * Validate start and end
	 */
	kr = vm_sanitize_addr_size(offset_u, size_u,
	    VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	    target_map, VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH,
	    map_start, map_end, map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}
	/*
	 * Validate offset
	 */
	kr = vm_sanitize_offset(offset_u, VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	    *map_start, *map_end, offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	return KERN_SUCCESS;
}

static kern_return_t
mach_make_memory_entry_named_create(
	vm_map_t                        target_map,
	memory_object_size_ut          *size_u,
	vm_map_offset_ut                offset_u,
	vm_prot_t                       permission,
	vm_named_entry_kernel_flags_t   vmne_kflags,
	ipc_port_t                     *object_handle)
{
	vm_object_t             object;
	unsigned int            access;
	vm_prot_t               protections;
	bool                    mask_protections;
	uint8_t                 wimg_mode;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	int                     ledger_flags = 0;
	task_t                  owner;
	bool                    fully_owned = false;
	vm_named_entry_t        user_entry = NULL;
	kern_return_t           kr;
	vm_map_size_t           map_size;
	vm_map_offset_t         map_start, map_end, offset;

	if (VM_SANITIZE_UNSAFE_IS_ZERO(*size_u)) {
		return mach_make_memory_entry_cleanup(KERN_SUCCESS, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	/*
	 * Sanitize addr and size. Permimssions have been sanitized prior to
	 * dispatch
	 */
	kr = mach_make_memory_entry_generic_sanitize(target_map,
	    *size_u,
	    offset_u,
	    &map_start,
	    &map_end,
	    &map_size,
	    &offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	assert(map_size != 0);

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	if (use_data_addr || use_4K_compat) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	/*
	 * Force the creation of the VM object now.
	 */
#if __LP64__
	if (map_size > ANON_MAX_SIZE) {
		return mach_make_memory_entry_cleanup(KERN_FAILURE, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}
#endif /* __LP64__ */

	object = vm_object_allocate(map_size, vm_map_maybe_serial_id(target_map));
	assert(object != VM_OBJECT_NULL);
	vm_object_lock(object);

	/*
	 * XXX
	 * We use this path when we want to make sure that
	 * nobody messes with the object (coalesce, for
	 * example) before we map it.
	 * We might want to use these objects for transposition via
	 * vm_object_transpose() too, so we don't want any copy or
	 * shadow objects either...
	 */
	object->copy_strategy = MEMORY_OBJECT_COPY_NONE;
	VM_OBJECT_SET_TRUE_SHARE(object, TRUE);

	owner = current_task();
	if ((permission & MAP_MEM_PURGABLE) ||
	    vmne_kflags.vmnekf_ledger_tag) {
		assert(object->vo_owner == NULL);
		assert(object->resident_page_count == 0);
		assert(object->wired_page_count == 0);
		assert(owner != TASK_NULL);
		if (vmne_kflags.vmnekf_ledger_no_footprint) {
			ledger_flags |= VM_LEDGER_FLAG_NO_FOOTPRINT;
			object->vo_no_footprint = TRUE;
		}
		if (permission & MAP_MEM_PURGABLE) {
			if (!(permission & VM_PROT_WRITE)) {
				/* if we can't write, we can't purge */
				vm_object_unlock(object);
				vm_object_deallocate(object);
				return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT,
				           target_map, size_u, offset_u, permission, user_entry,
				           object_handle);
			}
			VM_OBJECT_SET_PURGABLE(object, VM_PURGABLE_NONVOLATILE);
			if (permission & MAP_MEM_PURGABLE_KERNEL_ONLY) {
				VM_OBJECT_SET_PURGEABLE_ONLY_BY_KERNEL(object, TRUE);
			}
#if __arm64__
			if (owner->task_legacy_footprint) {
				/*
				 * For ios11, we failed to account for
				 * this memory.  Keep doing that for
				 * legacy apps (built before ios12),
				 * for backwards compatibility's sake...
				 */
				owner = kernel_task;
			}
#endif /* __arm64__ */
			vm_purgeable_nonvolatile_enqueue(object, owner);
			/* all memory in this named entry is "owned" */
			fully_owned = true;
		}
	}

	if (vmne_kflags.vmnekf_ledger_tag) {
		/*
		 * Bill this object to the current task's
		 * ledgers for the given tag.
		 */
		if (vmne_kflags.vmnekf_ledger_no_footprint) {
			ledger_flags |= VM_LEDGER_FLAG_NO_FOOTPRINT;
		}
		kr = vm_object_ownership_change(
			object,
			vmne_kflags.vmnekf_ledger_tag,
			owner,         /* new owner */
			ledger_flags,
			FALSE);         /* task_objq locked? */
		if (kr != KERN_SUCCESS) {
			vm_object_unlock(object);
			vm_object_deallocate(object);
			return mach_make_memory_entry_cleanup(kr, target_map,
			           size_u, offset_u, permission, user_entry, object_handle);
		}
		/* all memory in this named entry is "owned" */
		fully_owned = true;
	}

#if CONFIG_SECLUDED_MEMORY
	if (secluded_for_iokit && /* global boot-arg */
	    ((permission & MAP_MEM_GRAB_SECLUDED))) {
		object->can_grab_secluded = TRUE;
		assert(!object->eligible_for_secluded);
	}
#endif /* CONFIG_SECLUDED_MEMORY */

	/*
	 * The VM object is brand new and nobody else knows about it,
	 * so we don't need to lock it.
	 */

	wimg_mode = object->wimg_bits;
	vm_prot_to_wimg(access, &wimg_mode);
	if (access != MAP_MEM_NOOP) {
		object->wimg_bits = wimg_mode;
	}

	vm_object_unlock(object);

	/* the object has no pages, so no WIMG bits to update here */

	user_entry = mach_memory_entry_allocate(object_handle);
	vm_named_entry_associate_vm_object(
		user_entry,
		object,
		0,
		map_size,
		(protections & VM_PROT_ALL));
	user_entry->internal = TRUE;
	user_entry->is_sub_map = FALSE;
	user_entry->offset = 0;
	user_entry->data_offset = 0;
	user_entry->protection = protections;
	user_entry->access = access;
	user_entry->size = map_size;
	user_entry->is_fully_owned = fully_owned;

	/* user_object pager and internal fields are not used */
	/* when the object field is filled in.		      */

	*size_u = vm_sanitize_wrap_size(user_entry->size - user_entry->data_offset);
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> entry "
	    "%p kr 0x%x\n", target_map, offset, VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
	    permission, user_entry, KERN_SUCCESS);
	return KERN_SUCCESS;
}

static kern_return_t
mach_make_memory_entry_copy(
	vm_map_t                      target_map,
	memory_object_size_ut         *size_u,
	vm_map_offset_ut              offset_u,
	vm_prot_t                     permission,
	__unused vm_named_entry_kernel_flags_t vmne_kflags,
	ipc_port_t                    *object_handle)
{
	unsigned int            access;
	vm_prot_t               protections;
	bool                    mask_protections;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	vm_named_entry_t        user_entry = NULL;
	vm_map_copy_t           copy;
	/*
	 * Stash the offset in the page for use by vm_map_enter_mem_object()
	 * in the VM_FLAGS_RETURN_DATA_ADDR/MAP_MEM_USE_DATA_ADDR case.
	 */
	vm_object_offset_t      offset_in_page;
	kern_return_t           kr;
	vm_map_size_t           map_size;
	vm_map_offset_t         map_start, map_end, offset;

	if (VM_SANITIZE_UNSAFE_IS_ZERO(*size_u)) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	/*
	 * Sanitize addr and size. Permimssions have been sanitized prior to
	 * dispatch
	 */
	kr = mach_make_memory_entry_generic_sanitize(target_map,
	    *size_u,
	    offset_u,
	    &map_start,
	    &map_end,
	    &map_size,
	    &offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	assert(map_size != 0);

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	if (target_map == VM_MAP_NULL) {
		return mach_make_memory_entry_cleanup(KERN_INVALID_TASK, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	offset_in_page = vm_memory_entry_get_offset_in_page(offset, map_start,
	    use_data_addr, use_4K_compat);

	int copyin_flags = VM_MAP_COPYIN_ENTRY_LIST;
#if HAS_MTE
	copyin_flags |= VM_MAP_COPYIN_DEST_UNKNOWN;
	copyin_flags |= vmne_kflags.vmnekf_is_iokit ? VM_MAP_COPYIN_IOKIT : 0;
#endif
	kr = vm_map_copyin_internal(target_map,
	    map_start,
	    map_size,
	    copyin_flags,
	    &copy);
	if (kr != KERN_SUCCESS) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}
	assert(copy != VM_MAP_COPY_NULL);

	user_entry = mach_memory_entry_allocate(object_handle);
	user_entry->backing.copy = copy;
	user_entry->internal = FALSE;
	user_entry->is_sub_map = FALSE;
	user_entry->is_copy = TRUE;
	user_entry->offset = 0;
	user_entry->protection = protections;
	user_entry->size = map_size;
	user_entry->data_offset = offset_in_page;

	/* is all memory in this named entry "owned"? */
	vm_map_entry_t entry;
	user_entry->is_fully_owned = TRUE;
	for (entry = vm_map_copy_first_entry(copy);
	    entry != vm_map_copy_to_entry(copy);
	    entry = entry->vme_next) {
		if (entry->is_sub_map ||
		    VME_OBJECT(entry) == VM_OBJECT_NULL ||
		    VM_OBJECT_OWNER(VME_OBJECT(entry)) == TASK_NULL) {
			/* this memory is not "owned" */
			user_entry->is_fully_owned = FALSE;
			break;
		}
	}

	*size_u = vm_sanitize_wrap_size(user_entry->size - user_entry->data_offset);
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> "
	    "entry %p kr 0x%x\n", target_map, offset, VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
	    permission, user_entry, KERN_SUCCESS);
	return KERN_SUCCESS;
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_make_memory_entry_share_sanitize(
	vm_map_t                target_map,
	memory_object_size_ut   size_u,
	vm_map_offset_ut        offset_u,
	vm_map_offset_t        *map_start,
	vm_map_offset_t        *map_end,
	vm_map_size_t          *map_size,
	vm_map_offset_t        *offset)
{
	kern_return_t           kr;

#if CONFIG_KERNEL_TAGGING
	if (vm_kernel_map_is_kernel(target_map)) {
		/* Restrict canonicalization to tagged kernel addresses. */
		offset_u = vm_sanitize_canonicalize_ut_addr(target_map, offset_u);
	}
#endif /* CONFIG_KERNEL_TAGGING */

	/*
	 * Validate start and end
	 */
	kr = vm_sanitize_addr_size(offset_u, size_u,
	    VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	    target_map, VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH,
	    map_start, map_end, map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}
	/*
	 * Validate offset
	 */
	kr = vm_sanitize_offset(offset_u, VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	    *map_start, *map_end, offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	return KERN_SUCCESS;
}

__static_testable kern_return_t
mach_make_memory_entry_share(
	vm_map_t                      target_map,
	memory_object_size_ut        *size_u,
	vm_map_offset_ut              offset_u,
	vm_prot_t                     permission,
	__unused vm_named_entry_kernel_flags_t vmne_kflags,
	ipc_port_t                    *object_handle,
	ipc_port_t                    parent_handle,
	vm_named_entry_t              parent_entry)
{
	vm_object_t             object;
	unsigned int            access;
	vm_prot_t               protections;
	bool                    mask_protections;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	vm_named_entry_t        user_entry = NULL;
	vm_map_copy_t           copy;
	vm_prot_t               cur_prot, max_prot;
	vm_map_kernel_flags_t   vmk_flags;
	vm_map_entry_t          parent_copy_entry;
	/*
	 * Stash the offset in the page for use by vm_map_enter_mem_object()
	 * in the VM_FLAGS_RETURN_DATA_ADDR/MAP_MEM_USE_DATA_ADDR case.
	 */
	vm_object_offset_t      offset_in_page;
	uint8_t                 wimg_mode;
	kern_return_t           kr;
	vm_map_size_t           map_size;
	vm_map_offset_t         map_start, map_end, offset;

	vmlp_api_start(MACH_MAKE_MEMORY_ENTRY_SHARE);

	if (VM_SANITIZE_UNSAFE_IS_ZERO(*size_u)) {
		kr = mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		    size_u, offset_u, permission, user_entry, object_handle);
		vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
		return kr;
	}

	if (target_map == VM_MAP_NULL) {
		kr = mach_make_memory_entry_cleanup(KERN_INVALID_TASK, target_map,
		    size_u, offset_u, permission, user_entry, object_handle);
		vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
		return kr;
	}

	/*
	 * Sanitize addr and size. Permimssions have been sanitized prior to
	 * dispatch
	 */
	kr = mach_make_memory_entry_share_sanitize(target_map,
	    *size_u,
	    offset_u,
	    &map_start,
	    &map_end,
	    &map_size,
	    &offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		kr = mach_make_memory_entry_cleanup(kr, target_map,
		    size_u, offset_u, permission, user_entry, object_handle);
		vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
		return kr;
	}

	assert(map_size != 0);

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	vmk_flags = VM_MAP_KERNEL_FLAGS_NONE;
	vmk_flags.vmkf_range_id = KMEM_RANGE_ID_DATA_SHARED;

	parent_copy_entry = VM_MAP_ENTRY_NULL;
	if (!(permission & MAP_MEM_VM_SHARE)) {
		if (protections & VM_PROT_WRITE) {
			VM_MAP_LOCK_CTX_DECLARE(ctx);
			vm_map_t tmp_map, real_map;
			vm_object_t tmp_object;
			vm_map_entry_t tmp_entry;
			vm_object_offset_t obj_off;
			vm_prot_t prot;
			boolean_t wired;

			/* resolve any pending submap copy-on-write... */
			tmp_map = target_map;
			kr = vm_map_lookup_object_and_lock_entry(&tmp_map,
			    map_start,
			    protections | (mask_protections ? VM_PROT_IS_MASK : 0),
			    &tmp_object,
			    &tmp_entry,
			    &obj_off,
			    &prot,
			    &wired,
			    NULL,                               /* fault_info */
			    &real_map,
			    ctx,
			    NULL,
			    false);
			if (kr == KERN_SUCCESS) {
				vm_map_range_sh_unlock(ctx, NULL);
			}
		}

		/* ... and carry on */

		/* stop extracting if VM object changes */
		vmk_flags.vmkf_copy_single_object = TRUE;
		if ((permission & MAP_MEM_NAMED_REUSE) &&
		    parent_entry != NULL &&
		    parent_entry->is_object) {
			vm_map_copy_t parent_copy;
			parent_copy = parent_entry->backing.copy;
			/*
			 * Assert that the vm_map_copy is coming from the right
			 * zone and hasn't been forged
			 */
			vm_map_copy_require(parent_copy);
			assert(parent_copy->cpy_hdr.nentries == 1);
			parent_copy_entry = vm_map_copy_first_entry(parent_copy);
			assert(!parent_copy_entry->is_sub_map);
		}
	}

	offset_in_page = vm_memory_entry_get_offset_in_page(offset, map_start,
	    use_data_addr, use_4K_compat);

	if (mask_protections) {
		/*
		 * caller is asking for whichever proctections are
		 * available: no required protections.
		 */
		cur_prot = VM_PROT_NONE;
		max_prot = VM_PROT_NONE;
		vmk_flags.vmkf_remap_legacy_mode = true;
	} else {
		/*
		 * Caller wants a memory entry with "protections".
		 * Make sure we extract only memory that matches that.
		 */
		cur_prot = protections;
		max_prot = protections;
	}
	vmk_flags.vmkf_copy_same_map = FALSE;
#if HAS_MTE
	vmk_flags.vmkf_is_iokit = vmne_kflags.vmnekf_is_iokit;
	vmk_flags.vmkf_copy_dest = VM_COPY_DESTINATION_UNKNOWN;
#endif /* HAS_MTE */
	assert(map_size != 0);
	kr = vm_map_copy_extract(target_map,
	    map_start,
	    map_size,
	    FALSE,                              /* copy */
	    &copy,
	    &cur_prot,
	    &max_prot,
	    VM_INHERIT_SHARE,
	    vmk_flags);
	if (kr != KERN_SUCCESS) {
		kr = mach_make_memory_entry_cleanup(kr, target_map,
		    size_u, offset_u, permission, user_entry, object_handle);
		vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
		return kr;
	}
	assert(copy != VM_MAP_COPY_NULL);

	if (mask_protections) {
		/*
		 * We just want as much of "original_protections"
		 * as we can get out of the actual "cur_prot".
		 */
		protections &= cur_prot;
		if (protections == VM_PROT_NONE) {
			/* no access at all: fail */
			vm_map_copy_discard(copy);
			kr = mach_make_memory_entry_cleanup(KERN_PROTECTION_FAILURE,
			    target_map, size_u, offset_u, permission, user_entry,
			    object_handle);
			vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
			return kr;
		}
	} else {
		/*
		 * We want exactly "original_protections"
		 * out of "cur_prot".
		 */
		assert((cur_prot & protections) == protections);
		assert((max_prot & protections) == protections);
		/* XXX FBDP TODO: no longer needed? */
		if ((cur_prot & protections) != protections) {
			vm_map_copy_discard(copy);
			kr = mach_make_memory_entry_cleanup(KERN_PROTECTION_FAILURE,
			    target_map, size_u, offset_u, permission, user_entry,
			    object_handle);
			vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
			return kr;
		}
	}

	if (!(permission & MAP_MEM_VM_SHARE)) { /* vmkf_copy_single_object case */
		vm_map_entry_t copy_entry;

		/* limit size to what's actually covered by "copy" */
		assert(copy->cpy_hdr.nentries == 1);
		copy_entry = vm_map_copy_first_entry(copy);
		map_size = copy_entry->vme_end - copy_entry->vme_start;

		if ((permission & MAP_MEM_NAMED_REUSE) &&
		    parent_copy_entry != VM_MAP_ENTRY_NULL &&
		    VME_OBJECT(copy_entry) == VME_OBJECT(parent_copy_entry) &&
		    VME_OFFSET(copy_entry) == VME_OFFSET(parent_copy_entry) &&
		    parent_entry->offset == 0 &&
		    parent_entry->size == map_size &&
		    (parent_entry->data_offset == offset_in_page)) {
			/* we have a match: re-use "parent_entry" */

			/* release our new "copy" */
			vm_map_copy_discard(copy);
			/* get extra send right on handle */
			parent_handle = ipc_port_copy_send_any(parent_handle);

			*size_u = vm_sanitize_wrap_size(parent_entry->size -
			    parent_entry->data_offset);
			*object_handle = parent_handle;
			DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> "
			    "entry %p kr 0x%x\n", target_map, offset, VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
			    permission, user_entry, KERN_SUCCESS);
			vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, KERN_SUCCESS);
			return KERN_SUCCESS;
		}

		/* no match: we need to create a new entry */
		object = VME_OBJECT(copy_entry);

		if (object == VM_OBJECT_NULL) {
			/* object can be null when protection == max_protection == VM_PROT_NONE
			 * return a failure because the code that follows and other APIs that consume
			 * a named-entry expect to have non-null object */
			vm_map_copy_discard(copy);
			kr = mach_make_memory_entry_cleanup(KERN_PROTECTION_FAILURE,
			    target_map, size_u, offset_u, permission, user_entry,
			    object_handle);
			vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, kr);
			return kr;
		}

		vm_object_lock(object);
		wimg_mode = object->wimg_bits;
		if (!(object->nophyscache)) {
			vm_prot_to_wimg(access, &wimg_mode);
		}
		if (object->wimg_bits != wimg_mode) {
#if HAS_MTE
			if (vm_object_is_mte_mappable(object)) {
				vm_object_unlock(object);
				vm_map_copy_discard(copy);
				return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT,
				           target_map, size_u, offset_u, permission, user_entry,
				           object_handle);
			}
#endif /* HAS_MTE */
			vm_object_change_wimg_mode(object, wimg_mode);
		}
		vm_object_unlock(object);
	}

	user_entry = mach_memory_entry_allocate(object_handle);
	user_entry->backing.copy = copy;
	user_entry->is_sub_map = FALSE;
	user_entry->is_object = FALSE;
	user_entry->internal = FALSE;
	user_entry->protection = protections;
	user_entry->size = map_size;
	user_entry->data_offset = offset_in_page;

	if (permission & MAP_MEM_VM_SHARE) {
		vm_map_entry_t copy_entry;

		user_entry->is_copy = TRUE;
		user_entry->offset = 0;

		/* is all memory in this named entry "owned"? */
		user_entry->is_fully_owned = TRUE;
		for (copy_entry = vm_map_copy_first_entry(copy);
		    copy_entry != vm_map_copy_to_entry(copy);
		    copy_entry = copy_entry->vme_next) {
			if (copy_entry->is_sub_map) {
				/* submaps can't be owned */
				user_entry->is_fully_owned = FALSE;
				break;
			}
			if (VM_OBJECT_OWNER(VME_OBJECT(copy_entry)) == TASK_NULL) {
				object = VME_OBJECT(copy_entry);
				if (object && !object->internal) {
					/* external objects can be "owned",
					 * is_fully_owned remains TRUE as far as this entry is concerned */
					continue;
				}
				/* this memory is not "owned" */
				user_entry->is_fully_owned = FALSE;
				break;
			}
		}
	} else {
		assert3p(object, !=, VM_OBJECT_NULL); /* Sanity, this was set above */
		user_entry->is_object = TRUE;
		assert3p(object, ==, vm_named_entry_to_vm_object(user_entry)); /* Sanity, this was set above */
		user_entry->internal = object->internal;
		user_entry->offset = VME_OFFSET(vm_map_copy_first_entry(copy));
		user_entry->access = GET_MAP_MEM(permission);
		/* is all memory in this named entry "owned"? */
		user_entry->is_fully_owned = FALSE;
		if (VM_OBJECT_OWNER(object) != TASK_NULL) {
			/* object is owned */
			user_entry->is_fully_owned = TRUE;
		} else if (!object->internal) {
			/* external objects can become "owned" */
			user_entry->is_fully_owned = TRUE;
		}
	}

	*size_u = vm_sanitize_wrap_size(user_entry->size -
	    user_entry->data_offset);
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> entry "
	    "%p kr 0x%x\n", target_map, offset, VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
	    permission, user_entry, KERN_SUCCESS);

	vmlp_api_end(MACH_MAKE_MEMORY_ENTRY_SHARE, KERN_SUCCESS);
	return KERN_SUCCESS;
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_make_memory_entry_from_parent_entry_sanitize(
	vm_map_t                target_map,
	memory_object_size_ut   size_u,
	vm_map_offset_ut        offset_u,
	vm_prot_t               permission,
	vm_named_entry_t        parent_entry,
	vm_map_offset_t        *map_start,
	vm_map_offset_t        *map_end,
	vm_map_size_t          *map_size,
	vm_map_offset_t        *offset,
	vm_map_offset_t        *user_entry_offset)
{
	bool                    mask_protections;
	unsigned int            access;
	vm_prot_t               protections;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	vm_map_offset_t         start_mask = vm_map_page_mask(target_map);
	kern_return_t           kr;

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	if (use_data_addr || use_4K_compat) {
		/*
		 * Validate offset doesn't overflow when added to parent entry's offset
		 */
		if (vm_sanitize_add_overflow(offset_u, parent_entry->data_offset,
		    &offset_u)) {
			return KERN_INVALID_ARGUMENT;
		}
		start_mask = PAGE_MASK;
	}

	/*
	 * Currently the map_start is truncated using page mask from target_map
	 * when use_data_addr || use_4K_compat is false, while map_end uses
	 * PAGE_MASK. In order to maintain that behavior, we
	 * request for unaligned values and perform the truncing/rounding
	 * explicitly.
	 */
	kr = vm_sanitize_addr_size(offset_u, size_u,
	    VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY, PAGE_MASK,
	    VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH | VM_SANITIZE_FLAGS_GET_UNALIGNED_VALUES,
	    map_start, map_end, map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	*map_start =  vm_map_trunc_page_mask(*map_start, start_mask);
	*map_end = vm_map_round_page_mask(*map_end, PAGE_MASK);
	*map_size = *map_end - *map_start;

	/*
	 * Additional checks to make sure explicitly computed aligned start and end
	 * still make sense.
	 */
	if (__improbable(*map_end <= *map_start) || (*map_end > parent_entry->size)) {
		return KERN_INVALID_ARGUMENT;
	}

	/*
	 * Validate offset
	 */
	kr = vm_sanitize_offset(offset_u, VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	    *map_start, *map_end, offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	if (__improbable(os_add_overflow(parent_entry->offset, *map_start,
	    user_entry_offset))) {
		return KERN_INVALID_ARGUMENT;
	}

	return KERN_SUCCESS;
}

static kern_return_t
mach_make_memory_entry_from_parent_entry(
	vm_map_t                target_map,
	memory_object_size_ut  *size_u,
	vm_map_offset_ut        offset_u,
	vm_prot_t               permission,
	ipc_port_t             *object_handle,
	vm_named_entry_t        parent_entry)
{
	vm_object_t             object;
	unsigned int            access;
	vm_prot_t               protections;
	bool                    mask_protections;
	bool                    use_data_addr;
	bool                    use_4K_compat;
	vm_named_entry_t        user_entry = NULL;
	kern_return_t           kr;
	/*
	 * Stash the offset in the page for use by vm_map_enter_mem_object()
	 * in the VM_FLAGS_RETURN_DATA_ADDR/MAP_MEM_USE_DATA_ADDR case.
	 */
	vm_object_offset_t      offset_in_page;
	vm_map_offset_t         map_start, map_end;
	vm_map_size_t           map_size;
	vm_map_offset_t         user_entry_offset, offset;

	vm_memory_entry_decode_perm(permission, &access, &protections,
	    &mask_protections, &use_data_addr, &use_4K_compat);

	/*
	 * Sanitize addr and size. Permimssions have been sanitized prior to
	 * dispatch
	 */
	kr = mach_make_memory_entry_from_parent_entry_sanitize(target_map,
	    *size_u,
	    offset_u,
	    permission,
	    parent_entry,
	    &map_start,
	    &map_end,
	    &map_size,
	    &offset,
	    &user_entry_offset);
	if (__improbable(kr != KERN_SUCCESS)) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	if (use_data_addr || use_4K_compat) {
		/*
		 * submaps and pagers should only be accessible from within
		 * the kernel, which shouldn't use the data address flag, so can fail here.
		 */
		if (parent_entry->is_sub_map) {
			panic("Shouldn't be using data address with a parent entry that is a submap.");
		}
	}

	if (mask_protections) {
		/*
		 * The caller asked us to use the "protections" as
		 * a mask, so restrict "protections" to what this
		 * mapping actually allows.
		 */
		protections &= parent_entry->protection;
	}
	if ((protections & parent_entry->protection) != protections) {
		return mach_make_memory_entry_cleanup(KERN_PROTECTION_FAILURE, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	offset_in_page = vm_memory_entry_get_offset_in_page(offset, map_start,
	    use_data_addr, use_4K_compat);

	user_entry = mach_memory_entry_allocate(object_handle);
	user_entry->size = map_size;
	user_entry->offset = user_entry_offset;
	user_entry->data_offset = offset_in_page;
	user_entry->is_sub_map = parent_entry->is_sub_map;
	user_entry->is_copy = parent_entry->is_copy;
	user_entry->protection = protections;

	if (access != MAP_MEM_NOOP) {
		user_entry->access = access;
	}

	if (parent_entry->is_sub_map) {
		vm_map_t map = parent_entry->backing.map;
		vm_map_reference(map);
		user_entry->backing.map = map;
	} else {
		object = vm_named_entry_to_vm_object(parent_entry);
		assert(object != VM_OBJECT_NULL);
		if (object->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
			panic("mach_make_memory_entry can't handle SYMMETRIC object");
			/* This is because the resulting entry may be added to a map with vm_map_enter_mem_object()
			 * with needs_copy either true or false so the entry we create in the vm_map_copy_t object
			 * needs to be ready for either case. Allowing an entry with SYMMETRIC object and
			 * vm_map_enter() with needs_copy=false would create a CoW bypass
			 */
		}
		vm_named_entry_associate_vm_object(
			user_entry,
			object,
			user_entry->offset,
			user_entry->size,
			(user_entry->protection & VM_PROT_ALL));
		assert(user_entry->is_object);
		/* we now point to this object, hold on */
		vm_object_lock(object);
		vm_object_reference_locked(object);
#if VM_OBJECT_TRACKING_OP_TRUESHARE
		if (!object->true_share &&
		    vm_object_tracking_btlog) {
			btlog_record(vm_object_tracking_btlog, object,
			    VM_OBJECT_TRACKING_OP_TRUESHARE,
			    btref_get(__builtin_frame_address(0), 0));
		}
#endif /* VM_OBJECT_TRACKING_OP_TRUESHARE */

		VM_OBJECT_SET_TRUE_SHARE(object, TRUE);
		vm_object_unlock(object);
	}
	*size_u = vm_sanitize_wrap_size(user_entry->size -
	    user_entry->data_offset);
	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x -> entry "
	    "%p kr 0x%x\n", target_map, offset, VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
	    permission, user_entry, KERN_SUCCESS);
	return KERN_SUCCESS;
}

static inline kern_return_t
mach_make_memory_entry_sanitize_perm(
	vm_prot_ut              permission_u,
	vm_prot_t              *permission)
{
	return vm_sanitize_memory_entry_perm(permission_u,
	           VM_SANITIZE_CALLER_MACH_MAKE_MEMORY_ENTRY,
	           VM_SANITIZE_FLAGS_CHECK_USER_MEM_MAP_FLAGS,
	           VM_PROT_IS_MASK, permission);
}

kern_return_t
mach_make_memory_entry_internal(
	vm_map_t                        target_map,
	memory_object_size_ut          *size_u,
	memory_object_offset_ut         offset_u,
	vm_prot_ut                      permission_u,
	vm_named_entry_kernel_flags_t   vmne_kflags,
	ipc_port_t                     *object_handle,
	ipc_port_t                      parent_handle)
{
	vm_named_entry_t        user_entry __unused = NULL;
	vm_named_entry_t        parent_entry;
	kern_return_t           kr;
	vm_prot_t               permission;

	DEBUG4K_MEMENTRY("map %p offset 0x%llx size 0x%llx prot 0x%x\n",
	    target_map, VM_SANITIZE_UNSAFE_UNWRAP(offset_u), VM_SANITIZE_UNSAFE_UNWRAP(*size_u),
	    VM_SANITIZE_UNSAFE_UNWRAP(permission_u));

	/*
	 * Validate permissions as we need to dispatch the corresponding flavor
	 */
	kr = mach_make_memory_entry_sanitize_perm(permission_u, &permission);
	if (__improbable(kr != KERN_SUCCESS)) {
		return mach_make_memory_entry_cleanup(kr, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	if (permission & MAP_MEM_LEDGER_TAGGED) {
		vmne_kflags.vmnekf_ledger_tag = VM_LEDGER_TAG_DEFAULT;
	}

	parent_entry = mach_memory_entry_from_port(parent_handle);
	if (parent_entry && parent_entry->is_copy) {
		/* the parent entry we're trying to duplicate must be a sharable copy and not a CoW copy
		 * since we might want to eventually add it as is to a map */
		return mach_make_memory_entry_cleanup(KERN_INVALID_ARGUMENT, target_map,
		           size_u, offset_u, permission, user_entry, object_handle);
	}

	if (permission & MAP_MEM_ONLY) {
		return mach_make_memory_entry_mem_only(target_map, size_u, offset_u,
		           permission, object_handle, parent_entry);
	}

	if (permission & MAP_MEM_NAMED_CREATE) {
		return mach_make_memory_entry_named_create(target_map, size_u, offset_u,
		           permission, vmne_kflags, object_handle);
	}

	if (permission & MAP_MEM_VM_COPY) {
		return mach_make_memory_entry_copy(target_map, size_u, offset_u,
		           permission, vmne_kflags, object_handle);
	}

	if ((permission & MAP_MEM_VM_SHARE)
	    || parent_entry == NULL
	    || (permission & MAP_MEM_NAMED_REUSE)) {
		return mach_make_memory_entry_share(target_map, size_u, offset_u,
		           permission, vmne_kflags, object_handle, parent_handle,
		           parent_entry);
	}

	/*
	 * This function will compute map start, end and size by including the
	 * parent entry's offset. Therefore redo validation.
	 */
	return mach_make_memory_entry_from_parent_entry(target_map, size_u,
	           offset_u, permission, object_handle, parent_entry);
}

kern_return_t
_mach_make_memory_entry(
	vm_map_t                target_map,
	memory_object_size_ut  *size_u,
	memory_object_offset_ut offset_u,
	vm_prot_ut              permission_u,
	ipc_port_t              *object_handle,
	ipc_port_t              parent_entry)
{
	return mach_make_memory_entry_64(target_map, size_u,
	           offset_u, permission_u, object_handle, parent_entry);
}

kern_return_t
mach_make_memory_entry(
	vm_map_t                target_map,
	vm_size_ut             *size_u,
	vm_offset_ut            offset_u,
	vm_prot_ut              permission_u,
	ipc_port_t              *object_handle,
	ipc_port_t              parent_entry)
{
	kern_return_t           kr;

	kr = mach_make_memory_entry_64(target_map, size_u,
	    offset_u, permission_u, object_handle, parent_entry);
	return kr;
}

__private_extern__ vm_named_entry_t
mach_memory_entry_allocate(ipc_port_t *user_handle_p)
{
	vm_named_entry_t user_entry;

	user_entry = kalloc_type(struct vm_named_entry,
	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
	named_entry_lock_init(user_entry);

	*user_handle_p = ipc_kobject_alloc_port(user_entry, IKOT_NAMED_ENTRY,
	    IPC_KOBJECT_ALLOC_MAKE_SEND);

#if VM_NAMED_ENTRY_DEBUG
	/* backtrace at allocation time, for debugging only */
	user_entry->named_entry_bt = btref_get(__builtin_frame_address(0), 0);
#endif /* VM_NAMED_ENTRY_DEBUG */
	return user_entry;
}

static __attribute__((always_inline, warn_unused_result))
kern_return_t
mach_memory_object_memory_entry_64_sanitize(
	vm_object_size_ut       size_u,
	vm_prot_ut              permission_u,
	vm_object_size_t       *size,
	vm_prot_t              *permission)
{
	kern_return_t           kr;

	kr = vm_sanitize_object_size(size_u,
	    VM_SANITIZE_CALLER_MACH_MEMORY_OBJECT_MEMORY_ENTRY,
	    VM_SANITIZE_FLAGS_SIZE_ZERO_FAILS, size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}
	kr = vm_sanitize_memory_entry_perm(permission_u,
	    VM_SANITIZE_CALLER_MACH_MEMORY_OBJECT_MEMORY_ENTRY,
	    VM_SANITIZE_FLAGS_NONE, VM_PROT_NONE,
	    permission);
	if (__improbable(kr != KERN_SUCCESS)) {
		return kr;
	}

	return KERN_SUCCESS;
}

/*
 *	mach_memory_object_memory_entry_64
 *
 *	Create a named entry backed by the provided pager.
 *
 */
kern_return_t
mach_memory_object_memory_entry_64(
	host_t                  host,
	boolean_t               internal,
	vm_object_size_ut       size_u,
	vm_prot_ut              permission_u,
	memory_object_t         pager,
	ipc_port_t              *entry_handle)
{
	vm_named_entry_t        user_entry;
	ipc_port_t              user_handle;
	vm_object_t             object;
	vm_object_size_t        size;
	vm_prot_t               permission;
	kern_return_t           kr;

	if (host == HOST_NULL) {
		return KERN_INVALID_HOST;
	}

	/*
	 * Validate size and permission
	 */
	kr = mach_memory_object_memory_entry_64_sanitize(size_u,
	    permission_u,
	    &size,
	    &permission);
	if (__improbable(kr != KERN_SUCCESS)) {
		return vm_sanitize_get_kr(kr);
	}

	if (pager == MEMORY_OBJECT_NULL && internal) {
		object = vm_object_allocate(size, VM_MAP_SERIAL_NONE);
		if (object->copy_strategy == MEMORY_OBJECT_COPY_SYMMETRIC) {
			object->copy_strategy = MEMORY_OBJECT_COPY_DELAY;
		}
	} else {
		object = memory_object_to_vm_object(pager);
		if (object != VM_OBJECT_NULL) {
			vm_object_reference(object);
		}
	}
	if (object == VM_OBJECT_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	user_entry = mach_memory_entry_allocate(&user_handle);
	user_entry->size = size;
	user_entry->offset = 0;
	user_entry->protection = permission & VM_PROT_ALL;
	user_entry->access = GET_MAP_MEM(permission);
	user_entry->is_sub_map = FALSE;

	vm_named_entry_associate_vm_object(user_entry, object, 0, size,
	    (user_entry->protection & VM_PROT_ALL));
	user_entry->internal = object->internal;
	assert(object->internal == internal);
	if (VM_OBJECT_OWNER(object) != TASK_NULL) {
		/* all memory in this entry is "owned" */
		user_entry->is_fully_owned = TRUE;
	} else if (object && !object->internal) {
		/* external objects can become "owned" */
		user_entry->is_fully_owned = TRUE;
	}

	*entry_handle = user_handle;
	return KERN_SUCCESS;
}

/*
 *	mach_memory_object_control_memory_entry_64
 *
 *	Create a named entry backed by the provided memory_object_control.
 *
 */
kern_return_t
mach_memory_object_control_memory_entry_64(
	memory_object_control_t control,
	memory_object_offset_t  offset,
	memory_object_size_t    size,
	vm_prot_t               permission,
	ipc_port_t              *entry_handle)
{
	vm_named_entry_t        user_entry;
	ipc_port_t              user_handle;
	vm_object_t             object;

	*entry_handle = IPC_PORT_NULL;

	if (control == MEMORY_OBJECT_CONTROL_NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	object = memory_object_control_to_vm_object(control);
	if (object == VM_OBJECT_NULL) {
		return KERN_INVALID_ARGUMENT;
	}
	vm_object_reference(object);

	user_entry = mach_memory_entry_allocate(&user_handle);
	user_entry->size = size;
	user_entry->offset = offset;
	user_entry->protection = permission & VM_PROT_ALL;
	user_entry->access = GET_MAP_MEM(permission);
	user_entry->is_sub_map = FALSE;

	vm_named_entry_associate_vm_object(user_entry, object, offset, size,
	    (user_entry->protection & VM_PROT_ALL));
	user_entry->internal = object->internal;
	if (VM_OBJECT_OWNER(object) != TASK_NULL) {
		/* all memory in this entry is "owned" */
		user_entry->is_fully_owned = TRUE;
	} else if (object && !object->internal) {
		/* external objects can become "owned" */
		user_entry->is_fully_owned = TRUE;
	}

	*entry_handle = user_handle;
	return KERN_SUCCESS;
}

kern_return_t
mach_memory_object_memory_entry(
	host_t          host,
	boolean_t       internal,
	vm_size_ut      size_u,
	vm_prot_ut      permission_u,
	memory_object_t pager,
	ipc_port_t      *entry_handle)
{
	return mach_memory_object_memory_entry_64( host, internal,
	           size_u, permission_u, pager, entry_handle);
}

kern_return_t
mach_memory_entry_purgable_control(
	ipc_port_t      entry_port,
	vm_purgable_t   control,
	int             *state)
{
	if (control == VM_PURGABLE_SET_STATE_FROM_KERNEL) {
		/* not allowed from user-space */
		return KERN_INVALID_ARGUMENT;
	}

	return memory_entry_purgeable_control_internal(entry_port, control, state);
}

kern_return_t
memory_entry_purgeable_control_internal(
	ipc_port_t      entry_port,
	vm_purgable_t   control,
	int             *state)
{
	kern_return_t           kr;
	vm_named_entry_t        mem_entry;
	vm_object_t             object;

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	if (control != VM_PURGABLE_SET_STATE &&
	    control != VM_PURGABLE_GET_STATE &&
	    control != VM_PURGABLE_SET_STATE_FROM_KERNEL) {
		return KERN_INVALID_ARGUMENT;
	}

	if ((control == VM_PURGABLE_SET_STATE ||
	    control == VM_PURGABLE_SET_STATE_FROM_KERNEL) &&
	    (((*state & ~(VM_PURGABLE_ALL_MASKS)) != 0) ||
	    ((*state & VM_PURGABLE_STATE_MASK) > VM_PURGABLE_STATE_MASK))) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	vm_object_lock(object);

	/* check that named entry covers entire object ? */
	if (mem_entry->offset != 0 || object->vo_size != mem_entry->size) {
		vm_object_unlock(object);
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_unlock(mem_entry);

	kr = vm_object_purgable_control(object, control, state);

	vm_object_unlock(object);

	return kr;
}

static kern_return_t
memory_entry_access_tracking_internal(
	ipc_port_t      entry_port,
	int             *access_tracking,
	uint32_t        *access_tracking_reads,
	uint32_t        *access_tracking_writes)
{
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	kern_return_t           kr;

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

#if VM_OBJECT_ACCESS_TRACKING
	vm_object_access_tracking(object,
	    access_tracking,
	    access_tracking_reads,
	    access_tracking_writes);
	kr = KERN_SUCCESS;
#else /* VM_OBJECT_ACCESS_TRACKING */
	(void) access_tracking;
	(void) access_tracking_reads;
	(void) access_tracking_writes;
	kr = KERN_NOT_SUPPORTED;
#endif /* VM_OBJECT_ACCESS_TRACKING */

	named_entry_unlock(mem_entry);

	return kr;
}

kern_return_t
mach_memory_entry_access_tracking(
	ipc_port_t      entry_port,
	int             *access_tracking,
	uint32_t        *access_tracking_reads,
	uint32_t        *access_tracking_writes)
{
	return memory_entry_access_tracking_internal(entry_port,
	           access_tracking,
	           access_tracking_reads,
	           access_tracking_writes);
}

#if DEVELOPMENT || DEBUG
/* For dtrace probe in mach_memory_entry_ownership */
extern int proc_selfpid(void);
extern char *proc_name_address(void *p);
#endif /* DEVELOPMENT || DEBUG */

/* Kernel call only, MIG uses *_from_user() below */
kern_return_t
mach_memory_entry_ownership(
	ipc_port_t      entry_port,
	task_t          owner,
	int             ledger_tag,
	int             ledger_flags)
{
	task_t                  cur_task;
	kern_return_t           kr;
	vm_named_entry_t        mem_entry;
	vm_object_t             object;

	if (ledger_flags & ~VM_LEDGER_FLAGS_ALL) {
		/* reject unexpected flags */
		return KERN_INVALID_ARGUMENT;
	}

	cur_task = current_task();
	if (cur_task == kernel_task) {
		/* kernel thread: no entitlement needed */
	} else if (ledger_flags & VM_LEDGER_FLAG_FROM_KERNEL) {
		/* call is from trusted kernel code: no entitlement needed */
	} else if ((owner != cur_task && owner != TASK_NULL) ||
	    (ledger_flags & VM_LEDGER_FLAG_NO_FOOTPRINT) ||
	    (ledger_flags & VM_LEDGER_FLAG_NO_FOOTPRINT_FOR_DEBUG) ||
	    ledger_tag == VM_LEDGER_TAG_NETWORK) {
		bool transfer_ok = false;

		/*
		 * An entitlement is required to:
		 * + tranfer memory ownership to someone else,
		 * + request that the memory not count against the footprint,
		 * + tag as "network" (since that implies "no footprint")
		 *
		 * Exception: task with task_no_footprint_for_debug == 1 on internal build
		 */
		if (!cur_task->task_can_transfer_memory_ownership &&
		    IOCurrentTaskHasEntitlement("com.apple.private.memory.ownership_transfer")) {
			cur_task->task_can_transfer_memory_ownership = TRUE;
		}
		if (cur_task->task_can_transfer_memory_ownership) {
			/* we're allowed to transfer ownership to any task */
			transfer_ok = true;
		}
#if DEVELOPMENT || DEBUG
		if (!transfer_ok &&
		    ledger_tag == VM_LEDGER_TAG_DEFAULT &&
		    (ledger_flags & VM_LEDGER_FLAG_NO_FOOTPRINT_FOR_DEBUG) &&
		    cur_task->task_no_footprint_for_debug) {
			int         to_panic = 0;
			static bool init_bootarg = false;

			/*
			 * Allow performance tools running on internal builds to hide memory usage from phys_footprint even
			 * WITHOUT an entitlement. This can be enabled by per task sysctl vm.task_no_footprint_for_debug=1
			 * with the ledger tag VM_LEDGER_TAG_DEFAULT and flag VM_LEDGER_FLAG_NO_FOOTPRINT_FOR_DEBUG.
			 *
			 * If the boot-arg "panic_on_no_footprint_for_debug" is set, the kernel will
			 * panic here in order to detect any abuse of this feature, which is intended solely for
			 * memory debugging purpose.
			 */
			if (!init_bootarg) {
				PE_parse_boot_argn("panic_on_no_footprint_for_debug", &to_panic, sizeof(to_panic));
				init_bootarg = true;
			}
			if (to_panic) {
				panic("%s: panic_on_no_footprint_for_debug is triggered by pid %d procname %s", __func__, proc_selfpid(), get_bsdtask_info(cur_task)? proc_name_address(get_bsdtask_info(cur_task)) : "?");
			}

			/*
			 * Flushing out user space processes using this interface:
			 * $ dtrace -n 'task_no_footprint_for_debug {printf("%d[%s]\n", pid, execname); stack(); ustack();}'
			 */
			DTRACE_VM(task_no_footprint_for_debug);
			transfer_ok = true;
		}
#endif /* DEVELOPMENT || DEBUG */
		if (!transfer_ok) {
			char *our_id, *their_id;
			our_id = IOTaskGetEntitlement(current_task(), "com.apple.developer.memory.transfer-send");
			their_id = IOTaskGetEntitlement(owner, "com.apple.developer.memory.transfer-accept");
			if (our_id && their_id &&
			    !strcmp(our_id, their_id)) {     /* These are guaranteed to be null-terminated */
				/* allow transfer between tasks that have matching entitlements */
				transfer_ok = true;
			}
			if (our_id) {
				kfree_data_addr(our_id);
			}
			if (their_id) {
				kfree_data_addr(their_id);
			}
		}
		if (!transfer_ok) {
			/* transfer denied */
			return KERN_NO_ACCESS;
		}

		if (ledger_flags & VM_LEDGER_FLAG_NO_FOOTPRINT_FOR_DEBUG) {
			/*
			 * We've made it past the checks above, so we either
			 * have the entitlement or the sysctl.
			 * Convert to VM_LEDGER_FLAG_NO_FOOTPRINT.
			 */
			ledger_flags &= ~VM_LEDGER_FLAG_NO_FOOTPRINT_FOR_DEBUG;
			ledger_flags |= VM_LEDGER_FLAG_NO_FOOTPRINT;
		}
	}

	if (ledger_tag == VM_LEDGER_TAG_UNCHANGED) {
		/* leave "ledger_tag" unchanged */
	} else if (ledger_tag < 0 ||
	    ledger_tag > VM_LEDGER_TAG_MAX) {
		return KERN_INVALID_ARGUMENT;
	}
	if (owner == TASK_NULL) {
		/* leave "owner" unchanged */
		owner = VM_OBJECT_OWNER_UNCHANGED;
	}

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    !mem_entry->is_fully_owned) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	if (mem_entry->is_object) {
		object = vm_named_entry_to_vm_object(mem_entry);
		if (object == VM_OBJECT_NULL) {
			named_entry_unlock(mem_entry);
			return KERN_INVALID_ARGUMENT;
		}
		vm_object_lock(object);
		if (object->internal) {
			/* check that named entry covers entire object ? */
			if (mem_entry->offset != 0 ||
			    object->vo_size != mem_entry->size) {
				vm_object_unlock(object);
				named_entry_unlock(mem_entry);
				return KERN_INVALID_ARGUMENT;
			}
		}
		named_entry_unlock(mem_entry);
		kr = vm_object_ownership_change(object,
		    ledger_tag,
		    owner,
		    ledger_flags,
		    FALSE);                             /* task_objq_locked */
		vm_object_unlock(object);
	} else if (mem_entry->is_copy) {
		vm_map_copy_t copy;
		vm_map_entry_t entry;

		copy = mem_entry->backing.copy;
		for (entry = vm_map_copy_first_entry(copy);
		    entry != vm_map_copy_to_entry(copy);
		    entry = entry->vme_next) {
			object = VME_OBJECT(entry);
			if (entry->is_sub_map ||
			    object == VM_OBJECT_NULL) {
				kr = KERN_INVALID_ARGUMENT;
				break;
			}
			vm_object_lock(object);
			if (object->internal) {
				if (VME_OFFSET(entry) != 0 ||
				    entry->vme_end - entry->vme_start != object->vo_size) {
					vm_object_unlock(object);
					kr = KERN_INVALID_ARGUMENT;
					break;
				}
			}
			kr = vm_object_ownership_change(object,
			    ledger_tag,
			    owner,
			    ledger_flags,
			    FALSE);                             /* task_objq_locked */
			vm_object_unlock(object);
			if (kr != KERN_SUCCESS) {
				kr = KERN_INVALID_ARGUMENT;
				break;
			}
		}
		named_entry_unlock(mem_entry);
	} else {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	return kr;
}

/* MIG call from userspace */
kern_return_t
mach_memory_entry_ownership_from_user(
	ipc_port_t      entry_port,
	mach_port_t     owner_port,
	int             ledger_tag,
	int             ledger_flags)
{
	task_t owner = TASK_NULL;
	kern_return_t kr;

	if (ledger_flags & ~VM_LEDGER_FLAGS_USER) {
		return KERN_INVALID_ARGUMENT;
	}

	if (IP_VALID(owner_port)) {
		if (ip_type(owner_port) == IKOT_TASK_ID_TOKEN) {
			task_id_token_t token = convert_port_to_task_id_token(owner_port);
			(void)task_identity_token_get_task_grp(token, &owner, TASK_GRP_MIG);
			task_id_token_release(token);
			/* token ref released */
		} else {
			owner = convert_port_to_task_mig(owner_port);
		}
	}
	/* hold task ref on owner (Nullable) */

	if (owner && task_is_a_corpse(owner)) {
		/* identity token can represent a corpse, disallow it */
		task_deallocate_mig(owner);
		owner = TASK_NULL;
	}

	/* mach_memory_entry_ownership() will handle TASK_NULL owner */
	kr = mach_memory_entry_ownership(entry_port, owner, /* Nullable */
	    ledger_tag, ledger_flags);

	if (owner) {
		task_deallocate_mig(owner);
	}

	if (kr == KERN_SUCCESS) {
		/* MIG rule, consume port right on success */
		ipc_port_release_send(owner_port);
	}
	return kr;
}

kern_return_t
mach_memory_entry_get_page_counts(
	ipc_port_t      entry_port,
	uint64_t        *resident_page_count,
	uint64_t        *dirty_page_count,
	uint64_t        *swapped_page_count)
{
	kern_return_t           kr;
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	vm_object_offset_t      offset;
	vm_object_size_t        size;

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	vm_object_lock(object);

	offset = mem_entry->offset;
	size = mem_entry->size;
	size = vm_object_round_page(offset + size) - vm_object_trunc_page(offset);
	offset = vm_object_trunc_page(offset);

	named_entry_unlock(mem_entry);

	kr = vm_object_get_page_counts(object, offset, size, resident_page_count, dirty_page_count, swapped_page_count);

	vm_object_unlock(object);

	return kr;
}

kern_return_t
mach_memory_entry_phys_page_offset(
	ipc_port_t              entry_port,
	vm_object_offset_t      *offset_p)
{
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	vm_object_offset_t      offset;
	vm_object_offset_t      data_offset;

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	offset = mem_entry->offset;
	data_offset = mem_entry->data_offset;

	named_entry_unlock(mem_entry);

	*offset_p = offset - vm_object_trunc_page(offset) + data_offset;
	return KERN_SUCCESS;
}

static inline kern_return_t
mach_memory_entry_map_size_sanitize_locked(
	vm_map_t                   map,
	memory_object_offset_ut   *offset_u,
	memory_object_size_ut      size_u,
	vm_named_entry_t           mem_entry,
	memory_object_offset_t    *offset,
	memory_object_offset_t    *end,
	mach_vm_size_t            *map_size)
{
	kern_return_t           kr;

	if (mem_entry->is_object ||
	    (mem_entry->is_copy &&
	    (VM_MAP_COPY_PAGE_MASK(mem_entry->backing.copy) ==
	    VM_MAP_PAGE_MASK(map)))) {
		if (__improbable(vm_sanitize_add_overflow(*offset_u, mem_entry->offset,
		    offset_u))) {
			return KERN_INVALID_ARGUMENT;
		}
	}

	if (__improbable(vm_sanitize_add_overflow(*offset_u, mem_entry->data_offset,
	    offset_u))) {
		return KERN_INVALID_ARGUMENT;
	}

	kr = vm_sanitize_addr_size(*offset_u, size_u,
	    VM_SANITIZE_CALLER_MACH_MEMORY_ENTRY_MAP_SIZE, map,
	    VM_SANITIZE_FLAGS_SIZE_ZERO_FALLTHROUGH, offset, end, map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		return vm_sanitize_get_kr(kr);
	}

	return KERN_SUCCESS;
}

kern_return_t
mach_memory_entry_map_size(
	ipc_port_t                 entry_port,
	vm_map_t                   map,
	memory_object_offset_ut    offset_u,
	memory_object_size_ut      size_u,
	mach_vm_size_t            *map_size_out)
{
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	vm_map_copy_t           copy_map, target_copy_map;
	vm_map_offset_t         overmap_start, overmap_end, trimmed_start;
	kern_return_t           kr;
	memory_object_offset_t  offset;
	memory_object_offset_t  end;
	mach_vm_size_t          map_size;

	*map_size_out = 0;

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	/*
	 * Sanitize offset and size before use
	 */
	kr = mach_memory_entry_map_size_sanitize_locked(map,
	    &offset_u,
	    size_u,
	    mem_entry,
	    &offset,
	    &end,
	    &map_size);
	if (__improbable(kr != KERN_SUCCESS)) {
		named_entry_unlock(mem_entry);
		return kr;
	}

	if (mem_entry->is_object) {
		object = vm_named_entry_to_vm_object(mem_entry);
		if (object == VM_OBJECT_NULL) {
			named_entry_unlock(mem_entry);
			return KERN_INVALID_ARGUMENT;
		}

		named_entry_unlock(mem_entry);
		*map_size_out = map_size;
		return KERN_SUCCESS;
	}

	if (!mem_entry->is_copy) {
		panic("unsupported type of mem_entry %p", mem_entry);
	}

	assert(mem_entry->is_copy);
	if (VM_MAP_COPY_PAGE_MASK(mem_entry->backing.copy) == VM_MAP_PAGE_MASK(map)) {
		DEBUG4K_SHARE("map %p (%d) mem_entry %p offset 0x%llx + 0x%llx + 0x%llx size 0x%llx -> map_size 0x%llx\n", map, VM_MAP_PAGE_MASK(map), mem_entry, mem_entry->offset, mem_entry->data_offset, offset, VM_SANITIZE_UNSAFE_UNWRAP(size_u), map_size);
		named_entry_unlock(mem_entry);
		*map_size_out = map_size;
		return KERN_SUCCESS;
	}

	DEBUG4K_SHARE("mem_entry %p copy %p (%d) map %p (%d) offset 0x%llx size 0x%llx\n", mem_entry, mem_entry->backing.copy, VM_MAP_COPY_PAGE_SHIFT(mem_entry->backing.copy), map, VM_MAP_PAGE_SHIFT(map), offset, VM_SANITIZE_UNSAFE_UNWRAP(size_u));
	copy_map = mem_entry->backing.copy;
	target_copy_map = VM_MAP_COPY_NULL;
	DEBUG4K_ADJUST("adjusting...\n");
	kr = vm_map_copy_adjust_to_target(copy_map,
	    offset_u,
	    size_u,
	    map,
	    FALSE,
	    &target_copy_map,
	    &overmap_start,
	    &overmap_end,
	    &trimmed_start);
	if (kr == KERN_SUCCESS) {
		if (target_copy_map->size != copy_map->size) {
			DEBUG4K_ADJUST("copy %p (%d) map %p (%d) offset 0x%llx size 0x%llx overmap_start 0x%llx overmap_end 0x%llx trimmed_start 0x%llx map_size 0x%llx -> 0x%llx\n", copy_map, VM_MAP_COPY_PAGE_SHIFT(copy_map), map, VM_MAP_PAGE_SHIFT(map), (uint64_t)offset, (uint64_t)VM_SANITIZE_UNSAFE_UNWRAP(size_u), (uint64_t)overmap_start, (uint64_t)overmap_end, (uint64_t)trimmed_start, (uint64_t)copy_map->size, (uint64_t)target_copy_map->size);
		}
		*map_size_out = target_copy_map->size;
		if (target_copy_map != copy_map) {
			vm_map_copy_discard(target_copy_map);
		}
		target_copy_map = VM_MAP_COPY_NULL;
	}
	named_entry_unlock(mem_entry);
	return kr;
}

/*
 * mach_memory_entry_port_release:
 *
 * Release a send right on a named entry port.  This is the correct
 * way to destroy a named entry.  When the last right on the port is
 * released, mach_memory_entry_no_senders() willl be called.
 */
void
mach_memory_entry_port_release(
	ipc_port_t      port)
{
	assert(ip_type(port) == IKOT_NAMED_ENTRY);
	ipc_port_release_send(port);
}

vm_named_entry_t
mach_memory_entry_from_port(ipc_port_t port)
{
	if (IP_VALID(port)) {
		return ipc_kobject_get_stable(port, IKOT_NAMED_ENTRY);
	}
	return NULL;
}

void
mach_memory_entry_describe(
	vm_named_entry_t named_entry,
	kobject_description_t desc)
{
	vm_object_t vm_object;
	if (named_entry->is_object) {
		vm_object = vm_named_entry_to_vm_object(named_entry);
		vm_object_size_t size = vm_object->internal ?
		    vm_object->vo_un1.vou_size : 0;
		snprintf(desc, KOBJECT_DESCRIPTION_LENGTH,
		    "VM-OBJECT(0x%x, %lluKiB)",
		    VM_OBJECT_ID(vm_object),
		    BtoKiB(size));
	} else if (named_entry->is_copy) {
		vm_map_copy_t copy_map = named_entry->backing.copy;
		snprintf(desc, KOBJECT_DESCRIPTION_LENGTH,
		    "VM-MAP-COPY(0x%lx, %lluKiB)",
		    VM_KERNEL_ADDRHASH(copy_map),
		    BtoKiB(copy_map->size));
	} else if (named_entry->is_sub_map) {
		vm_map_t submap = named_entry->backing.map;
		snprintf(desc, KOBJECT_DESCRIPTION_LENGTH,
		    "VM-SUB-MAP(0x%lx, %lluKiB)",
		    VM_KERNEL_ADDRHASH(submap),
		    BtoKiB(submap->size));
	}
}

memory_object_size_t
mach_memory_entry_size(ipc_port_t port)
{
	vm_named_entry_t entry;

	assert(ip_type(port) == IKOT_NAMED_ENTRY);
	entry = mach_memory_entry_from_port(port);
	assert(entry);
	if (NULL == entry) {
		return 0;
	}
	return entry->size;
}


/*
 * mach_memory_entry_no_senders:
 *
 * Destroys the memory entry associated with a mach port.
 * Memory entries have the exact same lifetime as their owning port.
 *
 * Releasing a memory entry is done by calling
 * mach_memory_entry_port_release() on its owning port.
 */
static void
mach_memory_entry_no_senders(ipc_port_t port, mach_port_mscount_t mscount)
{
	vm_named_entry_t named_entry;

	named_entry = ipc_kobject_dealloc_port(port, mscount, IKOT_NAMED_ENTRY);

	if (named_entry->is_sub_map) {
		vm_map_deallocate(named_entry->backing.map);
	} else if (named_entry->is_copy) {
		vm_map_copy_discard(named_entry->backing.copy);
	} else if (named_entry->is_object) {
		assert(named_entry->backing.copy->cpy_hdr.nentries == 1);
		vm_map_copy_discard(named_entry->backing.copy);
	} else {
		assert(named_entry->backing.copy == VM_MAP_COPY_NULL);
	}

#if VM_NAMED_ENTRY_DEBUG
	btref_put(named_entry->named_entry_bt);
#endif /* VM_NAMED_ENTRY_DEBUG */

	named_entry_lock_destroy(named_entry);
	kfree_type(struct vm_named_entry, named_entry);
}

#if XNU_PLATFORM_MacOSX
/* Allow manipulation of individual page state.  This is actually part of */
/* the UPL regimen but takes place on the memory entry rather than on a UPL */

kern_return_t
mach_memory_entry_page_op(
	ipc_port_t              entry_port,
	vm_object_offset_ut     offset_u,
	int                     ops,
	ppnum_t                 *phys_entry,
	int                     *flags)
{
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	kern_return_t           kr;
	/*
	 * Unwrap offset as no mathematical operations are
	 * performed on it.
	 */
	vm_object_offset_t      offset = VM_SANITIZE_UNSAFE_UNWRAP(offset_u);

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	vm_object_reference(object);
	named_entry_unlock(mem_entry);

	kr = vm_object_page_op(object, offset, ops, phys_entry, flags);

	vm_object_deallocate(object);

	return kr;
}

/*
 * mach_memory_entry_range_op offers performance enhancement over
 * mach_memory_entry_page_op for page_op functions which do not require page
 * level state to be returned from the call.  Page_op was created to provide
 * a low-cost alternative to page manipulation via UPLs when only a single
 * page was involved.  The range_op call establishes the ability in the _op
 * family of functions to work on multiple pages where the lack of page level
 * state handling allows the caller to avoid the overhead of the upl structures.
 */

kern_return_t
mach_memory_entry_range_op(
	ipc_port_t              entry_port,
	vm_object_offset_ut     offset_beg_u,
	vm_object_offset_ut     offset_end_u,
	int                     ops,
	int                     *range)
{
	vm_named_entry_t        mem_entry;
	vm_object_t             object;
	kern_return_t           kr;
	vm_object_offset_t      offset_range;
	/*
	 * Unwrap offset beginning and end as no mathematical operations are
	 * performed on these quantities.
	 */
	vm_object_offset_t      offset_beg = VM_SANITIZE_UNSAFE_UNWRAP(offset_beg_u);
	vm_object_offset_t      offset_end = VM_SANITIZE_UNSAFE_UNWRAP(offset_end_u);

	mem_entry = mach_memory_entry_from_port(entry_port);
	if (mem_entry == NULL) {
		return KERN_INVALID_ARGUMENT;
	}

	named_entry_lock(mem_entry);

	if (__improbable(os_sub_overflow(offset_end, offset_beg, &offset_range) ||
	    (offset_range > (uint32_t) -1))) {
		/* range is too big and would overflow "*range" */
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	if (mem_entry->is_sub_map ||
	    mem_entry->is_copy) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	assert(mem_entry->is_object);
	object = vm_named_entry_to_vm_object(mem_entry);
	if (object == VM_OBJECT_NULL) {
		named_entry_unlock(mem_entry);
		return KERN_INVALID_ARGUMENT;
	}

	vm_object_reference(object);
	named_entry_unlock(mem_entry);

	kr = vm_object_range_op(object,
	    offset_beg,
	    offset_end,
	    ops,
	    (uint32_t *) range);

	vm_object_deallocate(object);

	return kr;
}
#endif /* XNU_PLATFORM_MacOSX */

kern_return_t
memory_entry_check_for_adjustment(
	vm_map_t                        src_map,
	ipc_port_t                      port,
	vm_map_offset_t         *overmap_start,
	vm_map_offset_t         *overmap_end)
{
	kern_return_t kr = KERN_SUCCESS;
	vm_map_copy_t copy_map = VM_MAP_COPY_NULL, target_copy_map = VM_MAP_COPY_NULL;

	assert(port);
	assertf(ip_type(port) == IKOT_NAMED_ENTRY,
	    "Port Type expected: %d...received:%d\n",
	    IKOT_NAMED_ENTRY, ip_type(port));

	vm_named_entry_t        named_entry;

	named_entry = mach_memory_entry_from_port(port);
	named_entry_lock(named_entry);
	copy_map = named_entry->backing.copy;
	target_copy_map = copy_map;

	if (src_map && VM_MAP_PAGE_SHIFT(src_map) < PAGE_SHIFT) {
		vm_map_offset_t trimmed_start;

		trimmed_start = 0;
		DEBUG4K_ADJUST("adjusting...\n");
		kr = vm_map_copy_adjust_to_target(
			copy_map,
			vm_sanitize_wrap_addr(0), /* offset */
			vm_sanitize_wrap_size(copy_map->size), /* size */
			src_map,
			FALSE, /* copy */
			&target_copy_map,
			overmap_start,
			overmap_end,
			&trimmed_start);
		assert(trimmed_start == 0);
	}
	named_entry_unlock(named_entry);

	return kr;
}

vm_named_entry_t
vm_convert_port_to_named_entry(
	ipc_port_t      port)
{
	/* Invalid / wrong port type? */
	if (!IP_VALID(port) || ip_type(port) != IKOT_NAMED_ENTRY) {
		return NULL;
	}

	vm_named_entry_t named_entry = mach_memory_entry_from_port(port);

	/* This is a no-op, it's here for reader clarity */
	if (!named_entry) {
		return NULL;
	}

	return named_entry;
}

vm_object_t
vm_convert_port_to_copy_object(
	ipc_port_t      port)
{
	vm_named_entry_t named_entry = vm_convert_port_to_named_entry(port);
	/* We expect the named entry to point to an object. */
	if (!named_entry || !named_entry->is_object) {
		return NULL;
	}
	/* Pull out the copy map object... */
	return vm_named_entry_to_vm_object(named_entry);
}

#pragma mark - tests
#if DEBUG || DEVELOPMENT

/*
 * Makes sure that tagged kernel addresses are handled
 * appropriately when creating a memory entry out of them
 * intended for sharing.
 *
 * In particular, tagged addresses due to KASAN should be
 * canonicalized prior to sanitization.
 */
static int
mach_make_memory_entry_share_kernel_heap_test_run(
	__unused int64_t in,
	int64_t *out)
{
	kern_return_t kr  = KERN_SUCCESS;
	vm_offset_t data  = 0;
	ipc_port_t handle = MACH_PORT_NULL;
	vm_named_entry_kernel_flags_t vmne_kflags = VM_NAMED_ENTRY_KERNEL_FLAGS_NONE;
	memory_object_size_t  size = PAGE_SIZE;
	memory_object_size_ut size_u = vm_sanitize_wrap_size(size);

	kr = kmem_alloc(
		kernel_map,
		&data,
		size,
		KMA_ZERO | KMA_DATA | KMA_TAG,
		VM_KERN_MEMORY_KALLOC_DATA);
	printf("%s: data: %lx\n", __func__, data);
	assert(data);

	kr = mach_make_memory_entry_share(
		kernel_map,
		&size_u,
		(vm_map_offset_t)data,
		VM_PROT_DEFAULT, /* need write permission to test vm_map_lookup_object_and_lock_entry() */
		vmne_kflags,
		&handle,
		MACH_PORT_NULL,
		NULL);

	assert3u(kr, ==, KERN_SUCCESS);

	kmem_free(kernel_map, data, size, KMF_TAG);
	*out = 1;
	return 0;
}
SYSCTL_TEST_REGISTER(memory_entry_share_kernel_heap_test,
    mach_make_memory_entry_share_kernel_heap_test_run);

#endif /* DEBUG || DEVELOPMENT */