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
|
/* CFPropertyList.c
Copyright (c) 1999-2019, Apple Inc. and the Swift project authors
Portions Copyright (c) 2014-2019, Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
Responsibility: Itai Ferber
*/
#include "CFPropertyList.h"
#include "CFPropertyList_Private.h"
#include "CFPropertyList_Internal.h"
#include "CFByteOrder.h"
#include "CFDate.h"
#include "CFNumber.h"
#include "CFSet.h"
#include "CFError.h"
#include "CFError_Private.h"
#include "CFPriv.h"
#include "CFStringEncodingConverter.h"
#include "CFNumber_Private.h"
#include "CFInternal.h"
#include "CFRuntime_Internal.h"
#include "CFBurstTrie.h"
#include "CFString.h"
#include "CFStream.h"
#include "CFCalendar.h"
#include "CFLocaleInternal.h"
#include <limits.h>
#include <float.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#include "CFOverflow.h"
#define PLIST_IX 0
#define ARRAY_IX 1
#define DICT_IX 2
#define KEY_IX 3
#define STRING_IX 4
#define DATA_IX 5
#define DATE_IX 6
#define REAL_IX 7
#define INTEGER_IX 8
#define TRUE_IX 9
#define FALSE_IX 10
#define DOCTYPE_IX 11
#define CDSECT_IX 12
#define PLIST_TAG_LENGTH 5
#define ARRAY_TAG_LENGTH 5
#define DICT_TAG_LENGTH 4
#define KEY_TAG_LENGTH 3
#define STRING_TAG_LENGTH 6
#define DATA_TAG_LENGTH 4
#define DATE_TAG_LENGTH 4
#define REAL_TAG_LENGTH 4
#define INTEGER_TAG_LENGTH 7
#define TRUE_TAG_LENGTH 4
#define FALSE_TAG_LENGTH 5
#define DOCTYPE_TAG_LENGTH 7
#define CDSECT_TAG_LENGTH 9
#if !defined(new_cftype_array)
#define new_cftype_array(N, C) \
size_t N ## _count__ = (C); \
if (N ## _count__ > LONG_MAX / sizeof(CFTypeRef)) { \
CRSetCrashLogMessage("CFPropertyList ran out of memory while attempting to allocate temporary storage."); \
HALT; \
} \
Boolean N ## _is_stack__ = (N ## _count__ <= 256); \
if (N ## _count__ == 0) N ## _count__ = 1; \
STACK_BUFFER_DECL(CFTypeRef, N ## _buffer__, N ## _is_stack__ ? N ## _count__ : 1); \
if (N ## _is_stack__) memset(N ## _buffer__, 0, N ## _count__ * sizeof(CFTypeRef)); \
CFTypeRef * N = N ## _is_stack__ ? N ## _buffer__ : (CFTypeRef *)CFAllocatorAllocate(kCFAllocatorSystemDefault, (N ## _count__) * sizeof(CFTypeRef), 0); \
if (! N) { \
CRSetCrashLogMessage("CFPropertyList ran out of memory while attempting to allocate temporary storage."); \
HALT; \
} \
do {} while (0)
#endif
#if !defined(free_cftype_array)
#define free_cftype_array(N) \
if (! N ## _is_stack__) { \
CFAllocatorDeallocate(kCFAllocatorSystemDefault, N); \
} \
do {} while (0)
#endif
// Used to reference an old-style plist parser error inside of a more general XML error
#define CFPropertyListOldStyleParserErrorKey CFSTR("kCFPropertyListOldStyleParsingError")
CF_PRIVATE CFErrorRef __CFPropertyListCreateError(CFIndex code, CFStringRef debugString, ...) {
va_list argList;
CFErrorRef error = NULL;
if (debugString != NULL) {
CFStringRef debugMessage = NULL;
va_start(argList, debugString);
debugMessage = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, NULL, debugString, argList);
va_end(argList);
CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, debugMessage);
error = CFErrorCreate(kCFAllocatorSystemDefault, kCFErrorDomainCocoa, code, userInfo);
CFRelease(debugMessage);
CFRelease(userInfo);
} else {
error = CFErrorCreate(kCFAllocatorSystemDefault, kCFErrorDomainCocoa, code, NULL);
}
return error;
}
static CFStringRef __copyErrorDebugDescription(CFErrorRef error) {
CFStringRef result = NULL;
if (error) {
CFDictionaryRef userInfo = CFErrorCopyUserInfo(error);
if (userInfo != NULL) {
CFStringRef desc = (CFStringRef) CFDictionaryGetValue(userInfo, kCFErrorDebugDescriptionKey);
if (desc != NULL) {
result = CFStringCreateCopy(kCFAllocatorSystemDefault, desc);
}
CFRelease(userInfo);
}
}
return result;
}
#pragma mark -
#pragma mark Property List Validation
// don't allow _CFKeyedArchiverUID here
#define __CFAssertIsPList(cf) CFAssert2(CFGetTypeID(cf) == CFStringGetTypeID() || CFGetTypeID(cf) == CFArrayGetTypeID() || CFGetTypeID(cf) == CFBooleanGetTypeID() || CFGetTypeID(cf) == CFNumberGetTypeID() || CFGetTypeID(cf) == CFDictionaryGetTypeID() || CFGetTypeID(cf) == CFDateGetTypeID() || CFGetTypeID(cf) == CFDataGetTypeID(), __kCFLogAssertion, "%s(): %p not of a property list type", __PRETTY_FUNCTION__, cf);
typedef struct context {
bool answer;
CFPropertyListFormat format;
CFMutableSetRef _Nullable set;
CFStringRef * _Nullable error;
CFMutableBagRef _Nullable referenceBag; /* Only used for non-bplists */
} ___CFPropertyListIsValidContext;
typedef ___CFPropertyListIsValidContext * __CFPropertyListIsValidContext;
static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, __CFPropertyListIsValidContext _Nonnull context);
static void __CFPropertyListIsArrayPlistAux(const void *value, void *context) {
__CFPropertyListIsValidContext ctx = context;
if (!ctx->answer) return;
if (!value && ctx->error && !*(ctx->error)) {
*(ctx->error) = (CFStringRef)CFRetain(CFSTR("property list arrays cannot contain NULL"));
}
ctx->answer = value && __CFPropertyListIsValidAux(value, true, ctx);
}
static void __CFPropertyListIsDictPlistAux(const void *key, const void *value, void *context) {
__CFPropertyListIsValidContext ctx = context;
if (!ctx->answer) return;
if (!key && ctx->error && !*(ctx->error)) *(ctx->error) = (CFStringRef)CFRetain(CFSTR("property list dictionaries cannot contain NULL keys"));
if (!value && ctx->error && !*(ctx->error)) *(ctx->error) = (CFStringRef)CFRetain(CFSTR("property list dictionaries cannot contain NULL values"));
if (_kCFRuntimeIDCFString != CFGetTypeID(key) && ctx->error && !*(ctx->error)) {
CFStringRef desc = CFCopyTypeIDDescription(CFGetTypeID(key));
*(ctx->error) = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("property list dictionaries may only have keys which are CFStrings, not '%@'"), desc);
CFRelease(desc);
}
ctx->answer = key && value && (_kCFRuntimeIDCFString == CFGetTypeID(key)) && __CFPropertyListIsValidAux(value, true, ctx);
}
static bool __CFPropertyListIsValidAux(CFPropertyListRef plist, bool recursive, __CFPropertyListIsValidContext _Nonnull context) {
CFAssert1(context != NULL, __kCFLogAssertion, "%s(): context cannot be null", __PRETTY_FUNCTION__);
if (!plist) {
if (context->error) *context->error = (CFStringRef)CFRetain(CFSTR("property lists cannot contain NULL"));
return false;
}
CFTypeID type = CFGetTypeID(plist);
if (_kCFRuntimeIDCFString == type) return true;
if (_kCFRuntimeIDCFData == type) return true;
if (kCFPropertyListOpenStepFormat != context->format) {
if (_kCFRuntimeIDCFBoolean == type) return true;
if (_kCFRuntimeIDCFNumber == type) return true;
if (_kCFRuntimeIDCFDate == type) return true;
if (_CFKeyedArchiverUIDGetTypeID() == type) return true;
}
if (!recursive && _kCFRuntimeIDCFArray == type) {
return true;
}
if (!recursive && _kCFRuntimeIDCFDictionary == type) {
return true;
}
// At any one invocation of this function, referenceBag should contain the objects in the "path" down to this object.
// For the outermost invocation it can be NULL.
bool createdSet = false;
if (!context->set) {
context->set = CFSetCreateMutable(kCFAllocatorSystemDefault, 0, NULL);
createdSet = true;
} else if (CFSetContainsValue(context->set, plist)) {
if (context->error) *context->error = (CFStringRef)CFRetain(CFSTR("property lists cannot contain recursive container references"));
return false;
}
// It's valid for bplists to contain references to other collections
// consider this:
//
// C = @[ @"a", @"a", @"a" ];
// B = @[ c, c, c ];
// A = @[ b, b, b ];
//
// But this can cause an explosion when converting those endlessly
// recursive collections to XML or OpenSTEP plists. We already have
// a max recursion depth limit, if we exceed it consider the plist invalid.
bool createdRefBag = false;
bool const limitCollectionDepth = context->format != kCFPropertyListBinaryFormat_v1_0;
if (limitCollectionDepth) {
if (!context->referenceBag) {
CFBagCallBacks callbacks = kCFTypeBagCallBacks;
callbacks.equal = NULL;
callbacks.hash = NULL;
context->referenceBag = CFBagCreateMutable(kCFAllocatorDefault, 0, &callbacks);
createdRefBag = true;
} else if (CFBagGetCountOfValue(context->referenceBag, plist) > _CFPropertyListMaxRecursionWidth()) {
if (context->error) *context->error = (CFStringRef)CFRetain(CFSTR("Too many nested arrays or dictionaries please use kCFPropertyListBinaryFormat_v1_0 instead which supports references"));
return false;
}
}
bool result = false;
if (_kCFRuntimeIDCFArray == type) {
CFIndex const arrayCount = CFArrayGetCount((CFArrayRef)plist);
// only arrays larger than zero could have cyclic references
if (arrayCount > 0 && limitCollectionDepth) {
CFBagAddValue(context->referenceBag, plist);
}
CFSetAddValue(context->set, plist);
CFArrayApplyFunction((CFArrayRef)plist, CFRangeMake(0, arrayCount), __CFPropertyListIsArrayPlistAux, context);
CFSetRemoveValue(context->set, plist);
result = context->answer;
} else if (_kCFRuntimeIDCFDictionary == type) {
CFIndex const dictCount = CFDictionaryGetCount((CFDictionaryRef)plist);
// only dictionaries larger than zero could have cyclic references
if (dictCount > 0 && limitCollectionDepth) {
CFBagAddValue(context->referenceBag, plist);
}
CFSetAddValue(context->set, plist);
CFDictionaryApplyFunction((CFDictionaryRef)plist, __CFPropertyListIsDictPlistAux, context);
CFSetRemoveValue(context->set, plist);
result = context->answer;
} else if (context->error) {
CFStringRef desc = CFCopyTypeIDDescription(type);
*context->error = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("property lists cannot contain objects of type '%@'"), desc);
CFRelease(desc);
}
if (createdSet) {
CFAssert1(context->set != NULL, __kCFLogAssertion, "%s(): context->set cannot be null", __PRETTY_FUNCTION__);
CFRelease(context->set);
context->set = NULL;
}
if (createdRefBag) {
CFAssert1(context->referenceBag != NULL, __kCFLogAssertion, "%s(): context->referenceBag cannot be null", __PRETTY_FUNCTION__);
CFRelease(context->referenceBag);
context->referenceBag = NULL;
}
return result;
}
static Boolean _CFPropertyListIsValidWithErrorString(CFPropertyListRef plist, CFPropertyListFormat format, CFStringRef *error) {
CFAssert1(plist != NULL, __kCFLogAssertion, "%s(): NULL is not a property list", __PRETTY_FUNCTION__);
___CFPropertyListIsValidContext context = {
.answer = true,
.format = format,
.error = error,
.referenceBag = NULL
};
return (Boolean)__CFPropertyListIsValidAux(plist, true, &context);
}
#pragma mark -
#pragma mark Writing Property Lists
static const char CFXMLPlistTags[13][10]= {
{'p', 'l', 'i', 's', 't', '\0', '\0', '\0', '\0', '\0'},
{'a', 'r', 'r', 'a', 'y', '\0', '\0', '\0', '\0', '\0'},
{'d', 'i', 'c', 't', '\0', '\0', '\0', '\0', '\0', '\0'},
{'k', 'e', 'y', '\0', '\0', '\0', '\0', '\0', '\0', '\0'},
{'s', 't', 'r', 'i', 'n', 'g', '\0', '\0', '\0', '\0'},
{'d', 'a', 't', 'a', '\0', '\0', '\0', '\0', '\0', '\0'},
{'d', 'a', 't', 'e', '\0', '\0', '\0', '\0', '\0', '\0'},
{'r', 'e', 'a', 'l', '\0', '\0', '\0', '\0', '\0', '\0'},
{'i', 'n', 't', 'e', 'g', 'e', 'r', '\0', '\0', '\0'},
{'t', 'r', 'u', 'e', '\0', '\0', '\0', '\0', '\0', '\0'},
{'f', 'a', 'l', 's', 'e', '\0', '\0', '\0', '\0', '\0'},
{'D', 'O', 'C', 'T', 'Y', 'P', 'E', '\0', '\0', '\0'},
{'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[', '\0'}
};
static const UniChar CFXMLPlistTagsUnicode[13][10]= {
{'p', 'l', 'i', 's', 't', '\0', '\0', '\0', '\0', '\0'},
{'a', 'r', 'r', 'a', 'y', '\0', '\0', '\0', '\0', '\0'},
{'d', 'i', 'c', 't', '\0', '\0', '\0', '\0', '\0', '\0'},
{'k', 'e', 'y', '\0', '\0', '\0', '\0', '\0', '\0', '\0'},
{'s', 't', 'r', 'i', 'n', 'g', '\0', '\0', '\0', '\0'},
{'d', 'a', 't', 'a', '\0', '\0', '\0', '\0', '\0', '\0'},
{'d', 'a', 't', 'e', '\0', '\0', '\0', '\0', '\0', '\0'},
{'r', 'e', 'a', 'l', '\0', '\0', '\0', '\0', '\0', '\0'},
{'i', 'n', 't', 'e', 'g', 'e', 'r', '\0', '\0', '\0'},
{'t', 'r', 'u', 'e', '\0', '\0', '\0', '\0', '\0', '\0'},
{'f', 'a', 'l', 's', 'e', '\0', '\0', '\0', '\0', '\0'},
{'D', 'O', 'C', 'T', 'Y', 'P', 'E', '\0', '\0', '\0'},
{'<', '!', '[', 'C', 'D', 'A', 'T', 'A', '[', '\0'}
};
typedef struct {
const char *begin; // first character of the XML to be parsed
const char *curr; // current parse location
const char *end; // the first character _after_ the end of the XML
CFErrorRef error;
CFAllocatorRef allocator;
UInt32 mutabilityOption;
CFBurstTrieRef stringTrie; // map of cached strings
CFMutableArrayRef stringCache; // retaining array of strings
Boolean allowNewTypes; // Whether to allow the new types supported by XML property lists, but not by the old, OPENSTEP ASCII property lists (CFNumber, CFBoolean, CFDate)
CFSetRef keyPaths; // if NULL, no filtering
Boolean skip; // if true, do not create any objects.
} _CFXMLPlistParseInfo;
CF_PRIVATE CFTypeRef __CFCreateOldStylePropertyListOrStringsFile(CFAllocatorRef allocator, CFDataRef xmlData, CFStringRef originalString, CFStringEncoding guessedEncoding, CFOptionFlags option, CFErrorRef *outError,CFPropertyListFormat *format);
CF_INLINE void __CFPListRelease(CFTypeRef cf, CFAllocatorRef allocator) {
if (cf) CFRelease(cf);
}
// The following set of _plist... functions append various things to a mutable data which is in UTF8 encoding. These are pretty general. Assumption is call characters and CFStrings can be converted to UTF8 and appended.
// Null-terminated, ASCII or UTF8 string
//
static void _plistAppendUTF8CString(CFMutableDataRef mData, const char *cString) {
CFDataAppendBytes (mData, (const UInt8 *)cString, strlen(cString));
}
// UniChars
//
static void _plistAppendCharacters(CFMutableDataRef mData, const UniChar *chars, CFIndex length) {
CFIndex curLoc = 0;
do { // Flush out ASCII chars, BUFLEN at a time
#define BUFLEN 400
UInt8 buf[BUFLEN], *bufPtr = buf;
CFIndex cnt = 0;
while (cnt < length && (cnt - curLoc < BUFLEN) && (chars[cnt] < 128)) *bufPtr++ = (UInt8)(chars[cnt++]);
if (cnt > curLoc) { // Flush any ASCII bytes
CFDataAppendBytes(mData, buf, cnt - curLoc);
curLoc = cnt;
}
} while (curLoc < length && (chars[curLoc] < 128)); // We will exit out of here when we run out of chars or hit a non-ASCII char
if (curLoc < length) { // Now deal with non-ASCII chars
CFDataRef data = NULL;
CFStringRef str = NULL;
if ((str = CFStringCreateWithCharactersNoCopy(kCFAllocatorSystemDefault, chars + curLoc, length - curLoc, kCFAllocatorNull))) {
if ((data = CFStringCreateExternalRepresentation(kCFAllocatorSystemDefault, str, kCFStringEncodingUTF8, 0))) {
CFDataAppendBytes (mData, CFDataGetBytePtr(data), CFDataGetLength(data));
CFRelease(data);
}
CFRelease(str);
}
CFAssert1(str && data, __kCFLogAssertion, "%s(): Error writing plist", __PRETTY_FUNCTION__);
}
}
// Append CFString
//
static void _plistAppendString(CFMutableDataRef mData, CFStringRef str) {
const UniChar *chars;
const char *cStr;
CFDataRef data;
if ((chars = CFStringGetCharactersPtr(str))) {
_plistAppendCharacters(mData, chars, CFStringGetLength(str));
} else if ((cStr = CFStringGetCStringPtr(str, kCFStringEncodingASCII)) || (cStr = CFStringGetCStringPtr(str, kCFStringEncodingUTF8))) {
_plistAppendUTF8CString(mData, cStr);
} else if ((data = CFStringCreateExternalRepresentation(kCFAllocatorSystemDefault, str, kCFStringEncodingUTF8, 0))) {
CFDataAppendBytes (mData, CFDataGetBytePtr(data), CFDataGetLength(data));
CFRelease(data);
} else {
CFAssert1(TRUE, __kCFLogAssertion, "%s(): Error in plist writing", __PRETTY_FUNCTION__);
}
}
// Append CFString-style format + arguments
//
static void _plistAppendFormat(CFMutableDataRef mData, CFStringRef format, ...) {
CFStringRef fStr;
va_list argList;
va_start(argList, format);
fStr = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, NULL, format, argList);
va_end(argList);
CFAssert1(fStr, __kCFLogAssertion, "%s(): Error writing plist", __PRETTY_FUNCTION__);
_plistAppendString(mData, fStr);
CFRelease(fStr);
}
static void _appendIndents(CFIndex numIndents, CFMutableDataRef str) {
#define NUMTABS 4
static const UniChar tabs[NUMTABS] = {'\t','\t','\t','\t'};
for (; numIndents > 0; numIndents -= NUMTABS) _plistAppendCharacters(str, tabs, (numIndents >= NUMTABS) ? NUMTABS : numIndents);
}
/* Append the escaped version of origStr to mStr.
*/
static void _appendEscapedString(CFStringRef origStr, CFMutableDataRef mStr) {
#define BUFSIZE 64
CFIndex i, length = CFStringGetLength(origStr);
CFIndex bufCnt = 0;
UniChar buf[BUFSIZE];
CFStringInlineBuffer inlineBuffer;
CFStringInitInlineBuffer(origStr, &inlineBuffer, CFRangeMake(0, length));
for (i = 0; i < length; i ++) {
UniChar ch = __CFStringGetCharacterFromInlineBufferQuick(&inlineBuffer, i);
if (CFStringIsSurrogateHighCharacter(ch) && (bufCnt + 2 >= BUFSIZE)) {
// flush the buffer first so we have room for a low/high pair and do not split them
_plistAppendCharacters(mStr, buf, bufCnt);
bufCnt = 0;
}
switch(ch) {
case '<':
if (bufCnt) _plistAppendCharacters(mStr, buf, bufCnt);
bufCnt = 0;
_plistAppendUTF8CString(mStr, "<");
break;
case '>':
if (bufCnt) _plistAppendCharacters(mStr, buf, bufCnt);
bufCnt = 0;
_plistAppendUTF8CString(mStr, ">");
break;
case '&':
if (bufCnt) _plistAppendCharacters(mStr, buf, bufCnt);
bufCnt = 0;
_plistAppendUTF8CString(mStr, "&");
break;
default:
buf[bufCnt++] = ch;
if (bufCnt == BUFSIZE) {
_plistAppendCharacters(mStr, buf, bufCnt);
bufCnt = 0;
}
break;
}
}
if (bufCnt) _plistAppendCharacters(mStr, buf, bufCnt);
}
/* Base-64 encoding/decoding */
/* The base-64 encoding packs three 8-bit bytes into four 7-bit ASCII
* characters. If the number of bytes in the original data isn't divisable
* by three, "=" characters are used to pad the encoded data. The complete
* set of characters used in base-64 are:
*
* 'A'..'Z' => 00..25
* 'a'..'z' => 26..51
* '0'..'9' => 52..61
* '+' => 62
* '/' => 63
* '=' => pad
*/
// Write the inputData to the mData using Base 64 encoding
static void _XMLPlistAppendDataUsingBase64(CFMutableDataRef mData, CFDataRef inputData, CFIndex indent) {
static const char __CFPLDataEncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#define MAXLINELEN 76
char buf[MAXLINELEN + 4 + 2]; // For the slop and carriage return and terminating NULL
const uint8_t *bytes = CFDataGetBytePtr(inputData);
CFIndex length = CFDataGetLength(inputData);
CFIndex i, pos;
const uint8_t *p;
if (indent > 8) indent = 8; // refuse to indent more than 64 characters
pos = 0; // position within buf
for (i = 0, p = bytes; i < length; i++, p++) {
/* 3 bytes are encoded as 4 */
switch (i % 3) {
case 0:
buf[pos++] = __CFPLDataEncodeTable [ ((p[0] >> 2) & 0x3f)];
break;
case 1:
buf[pos++] = __CFPLDataEncodeTable [ ((((p[-1] << 8) | p[0]) >> 4) & 0x3f)];
break;
case 2:
buf[pos++] = __CFPLDataEncodeTable [ ((((p[-1] << 8) | p[0]) >> 6) & 0x3f)];
buf[pos++] = __CFPLDataEncodeTable [ (p[0] & 0x3f)];
break;
}
/* Flush the line out every 76 (or fewer) chars --- indents count against the line length*/
if (pos >= MAXLINELEN - 8 * indent) {
buf[pos++] = '\n';
buf[pos++] = 0;
_appendIndents(indent, mData);
_plistAppendUTF8CString(mData, buf);
pos = 0;
}
}
switch (i % 3) {
case 0:
break;
case 1:
buf[pos++] = __CFPLDataEncodeTable [ ((p[-1] << 4) & 0x30)];
buf[pos++] = '=';
buf[pos++] = '=';
break;
case 2:
buf[pos++] = __CFPLDataEncodeTable [ ((p[-1] << 2) & 0x3c)];
buf[pos++] = '=';
break;
}
if (pos > 0) {
buf[pos++] = '\n';
buf[pos++] = 0;
_appendIndents(indent, mData);
_plistAppendUTF8CString(mData, buf);
}
}
extern CFStringRef __CFNumberCopyFormattingDescriptionAsFloat64(CFTypeRef cf);
static void _CFAppendXML0(CFTypeRef object, UInt32 indentation, CFMutableDataRef xmlString) {
UInt32 typeID = CFGetTypeID(object);
_appendIndents(indentation, xmlString);
if (typeID == _kCFRuntimeIDCFString) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[STRING_IX], STRING_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
_appendEscapedString((CFStringRef)object, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[STRING_IX], STRING_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _CFKeyedArchiverUIDGetTypeID()) {
// This is only used for the keyed archiver
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DICT_IX], DICT_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
_appendIndents(indentation+1, xmlString);
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[KEY_IX], KEY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
_appendEscapedString(CFSTR("CF$UID"), xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[KEY_IX], KEY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
_appendIndents(indentation + 1, xmlString);
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[INTEGER_IX], INTEGER_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
uint64_t v = _CFKeyedArchiverUIDGetValue((CFKeyedArchiverUIDRef)object);
CFNumberRef num = CFNumberCreate(kCFAllocatorSystemDefault, kCFNumberSInt64Type, &v);
_plistAppendFormat(xmlString, CFSTR("%@"), num);
CFRelease(num);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[INTEGER_IX], INTEGER_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
_appendIndents(indentation, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DICT_IX], DICT_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _kCFRuntimeIDCFArray) {
UInt32 i, count = CFArrayGetCount((CFArrayRef)object);
if (count == 0) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[ARRAY_IX], ARRAY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, "/>\n");
return;
}
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[ARRAY_IX], ARRAY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
for (i = 0; i < count; i ++) {
_CFAppendXML0(CFArrayGetValueAtIndex((CFArrayRef)object, i), indentation+1, xmlString);
}
_appendIndents(indentation, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[ARRAY_IX], ARRAY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _kCFRuntimeIDCFDictionary) {
UInt32 i, count = CFDictionaryGetCount((CFDictionaryRef)object);
CFMutableArrayRef keyArray;
if (count == 0) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DICT_IX], DICT_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, "/>\n");
return;
}
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DICT_IX], DICT_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
new_cftype_array(keys, count);
CFDictionaryGetKeysAndValues((CFDictionaryRef)object, keys, NULL);
keyArray = CFArrayCreateMutable(kCFAllocatorSystemDefault, count, &kCFTypeArrayCallBacks);
CFArrayReplaceValues(keyArray, CFRangeMake(0, 0), keys, count);
CFArraySortValues(keyArray, CFRangeMake(0, count), (CFComparatorFunction)CFStringCompare, NULL);
CFArrayGetValues(keyArray, CFRangeMake(0, count), keys);
CFRelease(keyArray);
for (i = 0; i < count; i ++) {
CFTypeRef key = keys[i];
_appendIndents(indentation+1, xmlString);
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[KEY_IX], KEY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
_appendEscapedString((CFStringRef)key, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[KEY_IX], KEY_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
_CFAppendXML0(CFDictionaryGetValue((CFDictionaryRef)object, key), indentation+1, xmlString);
}
free_cftype_array(keys);
_appendIndents(indentation, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DICT_IX], DICT_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _kCFRuntimeIDCFData) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DATA_IX], DATA_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
_XMLPlistAppendDataUsingBase64(xmlString, (CFDataRef)object, indentation);
_appendIndents(indentation, xmlString);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DATA_IX], DATA_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _kCFRuntimeIDCFDate) {
// YYYY '-' MM '-' DD 'T' hh ':' mm ':' ss 'Z'
int32_t y = 0, M = 0, d = 0, H = 0, m = 0, s = 0;
CFAbsoluteTime at = CFDateGetAbsoluteTime((CFDateRef)object);
#if 0
// Alternative to the CFAbsoluteTimeGetGregorianDate() code which works well
struct timeval tv;
struct tm mine;
tv.tv_sec = floor(at + kCFAbsoluteTimeIntervalSince1970);
gmtime_r(&tv.tv_sec, &mine);
y = mine.tm_year + 1900;
M = mine.tm_mon + 1;
d = mine.tm_mday;
H = mine.tm_hour;
m = mine.tm_min;
s = mine.tm_sec;
#endif
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
CFGregorianDate date = CFAbsoluteTimeGetGregorianDate(at, NULL);
#pragma GCC diagnostic pop
#if 0
if (date.year != y || date.month != M || date.day != d || date.hour != H || date.minute != m || (int32_t)date.second != s) {
CFLog(4, CFSTR("DATE ERROR {%d, %d, %d, %d, %d, %d} != {%d, %d, %d, %d, %d, %d}\n"), (int)date.year, (int)date.month, (int)date.day, (int)date.hour, (int)date.minute, (int32_t)date.second, y, M, d, H, m, s);
}
#endif
y = date.year;
M = date.month;
d = date.day;
H = date.hour;
m = date.minute;
s = (int32_t)date.second;
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DATE_IX], DATE_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
_plistAppendFormat(xmlString, CFSTR("%04d-%02d-%02dT%02d:%02d:%02dZ"), y, M, d, H, m, s);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[DATE_IX], DATE_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else if (typeID == _kCFRuntimeIDCFNumber) {
if (CFNumberIsFloatType((CFNumberRef)object)) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[REAL_IX], REAL_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
CFStringRef s = __CFNumberCopyFormattingDescriptionAsFloat64(object);
_plistAppendString(xmlString, s);
CFRelease(s);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[REAL_IX], REAL_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
} else {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[INTEGER_IX], INTEGER_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">");
_plistAppendFormat(xmlString, CFSTR("%@"), object);
_plistAppendUTF8CString(xmlString, "</");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[INTEGER_IX], INTEGER_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, ">\n");
}
} else if (typeID == _kCFRuntimeIDCFBoolean) {
if (CFBooleanGetValue((CFBooleanRef)object)) {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[TRUE_IX], TRUE_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, "/>\n");
} else {
_plistAppendUTF8CString(xmlString, "<");
_plistAppendCharacters(xmlString, CFXMLPlistTagsUnicode[FALSE_IX], FALSE_TAG_LENGTH);
_plistAppendUTF8CString(xmlString, "/>\n");
}
}
}
static void _CFGenerateXMLPropertyListToData(CFMutableDataRef xml, CFTypeRef propertyList) {
_plistAppendUTF8CString(xml, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE ");
_plistAppendCharacters(xml, CFXMLPlistTagsUnicode[PLIST_IX], PLIST_TAG_LENGTH);
_plistAppendUTF8CString(xml, " PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<");
_plistAppendCharacters(xml, CFXMLPlistTagsUnicode[PLIST_IX], PLIST_TAG_LENGTH);
_plistAppendUTF8CString(xml, " version=\"1.0\">\n");
_CFAppendXML0(propertyList, 0, xml);
_plistAppendUTF8CString(xml, "</");
_plistAppendCharacters(xml, CFXMLPlistTagsUnicode[PLIST_IX], PLIST_TAG_LENGTH);
_plistAppendUTF8CString(xml, ">\n");
}
// ========================================================================
#pragma mark -
#pragma mark Exported Creation Functions
CFDataRef _CFPropertyListCreateXMLData(CFAllocatorRef allocator, CFPropertyListRef propertyList, Boolean checkValidPlist) {
CFMutableDataRef xml;
CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): Cannot be called with a NULL property list", __PRETTY_FUNCTION__);
if (checkValidPlist && !CFPropertyListIsValid(propertyList, kCFPropertyListXMLFormat_v1_0)) {
__CFAssertIsPList(propertyList);
return NULL;
}
xml = CFDataCreateMutable(allocator, 0);
_CFGenerateXMLPropertyListToData(xml, propertyList);
return xml;
}
CFDataRef CFPropertyListCreateXMLData(CFAllocatorRef allocator, CFPropertyListRef propertyList) {
return _CFPropertyListCreateXMLData(allocator, propertyList, true);
}
CF_EXPORT CFDataRef _CFPropertyListCreateXMLDataWithExtras(CFAllocatorRef allocator, CFPropertyListRef propertyList) {
return _CFPropertyListCreateXMLData(allocator, propertyList, false);
}
Boolean CFPropertyListIsValid(CFPropertyListRef plist, CFPropertyListFormat format) {
// The first is only there for testing when building with `-DDEBUG`
// See the actual implementation in the `else` below
CFAssert1(plist != NULL, __kCFLogAssertion, "%s(): NULL is not a property list", __PRETTY_FUNCTION__);
___CFPropertyListIsValidContext context = {
.answer = true,
.format = format,
.error = NULL,
.referenceBag = NULL
};
return __CFPropertyListIsValidAux(plist, true, &context);
}
// ========================================================================
#pragma mark -
#pragma mark Reading Plists
//
// ------------------------- Reading plists ------------------
//
static Boolean parseXMLElement(_CFXMLPlistParseInfo * _Nonnull pInfo, Boolean * _Nullable isKey, CFTypeRef * _Nullable out, size_t curDepth);
// warning: doesn't have a good idea of Unicode line separators
static UInt32 lineNumber(_CFXMLPlistParseInfo *pInfo) {
const char *p = pInfo->begin;
UInt32 count = 1;
while (p < pInfo->end && p < pInfo->curr) {
if (*p == '\r') {
count ++;
if (p + 1 < pInfo->end && p + 1 < pInfo->curr && *(p + 1) == '\n') {
p ++;
}
} else if (*p == '\n') {
count ++;
}
p ++;
}
return count;
}
// warning: doesn't have a good idea of Unicode white space
CF_INLINE void skipWhitespace(_CFXMLPlistParseInfo *pInfo) {
while (pInfo->curr < pInfo->end) {
switch (*(pInfo->curr)) {
case ' ':
case '\t':
case '\n':
case '\r':
pInfo->curr ++;
continue;
default:
return;
}
}
}
/* All of these advance to the end of the given construct and return a pointer to the first character beyond the construct. If the construct doesn't parse properly, NULL is returned. */
// pInfo should be just past "<!--"
static void skipXMLComment(_CFXMLPlistParseInfo *pInfo) {
const char *p = pInfo->curr;
const char *end = pInfo->end - 3; // Need at least 3 characters to compare against
while (p < end) {
if (*p == '-' && *(p+1) == '-' && *(p+2) == '>') {
pInfo->curr = p+3;
return;
}
p ++;
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unterminated comment started on line %d"), lineNumber(pInfo));
}
// pInfo should be set to the first character after "<?"
static void skipXMLProcessingInstruction(_CFXMLPlistParseInfo *pInfo) {
const char *begin = pInfo->curr, *end = pInfo->end - 2; // Looking for "?>" so we need at least 2 characters
while (pInfo->curr < end) {
if (*(pInfo->curr) == '?' && *(pInfo->curr+1) == '>') {
pInfo->curr += 2;
return;
}
pInfo->curr ++;
}
pInfo->curr = begin;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF while parsing the processing instruction begun on line %d"), lineNumber(pInfo));
}
// first character should be immediately after the "<!"
static void skipDTD(_CFXMLPlistParseInfo *pInfo) {
// First pass "DOCTYPE"
if (pInfo->end - pInfo->curr < DOCTYPE_TAG_LENGTH || memcmp(pInfo->curr, CFXMLPlistTags[DOCTYPE_IX], DOCTYPE_TAG_LENGTH)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Malformed DTD on line %d"), lineNumber(pInfo));
return;
}
pInfo->curr += DOCTYPE_TAG_LENGTH;
skipWhitespace(pInfo);
// Look for either the beginning of a complex DTD or the end of the DOCTYPE structure
while (pInfo->curr < pInfo->end) {
char ch = *(pInfo->curr);
if (ch == '[') break; // inline DTD
if (ch == '>') { // End of the DTD
pInfo->curr ++;
return;
}
pInfo->curr ++;
}
if (pInfo->curr == pInfo->end) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF while parsing DTD"));
return;
}
if (pInfo->error) return;
skipWhitespace(pInfo);
if (pInfo->error) return;
if (pInfo->curr < pInfo->end) {
if (*(pInfo->curr) == '>') {
pInfo->curr ++;
} else {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c on line %d while parsing DTD"), *(pInfo->curr), lineNumber(pInfo));
}
} else {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF while parsing DTD"));
}
}
// content ::== (element | CharData | Reference | CDSect | PI | Comment)*
// In the context of a plist, CharData, Reference and CDSect are not legal (they all resolve to strings). Skipping whitespace, then, the next character should be '<'. From there, we figure out which of the three remaining cases we have (element, PI, or Comment).
static Boolean getContentObject(_CFXMLPlistParseInfo * _Nonnull pInfo, Boolean * _Nullable isKey, CFTypeRef * _Nullable out, size_t curDepth) {
if (curDepth > _CFPropertyListMaxRecursionDepth()) {
// Bail before we get so far into the stack that we run out of space.
//
// In bplist parsing we don't have the ability to set the error message
// descriptively like we do here, so in bplists we use an `os_log_fault`
// here we can just set `pInfo->error` see rdar://65835843
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Too many nested arrays or dictionaries, failing on line %d"), lineNumber(pInfo));
return false;
}
if (isKey) *isKey = false;
while (!pInfo->error && pInfo->curr < pInfo->end) {
skipWhitespace(pInfo);
if (pInfo->curr >= pInfo->end) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return false;
}
if (*(pInfo->curr) != '<') {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c on line %d while looking for open tag"), *(pInfo->curr), lineNumber(pInfo));
return false;
}
pInfo->curr ++;
if (pInfo->curr >= pInfo->end) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return false;
}
switch (*(pInfo->curr)) {
case '?':
// Processing instruction
skipXMLProcessingInstruction(pInfo);
break;
case '!':
// Could be a comment
if (pInfo->curr+2 >= pInfo->end) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return false;
}
if (*(pInfo->curr+1) == '-' && *(pInfo->curr+2) == '-') {
// skip `--` and set the cursor 1 past the two dashes
pInfo->curr += 3;
skipXMLComment(pInfo);
} else {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return false;
}
break;
case '/':
// Whoops! Looks like we got to the end tag for the element whose content we're parsing
pInfo->curr --; // Back off to the '<'
return false;
default:
// Should be an element
return parseXMLElement(pInfo, isKey, out, curDepth);
}
}
// Do not set the error string here; if it wasn't already set by one of the recursive parsing calls, the caller will quickly detect the failure (b/c pInfo->curr >= pInfo->end) and provide a more useful one of the form "end tag for <blah> not found"
return false;
}
static void parseCDSect_pl(_CFXMLPlistParseInfo *pInfo, CFMutableDataRef stringData) {
const char *end, *begin;
if (pInfo->end - pInfo->curr < CDSECT_TAG_LENGTH) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return;
}
if (memcmp(pInfo->curr, CFXMLPlistTags[CDSECT_IX], CDSECT_TAG_LENGTH)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered improper CDATA opening at line %d"), lineNumber(pInfo));
return;
}
pInfo->curr += CDSECT_TAG_LENGTH;
begin = pInfo->curr; // Marks the first character of the CDATA content
end = pInfo->end-2; // So we can safely look 2 characters beyond p
while (pInfo->curr < end) {
if (*(pInfo->curr) == ']' && *(pInfo->curr+1) == ']' && *(pInfo->curr+2) == '>') {
// Found the end!
CFDataAppendBytes(stringData, (const UInt8 *)begin, pInfo->curr-begin);
pInfo->curr += 3;
return;
}
pInfo->curr ++;
}
// Never found the end mark
pInfo->curr = begin;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not find end of CDATA started on line %d"), lineNumber(pInfo));
}
// Only legal references are {lt, gt, amp, apos, quote, #ddd, #xAAA}
static void parseEntityReference_pl(_CFXMLPlistParseInfo *pInfo, CFMutableDataRef stringData) {
int len;
pInfo->curr ++; // move past the '&';
len = pInfo->end - pInfo->curr; // how many bytes we can safely scan
if (len < 1) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return;
}
char ch;
switch (*(pInfo->curr)) {
case 'l': // "lt"
if (len >= 3 && *(pInfo->curr+1) == 't' && *(pInfo->curr+2) == ';') {
ch = '<';
pInfo->curr += 3;
break;
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown ampersand-escape sequence at line %d"), lineNumber(pInfo));
return;
case 'g': // "gt"
if (len >= 3 && *(pInfo->curr+1) == 't' && *(pInfo->curr+2) == ';') {
ch = '>';
pInfo->curr += 3;
break;
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown ampersand-escape sequence at line %d"), lineNumber(pInfo));
return;
case 'a': // "apos" or "amp"
if (len < 4) { // Not enough characters for either conversion
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return;
}
if (*(pInfo->curr+1) == 'm') {
// "amp"
if (*(pInfo->curr+2) == 'p' && *(pInfo->curr+3) == ';') {
ch = '&';
pInfo->curr += 4;
break;
}
} else if (*(pInfo->curr+1) == 'p') {
// "apos"
if (len > 4 && *(pInfo->curr+2) == 'o' && *(pInfo->curr+3) == 's' && *(pInfo->curr+4) == ';') {
ch = '\'';
pInfo->curr += 5;
break;
}
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown ampersand-escape sequence at line %d"), lineNumber(pInfo));
return;
case 'q': // "quote"
if (len >= 5 && *(pInfo->curr+1) == 'u' && *(pInfo->curr+2) == 'o' && *(pInfo->curr+3) == 't' && *(pInfo->curr+4) == ';') {
ch = '\"';
pInfo->curr += 5;
break;
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown ampersand-escape sequence at line %d"), lineNumber(pInfo));
return;
case '#':
{
uint32_t num = 0;
Boolean isHex = false;
if ( len < 4) { // Not enough characters to make it all fit! Need at least "&#d;"
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return;
}
pInfo->curr ++;
if (*(pInfo->curr) == 'x') {
isHex = true;
pInfo->curr ++;
}
int numberOfCharactersSoFar = 0;
while (pInfo->curr < pInfo->end) {
ch = *(pInfo->curr);
pInfo->curr ++;
numberOfCharactersSoFar++;
if (ch == ';') {
// The value in num always refers to the unicode code point. We'll have to convert since the calling function expects UTF8 data. Swap to BE always so we know what encoding to use.
num = CFSwapInt32HostToBig(num);
CFStringRef oneChar = CFStringCreateWithBytes(pInfo->allocator, (const uint8_t *)&num, sizeof(num), kCFStringEncodingUTF32BE, NO);
if (!oneChar) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unparseable Unicode sequence at line %d while parsing data (input did not result in a real string)"), lineNumber(pInfo));
return;
}
uint8_t tmpBuf[6]; // max of 6 bytes for UTF8
CFIndex tmpBufLength = 0;
CFStringGetBytes(oneChar, CFRangeMake(0, CFStringGetLength(oneChar)), kCFStringEncodingUTF8, 0, NO, tmpBuf, 6, &tmpBufLength);
CFDataAppendBytes(stringData, tmpBuf, tmpBufLength);
__CFPListRelease(oneChar, pInfo->allocator);
return;
} else if (numberOfCharactersSoFar > 8) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unparseable unicode sequence at line %d while parsing data (too large of a value for a Unicode sequence)"), lineNumber(pInfo));
return;
}
if (!isHex) num = num*10;
else num = num << 4;
if (ch <= '9' && ch >= '0') {
num += (ch - '0');
} else if (!isHex) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c at line %d while parsing data"), ch, lineNumber(pInfo));
return;
} else if (ch >= 'a' && ch <= 'f') {
num += 10 + (ch - 'a');
} else if (ch >= 'A' && ch <= 'F') {
num += 10 + (ch - 'A');
} else {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c at line %d while parsing data"), ch, lineNumber(pInfo));
return;
}
}
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
return;
}
default:
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown ampersand-escape sequence at line %d"), lineNumber(pInfo));
return;
}
CFDataAppendBytes(stringData, (const UInt8 *)&ch, 1);
}
static void _createStringMap(_CFXMLPlistParseInfo *pInfo) {
pInfo->stringTrie = CFBurstTrieCreate();
pInfo->stringCache = CFArrayCreateMutable(pInfo->allocator, 0, &kCFTypeArrayCallBacks);
}
static void _cleanupStringMap(_CFXMLPlistParseInfo *pInfo) {
CFBurstTrieRelease(pInfo->stringTrie);
CFRelease(pInfo->stringCache);
pInfo->stringTrie = NULL;
pInfo->stringCache = NULL;
}
static CFStringRef _createUniqueStringWithUTF8Bytes(_CFXMLPlistParseInfo *pInfo, const char *base, CFIndex length) {
if (length == 0) return (CFStringRef)CFRetain(CFSTR(""));
CFStringRef result = NULL;
uint32_t payload = 0;
Boolean uniqued = CFBurstTrieContainsUTF8String(pInfo->stringTrie, (UInt8 *)base, length, &payload);
if (uniqued && payload > 0) {
// The index is at payload - 1 (see below).
result = (CFStringRef)CFArrayGetValueAtIndex(pInfo->stringCache, (CFIndex)payload - 1);
CFRetain(result);
} else {
result = CFStringCreateWithBytes(pInfo->allocator, (const UInt8 *)base, length, kCFStringEncodingUTF8, NO);
if (!result) return NULL;
// Payload must be >0, so the actual index of the value is at payload - 1
// We also get add to the array after we make sure that CFBurstTrieAddUTF8String succeeds (it can fail, if the string is too large, for example)
payload = CFArrayGetCount(pInfo->stringCache) + 1;
Boolean didAddToBurstTrie = CFBurstTrieAddUTF8String(pInfo->stringTrie, (UInt8 *)base, length, payload);
if (didAddToBurstTrie) {
CFArrayAppendValue(pInfo->stringCache, result);
}
}
return result;
}
// String could be comprised of characters, CDSects, or references to one of the "well-known" entities ('<', '>', '&', ''', '"')
static Boolean parseStringTag(_CFXMLPlistParseInfo *pInfo, CFStringRef *out) {
const char *mark = pInfo->curr;
CFMutableDataRef stringData = NULL;
while (!pInfo->error && pInfo->curr < pInfo->end) {
char ch = *(pInfo->curr);
if (ch == '<') {
if (pInfo->curr + 1 >= pInfo->end) break;
// Could be a CDSect; could be the end of the string
if (*(pInfo->curr+1) != '!') break; // End of the string
if (!stringData) stringData = CFDataCreateMutable(pInfo->allocator, 0);
CFDataAppendBytes(stringData, (const UInt8 *)mark, pInfo->curr - mark);
parseCDSect_pl(pInfo, stringData); // TODO: move to return boolean
mark = pInfo->curr;
} else if (ch == '&') {
if (!stringData) stringData = CFDataCreateMutable(pInfo->allocator, 0);
CFDataAppendBytes(stringData, (const UInt8 *)mark, pInfo->curr - mark);
parseEntityReference_pl(pInfo, stringData); // TODO: move to return boolean
mark = pInfo->curr;
} else {
pInfo->curr ++;
}
}
if (pInfo->error) {
__CFPListRelease(stringData, pInfo->allocator);
return false;
}
if (!stringData) {
if (pInfo->skip) {
*out = NULL;
} else {
if (pInfo->mutabilityOption != kCFPropertyListMutableContainersAndLeaves) {
CFStringRef s = _createUniqueStringWithUTF8Bytes(pInfo, mark, pInfo->curr - mark);
if (!s) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to convert string to correct encoding"));
return false;
}
*out = s;
} else {
CFStringRef s = CFStringCreateWithBytes(pInfo->allocator, (const UInt8 *)mark, pInfo->curr - mark, kCFStringEncodingUTF8, NO);
if (!s) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to convert string to correct encoding"));
return false;
}
*out = CFStringCreateMutableCopy(pInfo->allocator, 0, s);
__CFPListRelease(s, pInfo->allocator);
}
}
return true;
} else {
if (pInfo->skip) {
*out = NULL;
} else {
CFDataAppendBytes(stringData, (const UInt8 *)mark, pInfo->curr - mark);
if (pInfo->mutabilityOption != kCFPropertyListMutableContainersAndLeaves) {
CFStringRef s = _createUniqueStringWithUTF8Bytes(pInfo, (const char *)CFDataGetBytePtr(stringData), CFDataGetLength(stringData));
if (!s) {
CFRelease(stringData);
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to convert string to correct encoding"));
return false;
}
*out = s;
} else {
CFStringRef s = CFStringCreateWithBytes(pInfo->allocator, (const UInt8 *)CFDataGetBytePtr(stringData), CFDataGetLength(stringData), kCFStringEncodingUTF8, NO);
if (!s) {
CFRelease(stringData);
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to convert string to correct encoding"));
return false;
}
*out = CFStringCreateMutableCopy(pInfo->allocator, 0, s);
__CFPListRelease(s, pInfo->allocator);
}
}
__CFPListRelease(stringData, pInfo->allocator);
return true;
}
}
static Boolean checkForCloseTag(_CFXMLPlistParseInfo *pInfo, const char *tag, CFIndex tagLen) {
if (pInfo->end - pInfo->curr < tagLen + 3) {
if (!pInfo->error) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
}
return false;
}
if (*(pInfo->curr) != '<' || *(++pInfo->curr) != '/') {
if (!pInfo->error) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c on line %d while looking for close tag"), *(pInfo->curr), lineNumber(pInfo));
}
return false;
}
pInfo->curr ++;
if (memcmp(pInfo->curr, tag, tagLen)) {
CFStringRef str = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (const UInt8 *)tag, tagLen, kCFStringEncodingUTF8, NO);
if (!pInfo->error) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Close tag on line %d does not match open tag %@"), lineNumber(pInfo), str);
}
CFRelease(str);
return false;
}
pInfo->curr += tagLen;
skipWhitespace(pInfo);
if (pInfo->curr == pInfo->end) {
if (!pInfo->error) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
}
return false;
}
if (*(pInfo->curr) != '>') {
if (!pInfo->error) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected character %c on line %d while looking for close tag"), *(pInfo->curr), lineNumber(pInfo));
}
return false;
}
pInfo->curr ++;
return true;
}
// pInfo should be set to the first content character of the <plist>
static Boolean parsePListTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out, size_t curDepth) {
CFTypeRef result = NULL;
if (!getContentObject(pInfo, NULL, &result, curDepth)) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty plist tag"));
return false;
}
const char *save = pInfo->curr; // Save this in case the next step fails
CFTypeRef tmp = NULL;
if (getContentObject(pInfo, NULL, &tmp, curDepth)) {
// Got an extra object
__CFPListRelease(tmp, pInfo->allocator);
__CFPListRelease(result, pInfo->allocator);
pInfo->curr = save;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected element at line %d (plist can only include one object)"), lineNumber(pInfo));
return false;
}
if (pInfo->error) {
// Parse failed catastrophically
__CFPListRelease(result, pInfo->allocator);
return false;
}
if (!checkForCloseTag(pInfo, CFXMLPlistTags[PLIST_IX], PLIST_TAG_LENGTH)) {
__CFPListRelease(result, pInfo->allocator);
return false;
}
*out = result;
return true;
}
static int allowImmutableCollections = -1;
static void checkImmutableCollections(void) {
allowImmutableCollections = (NULL == getenv("CFPropertyListAllowImmutableCollections")) ? 0 : 1;
}
// This converts the input value, a set of strings, into the form that's efficient for using during recursive decent parsing, a set of arrays
static CFSetRef createTopLevelKeypaths(CFAllocatorRef allocator, CFSetRef keyPaths) {
if (!keyPaths) return NULL;
CFIndex count = CFSetGetCount(keyPaths);
new_cftype_array(keyPathValues, count);
CFSetGetValues(keyPaths, keyPathValues);
CFMutableSetRef splitKeyPathSet = CFSetCreateMutable(allocator, count, &kCFTypeSetCallBacks);
for (CFIndex i = 0; i < count; i++) {
// Split each key path and add it to the split path set, which we will reference throughout parsing
CFArrayRef split = CFStringCreateArrayBySeparatingStrings(allocator, (CFStringRef)(keyPathValues[i]), CFSTR(":"));
CFSetAddValue(splitKeyPathSet, split);
__CFPListRelease(split, allocator);
}
free_cftype_array(keyPathValues);
return splitKeyPathSet;
}
// This splits up the keypaths into the ones relevant for this level (of array or dictionary), and the ones for the next level (of array or dictionary)
CF_PRIVATE void __CFPropertyListCreateSplitKeypaths(CFAllocatorRef allocator, CFSetRef currentKeys, CFSetRef *theseKeys, CFSetRef *nextKeys) {
if (!currentKeys) { *theseKeys = NULL; *nextKeys = NULL; return; }
CFIndex count = CFSetGetCount(currentKeys);
// For each array in the current key path set, grab the item at the start of the list and put it into theseKeys. The rest of the array goes into nextKeys.
CFMutableSetRef outTheseKeys = NULL;
CFMutableSetRef outNextKeys = NULL;
new_cftype_array(currentKeyPaths, count);
CFSetGetValues(currentKeys, currentKeyPaths);
for (CFIndex i = 0; i < count; i++) {
CFArrayRef oneKeyPath = (CFArrayRef)currentKeyPaths[i];
CFIndex keyPathCount = CFArrayGetCount(oneKeyPath);
if (keyPathCount > 0) {
if (!outTheseKeys) outTheseKeys = CFSetCreateMutable(allocator, 0, &kCFTypeSetCallBacks);
CFSetAddValue(outTheseKeys, CFArrayGetValueAtIndex(oneKeyPath, 0));
}
if (keyPathCount > 1) {
if (!outNextKeys) outNextKeys = CFSetCreateMutable(allocator, 0, &kCFTypeSetCallBacks);
// Create an array with values from 1 - end of list
new_cftype_array(restOfKeys, keyPathCount - 1);
CFArrayGetValues(oneKeyPath, CFRangeMake(1, CFArrayGetCount(oneKeyPath) - 1), restOfKeys);
CFArrayRef newNextKeys = CFArrayCreate(allocator, restOfKeys, CFArrayGetCount(oneKeyPath) - 1, &kCFTypeArrayCallBacks);
CFSetAddValue(outNextKeys, newNextKeys);
__CFPListRelease(newNextKeys, allocator);
free_cftype_array(restOfKeys);
}
}
free_cftype_array(currentKeyPaths);
*theseKeys = outTheseKeys;
*nextKeys = outNextKeys;
}
static Boolean parseArrayTag(_CFXMLPlistParseInfo * _Nonnull pInfo, CFTypeRef * _Nullable out, size_t curDepth) {
CFTypeRef tmp = NULL;
if (pInfo->skip) {
Boolean result = getContentObject(pInfo, NULL, &tmp, curDepth);
while (result) {
if (tmp) {
// Shouldn't happen (if skipping, all content values should be null), but just in case
__CFPListRelease(tmp, pInfo->allocator);
}
result = getContentObject(pInfo, NULL, &tmp, curDepth);
}
if (pInfo->error) {
// getContentObject encountered a parse error
return false;
}
if (!checkForCloseTag(pInfo, CFXMLPlistTags[ARRAY_IX], ARRAY_TAG_LENGTH)) {
return false;
} else {
*out = NULL;
return true;
}
}
CFMutableArrayRef array = CFArrayCreateMutable(pInfo->allocator, 0, &kCFTypeArrayCallBacks);
Boolean result;
CFIndex count = 0;
CFSetRef oldKeyPaths = pInfo->keyPaths;
CFSetRef newKeyPaths, keys;
__CFPropertyListCreateSplitKeypaths(pInfo->allocator, pInfo->keyPaths, &keys, &newKeyPaths);
if (keys) {
CFStringRef countString = CFStringCreateWithFormat(pInfo->allocator, NULL, CFSTR("%ld"), count);
if (!CFSetContainsValue(keys, countString)) pInfo->skip = true;
__CFPListRelease(countString, pInfo->allocator);
count++;
pInfo->keyPaths = newKeyPaths;
}
result = getContentObject(pInfo, NULL, &tmp, curDepth);
if (keys) {
pInfo->keyPaths = oldKeyPaths;
pInfo->skip = false;
}
while (result) {
if (tmp) {
CFArrayAppendValue(array, tmp);
__CFPListRelease(tmp, pInfo->allocator);
}
if (keys) {
// prep for getting next object
CFStringRef countString = CFStringCreateWithFormat(pInfo->allocator, NULL, CFSTR("%ld"), count);
if (!CFSetContainsValue(keys, countString)) pInfo->skip = true;
__CFPListRelease(countString, pInfo->allocator);
count++;
pInfo->keyPaths = newKeyPaths;
}
result = getContentObject(pInfo, NULL, &tmp, curDepth);
if (keys) {
// reset after getting object
pInfo->keyPaths = oldKeyPaths;
pInfo->skip = false;
}
}
__CFPListRelease(newKeyPaths, pInfo->allocator);
__CFPListRelease(keys, pInfo->allocator);
if (pInfo->error) { // getContentObject encountered a parse error
__CFPListRelease(array, pInfo->allocator);
return false;
}
if (!checkForCloseTag(pInfo, CFXMLPlistTags[ARRAY_IX], ARRAY_TAG_LENGTH)) {
__CFPListRelease(array, pInfo->allocator);
return false;
}
if (-1 == allowImmutableCollections) {
checkImmutableCollections();
}
if (1 == allowImmutableCollections) {
if (pInfo->mutabilityOption == kCFPropertyListImmutable) {
CFArrayRef newArray = CFArrayCreateCopy(pInfo->allocator, array);
__CFPListRelease(array, pInfo->allocator);
array = (CFMutableArrayRef)newArray;
}
}
*out = array;
return true;
}
static Boolean parseDictTag(_CFXMLPlistParseInfo * _Nonnull pInfo, CFTypeRef * _Nullable out, size_t curDepth) {
Boolean gotKey;
Boolean result;
CFTypeRef key = NULL, value = NULL;
if (pInfo->skip) {
result = getContentObject(pInfo, &gotKey, &key, curDepth);
while (result) {
if (!gotKey) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Found non-key inside <dict> at line %d"), lineNumber(pInfo));
return false;
}
result = getContentObject(pInfo, NULL, &value, curDepth);
if (!result) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Value missing for key inside <dict> at line %d"), lineNumber(pInfo));
return false;
}
// key and value should be null, but we'll release just in case here
__CFPListRelease(key, pInfo->allocator);
key = NULL;
__CFPListRelease(value, pInfo->allocator);
value = NULL;
result = getContentObject(pInfo, &gotKey, &key, curDepth);
}
if (checkForCloseTag(pInfo, CFXMLPlistTags[DICT_IX], DICT_TAG_LENGTH)) {
*out = NULL;
return true;
} else {
return false;
}
}
CFSetRef oldKeyPaths = pInfo->keyPaths;
CFSetRef nextKeyPaths, theseKeyPaths;
__CFPropertyListCreateSplitKeypaths(pInfo->allocator, pInfo->keyPaths, &theseKeyPaths, &nextKeyPaths);
CFMutableDictionaryRef dict = NULL;
result = getContentObject(pInfo, &gotKey, &key, curDepth);
while (result && key) {
if (!gotKey) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Found non-key inside <dict> at line %d"), lineNumber(pInfo));
__CFPListRelease(key, pInfo->allocator);
__CFPListRelease(nextKeyPaths, pInfo->allocator);
__CFPListRelease(theseKeyPaths, pInfo->allocator);
__CFPListRelease(dict, pInfo->allocator);
return false;
}
if (theseKeyPaths) {
if (!CFSetContainsValue(theseKeyPaths, key)) pInfo->skip = true;
pInfo->keyPaths = nextKeyPaths;
}
result = getContentObject(pInfo, NULL, &value, curDepth);
if (theseKeyPaths) {
pInfo->keyPaths = oldKeyPaths;
pInfo->skip = false;
}
if (!result) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Value missing for key inside <dict> at line %d"), lineNumber(pInfo));
__CFPListRelease(key, pInfo->allocator);
__CFPListRelease(nextKeyPaths, pInfo->allocator);
__CFPListRelease(theseKeyPaths, pInfo->allocator);
__CFPListRelease(dict, pInfo->allocator);
return false;
}
if (key && value) {
if (NULL == dict) {
dict = CFDictionaryCreateMutable(pInfo->allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
_CFDictionarySetCapacity(dict, 10);
}
CFDictionarySetValue(dict, key, value);
}
__CFPListRelease(key, pInfo->allocator);
key = NULL;
__CFPListRelease(value, pInfo->allocator);
value = NULL;
result = getContentObject(pInfo, &gotKey, &key, curDepth);
}
__CFPListRelease(nextKeyPaths, pInfo->allocator);
__CFPListRelease(theseKeyPaths, pInfo->allocator);
if (pInfo->error) { // getContentObject encountered a parse error
__CFPListRelease(dict, pInfo->allocator);
return false;
}
if (checkForCloseTag(pInfo, CFXMLPlistTags[DICT_IX], DICT_TAG_LENGTH)) {
if (NULL == dict) {
if (pInfo->mutabilityOption == kCFPropertyListImmutable) {
dict = (CFMutableDictionaryRef)CFDictionaryCreate(pInfo->allocator, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
} else {
dict = CFDictionaryCreateMutable(pInfo->allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
} else {
CFIndex cnt = CFDictionaryGetCount(dict);
if (1 == cnt) {
CFTypeRef val = CFDictionaryGetValue(dict, CFSTR("CF$UID"));
if (val && CFGetTypeID(val) == _kCFRuntimeIDCFNumber) {
CFTypeRef uid;
uint32_t v;
CFNumberGetValue((CFNumberRef)val, kCFNumberSInt32Type, &v);
uid = (CFTypeRef)_CFKeyedArchiverUIDCreate(pInfo->allocator, v);
__CFPListRelease(dict, pInfo->allocator);
*out = uid;
return true;
}
}
if (-1 == allowImmutableCollections) checkImmutableCollections();
if (1 == allowImmutableCollections) {
if (pInfo->mutabilityOption == kCFPropertyListImmutable) {
CFDictionaryRef newDict = CFDictionaryCreateCopy(pInfo->allocator, dict);
__CFPListRelease(dict, pInfo->allocator);
dict = (CFMutableDictionaryRef)newDict;
}
}
}
*out = dict;
return true;
}
if (dict) __CFPListRelease(dict, pInfo->allocator);
return false;
}
static Boolean parseDataTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) {
const char *base = pInfo->curr;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wgnu-folding-constant"
static const unsigned char dataDecodeTableSize = 128;
static const signed char dataDecodeTable[dataDecodeTableSize] = {
/* 000 */ -1, -1, -1, -1, -1, -1, -1, -1,
/* 010 */ -1, -1, -1, -1, -1, -1, -1, -1,
/* 020 */ -1, -1, -1, -1, -1, -1, -1, -1,
/* 030 */ -1, -1, -1, -1, -1, -1, -1, -1,
/* ' ' */ -1, -1, -1, -1, -1, -1, -1, -1,
/* '(' */ -1, -1, -1, 62, -1, -1, -1, 63,
/* '0' */ 52, 53, 54, 55, 56, 57, 58, 59,
/* '8' */ 60, 61, -1, -1, -1, 0, -1, -1,
/* '@' */ -1, 0, 1, 2, 3, 4, 5, 6,
/* 'H' */ 7, 8, 9, 10, 11, 12, 13, 14,
/* 'P' */ 15, 16, 17, 18, 19, 20, 21, 22,
/* 'X' */ 23, 24, 25, -1, -1, -1, -1, -1,
/* '`' */ -1, 26, 27, 28, 29, 30, 31, 32,
/* 'h' */ 33, 34, 35, 36, 37, 38, 39, 40,
/* 'p' */ 41, 42, 43, 44, 45, 46, 47, 48,
/* 'x' */ 49, 50, 51, -1, -1, -1, -1, -1
};
#pragma GCC diagnostic pop
int tmpbufpos = 0;
int tmpbuflen = 256;
uint8_t *tmpbuf = pInfo->skip ? NULL : (uint8_t *)CFAllocatorAllocate(pInfo->allocator, tmpbuflen, 0);
int numeq = 0;
int acc = 0;
int cntr = 0;
for (; pInfo->curr < pInfo->end; pInfo->curr++) {
unsigned char c = *(pInfo->curr);
if (c == '<') {
break;
}
if ('=' == c) {
numeq++;
} else if (!isspace(c)) {
numeq = 0;
}
if (c >= dataDecodeTableSize) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not interpret <data> on line %d (invalid character 0x%hhX)"), lineNumber(pInfo), c);
if (tmpbuf) { CFAllocatorDeallocate(pInfo->allocator, tmpbuf); }
return false;
}
if (dataDecodeTable[c] < 0)
continue;
cntr++;
acc <<= 6;
acc += dataDecodeTable[c];
if (!pInfo->skip && 0 == (cntr & 0x3)) {
if (tmpbuflen <= tmpbufpos + 2) {
if (tmpbuflen < 256 * 1024) {
tmpbuflen *= 4;
} else if (tmpbuflen < 16 * 1024 * 1024) {
tmpbuflen *= 2;
} else {
// once in this stage, this will be really slow
// and really potentially fragment memory
tmpbuflen += 256 * 1024;
}
tmpbuf = __CFSafelyReallocateWithAllocator(pInfo->allocator, tmpbuf, tmpbuflen, 0, NULL);
}
tmpbuf[tmpbufpos++] = (acc >> 16) & 0xff;
if (numeq < 2) tmpbuf[tmpbufpos++] = (acc >> 8) & 0xff;
if (numeq < 1) tmpbuf[tmpbufpos++] = acc & 0xff;
}
}
CFDataRef result = NULL;
if (!pInfo->skip) {
if (pInfo->mutabilityOption == kCFPropertyListMutableContainersAndLeaves) {
result = (CFDataRef)CFDataCreateMutable(pInfo->allocator, 0);
CFDataAppendBytes((CFMutableDataRef)result, tmpbuf, tmpbufpos);
CFAllocatorDeallocate(pInfo->allocator, tmpbuf);
} else {
result = CFDataCreateWithBytesNoCopy(pInfo->allocator, tmpbuf, tmpbufpos, pInfo->allocator);
}
if (!result) {
pInfo->curr = base;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not interpret <data> at line %d (should be base64-encoded)"), lineNumber(pInfo));
return false;
}
}
if (checkForCloseTag(pInfo, CFXMLPlistTags[DATA_IX], DATA_TAG_LENGTH)) {
*out = result;
return true;
} else {
__CFPListRelease(result, pInfo->allocator);
return false;
}
}
CF_INLINE Boolean read2DigitNumber(_CFXMLPlistParseInfo *pInfo, int32_t *result) {
char ch1, ch2;
if (pInfo->curr + 2 >= pInfo->end) {
return false;
}
ch1 = *pInfo->curr;
ch2 = *(pInfo->curr + 1);
pInfo->curr += 2;
if (!isdigit(ch1) || !isdigit(ch2)) {
return false;
}
*result = (ch1 - '0')*10 + (ch2 - '0');
return true;
}
// YYYY '-' MM '-' DD 'T' hh ':' mm ':' ss 'Z'
static Boolean parseDateTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) {
int32_t year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0;
int32_t num = 0;
Boolean badForm = false;
Boolean yearIsNegative = false;
if (pInfo->curr < pInfo->end && *pInfo->curr == '-') {
yearIsNegative = true;
pInfo->curr++;
}
while (pInfo->curr < pInfo->end && isdigit(*pInfo->curr)) {
year = 10*year + (*pInfo->curr) - '0';
pInfo->curr ++;
}
if (pInfo->curr >= pInfo->end || *pInfo->curr != '-') {
badForm = true;
} else {
pInfo->curr ++;
}
if (!badForm && read2DigitNumber(pInfo, &month) && pInfo->curr < pInfo->end && *pInfo->curr == '-') {
pInfo->curr ++;
} else {
badForm = true;
}
if (!badForm && read2DigitNumber(pInfo, &day) && pInfo->curr < pInfo->end && *pInfo->curr == 'T') {
pInfo->curr ++;
} else {
badForm = true;
}
if (!badForm && read2DigitNumber(pInfo, &hour) && pInfo->curr < pInfo->end && *pInfo->curr == ':') {
pInfo->curr ++;
} else {
badForm = true;
}
if (!badForm && read2DigitNumber(pInfo, &minute) && pInfo->curr < pInfo->end && *pInfo->curr == ':') {
pInfo->curr ++;
} else {
badForm = true;
}
if (!badForm && read2DigitNumber(pInfo, &num) && pInfo->curr < pInfo->end && *pInfo->curr == 'Z') {
second = num;
pInfo->curr ++;
} else {
badForm = true;
}
if (badForm || !checkForCloseTag(pInfo, CFXMLPlistTags[DATE_IX], DATE_TAG_LENGTH)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not interpret <date> at line %d"), lineNumber(pInfo));
return false;
}
CFAbsoluteTime at = 0.0;
#if 0
{ // alternative to CFGregorianDateGetAbsoluteTime() below; also, cheaper than CFCalendar would be;
// clearly not thread-safe with that environment variable having to be set;
// timegm() could be used instead of mktime(), on platforms which have it
struct tm mine;
mine.tm_year = (yearIsNegative ? -year : year) - 1900;
mine.tm_mon = month - 1;
mine.tm_mday = day;
mine.tm_hour = hour;
mine.tm_min = minute;
mine.tm_sec = second;
char *tz = getenv("TZ");
setenv("TZ", "", 1);
tzset();
at = mktime(tm) - kCFAbsoluteTimeIntervalSince1970;
if (tz) {
setenv("TZ", tz, 1);
} else {
unsetenv("TZ");
}
tzset();
}
#endif
// See <rdar://problem/5052483> Revisit the CFGregorianDate -> CFCalendar change in CFPropertyList.c
// for why we can't use CFCalendar
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated"
CFGregorianDate date = {yearIsNegative ? -year : year, month, day, hour, minute, second};
at = CFGregorianDateGetAbsoluteTime(date, NULL);
#pragma GCC diagnostic pop
if (pInfo->skip) {
*out = NULL;
} else {
*out = CFDateCreate(pInfo->allocator, at);
}
return true;
}
static Boolean parseRealTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) {
CFStringRef str = NULL;
if (!parseStringTag(pInfo, &str)) {
if (!pInfo->error) pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <real> on line %d"), lineNumber(pInfo));
return false;
}
CFNumberRef result = NULL;
if (!pInfo->skip) {
if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("nan"), kCFCompareCaseInsensitive)) result = kCFNumberNaN;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("+infinity"), kCFCompareCaseInsensitive)) result = kCFNumberPositiveInfinity;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("-infinity"), kCFCompareCaseInsensitive)) result = kCFNumberNegativeInfinity;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("infinity"), kCFCompareCaseInsensitive)) result = kCFNumberPositiveInfinity;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("-inf"), kCFCompareCaseInsensitive)) result = kCFNumberNegativeInfinity;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("inf"), kCFCompareCaseInsensitive)) result = kCFNumberPositiveInfinity;
else if (kCFCompareEqualTo == CFStringCompare(str, CFSTR("+inf"), kCFCompareCaseInsensitive)) result = kCFNumberPositiveInfinity;
if (result) {
CFRetain(result);
} else {
CFIndex len = CFStringGetLength(str);
CFStringInlineBuffer buf;
CFStringInitInlineBuffer(str, &buf, CFRangeMake(0, len));
SInt32 idx = 0;
double val;
if (!__CFStringScanDouble(&buf, NULL, &idx, &val) || idx != len) {
__CFPListRelease(str, pInfo->allocator);
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered misformatted real on line %d"), lineNumber(pInfo));
return false;
}
result = CFNumberCreate(pInfo->allocator, kCFNumberDoubleType, &val);
}
}
__CFPListRelease(str, pInfo->allocator);
if (checkForCloseTag(pInfo, CFXMLPlistTags[REAL_IX], REAL_TAG_LENGTH)) {
*out = result;
return true;
} else {
__CFPListRelease(result, pInfo->allocator);
return false;
}
}
#define GET_CH if (pInfo->curr == pInfo->end) { \
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Premature end of file after <integer> on line %d"), lineNumber(pInfo)); \
return false; \
} \
ch = *(pInfo->curr)
CF_INLINE bool isWhitespace(const char *utf8bytes, const char *end) {
// Converted UTF-16 isWhitespace from CFString to UTF8 bytes to get full list of UTF8 whitespace
/*
0020 -> <20>
0009 -> <09>
00a0 -> <c2a0>
1680 -> <e19a80>
2000 -> <e28080>
2001 -> <e28081>
2002 -> <e28082>
2003 -> <e28083>
2004 -> <e28084>
2005 -> <e28085>
2006 -> <e28086>
2007 -> <e28087>
2008 -> <e28088>
2009 -> <e28089>
200a -> <e2808a>
200b -> <e2808b>
202f -> <e280af>
205f -> <e2819f>
3000 -> <e38080>
*/
// Except we consider some additional values from 0x0 to 0x21 and 0x7E to 0xA1 as whitespace, for compatibility
unsigned char byte1 = *utf8bytes;
if (byte1 < 0x21 || (byte1 > 0x7E && byte1 < 0xA1)) return true;
if ((byte1 == 0xe2 || byte1 == 0xe3) && (end - utf8bytes >= 3)) {
// Check other possibilities in the 3-bytes range
unsigned char byte2 = *(utf8bytes + 1);
unsigned char byte3 = *(utf8bytes + 2);
if (byte1 == 0xe2 && byte2 == 0x80) {
return ((byte3 >= 80 && byte3 <= 0x8b) || byte3 == 0xaf);
} else if (byte1 == 0xe2 && byte2 == 0x81) {
return byte3 == 0x9f;
} else if (byte1 == 0xe3 && byte2 == 0x80 && byte3 == 0x80) {
return true;
}
}
return false;
}
static Boolean parseIntegerTag(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) {
bool isHex = false, isNeg = false, hadLeadingZero = false;
char ch = 0;
// decimal_constant S*(-|+)?S*[0-9]+ (S == space)
// hex_constant S*(-|+)?S*0[xX][0-9a-fA-F]+ (S == space)
while (pInfo->curr < pInfo->end && isWhitespace(pInfo->curr, pInfo->end)) pInfo->curr++;
GET_CH;
if ('<' == ch) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <integer> on line %d"), lineNumber(pInfo));
return false;
}
if ('-' == ch || '+' == ch) {
isNeg = ('-' == ch);
pInfo->curr++;
while (pInfo->curr < pInfo->end && isWhitespace(pInfo->curr, pInfo->end)) pInfo->curr++;
}
GET_CH;
if ('0' == ch) {
if (pInfo->curr + 1 < pInfo->end && ('x' == *(pInfo->curr + 1) || 'X' == *(pInfo->curr + 1))) {
pInfo->curr++;
isHex = true;
} else {
hadLeadingZero = true;
}
pInfo->curr++;
}
GET_CH;
while ('0' == ch) {
hadLeadingZero = true;
pInfo->curr++;
GET_CH;
}
if ('<' == ch && hadLeadingZero) { // nothing but zeros
int32_t val = 0;
if (!checkForCloseTag(pInfo, CFXMLPlistTags[INTEGER_IX], INTEGER_TAG_LENGTH)) {
// checkForCloseTag() sets error string
return false;
}
if (pInfo->skip) {
*out = NULL;
} else {
*out = CFNumberCreate(pInfo->allocator, kCFNumberSInt32Type, &val);
}
return true;
}
if ('<' == ch) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Incomplete <integer> on line %d"), lineNumber(pInfo));
return false;
}
uint64_t value = 0;
uint32_t multiplier = (isHex ? 16 : 10);
while ('<' != ch) {
uint32_t new_digit = 0;
switch (ch) {
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
new_digit = (ch - '0');
break;
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
new_digit = (ch - 'a' + 10);
break;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
new_digit = (ch - 'A' + 10);
break;
default: // other character
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unknown character '%c' (0x%x) in <integer> on line %d"), ch, ch, lineNumber(pInfo));
return false;
}
if (!isHex && new_digit > 9) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Hex digit in non-hex <integer> on line %d"), lineNumber(pInfo));
return false;
}
if (UINT64_MAX / multiplier < value) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Integer overflow in <integer> on line %d"), lineNumber(pInfo));
return false;
}
value = multiplier * value;
if (UINT64_MAX - new_digit < value) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Integer overflow in <integer> on line %d"), lineNumber(pInfo));
return false;
}
value = value + new_digit;
if (isNeg && (uint64_t)INT64_MAX + 1 < value) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Integer underflow in <integer> on line %d"), lineNumber(pInfo));
return false;
}
pInfo->curr++;
GET_CH;
}
if (!checkForCloseTag(pInfo, CFXMLPlistTags[INTEGER_IX], INTEGER_TAG_LENGTH)) {
// checkForCloseTag() sets error string
return false;
}
if (pInfo->skip) {
*out = NULL;
} else {
if (isNeg || value <= INT64_MAX) {
int64_t v = value;
if (isNeg) v = -v; // no-op if INT64_MIN
*out = CFNumberCreate(pInfo->allocator, kCFNumberSInt64Type, &v);
} else {
CFSInt128Struct val;
val.high = 0;
val.low = value;
*out = CFNumberCreate(pInfo->allocator, kCFNumberSInt128Type, &val);
}
}
return true;
}
#undef GET_CH
// Returned object is retained; caller must free. pInfo->curr expected to point to the first character after the '<'
static Boolean parseXMLElement(_CFXMLPlistParseInfo * _Nonnull pInfo, Boolean * _Nullable isKey, CFTypeRef * _Nullable out, size_t curDepth) {
const char *marker = pInfo->curr;
int markerLength = -1;
Boolean isEmpty;
int markerIx = -1;
if (isKey) *isKey = false;
while (pInfo->curr < pInfo->end) {
char ch = *(pInfo->curr);
if (ch == ' ' || ch == '\t' || ch == '\n' || ch =='\r') {
if (markerLength == -1) markerLength = pInfo->curr - marker;
} else if (ch == '>') {
break;
}
pInfo->curr ++;
}
if (pInfo->curr >= pInfo->end) {
return false;
}
isEmpty = (*(pInfo->curr-1) == '/');
if (markerLength == -1)
markerLength = pInfo->curr - (isEmpty ? 1 : 0) - marker;
pInfo->curr ++; // Advance past '>'
if (markerLength == 0) {
// Back up to the beginning of the marker
pInfo->curr = marker;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Malformed tag on line %d"), lineNumber(pInfo));
return false;
}
switch (*marker) {
case 'a': // Array
if (markerLength == ARRAY_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[ARRAY_IX], ARRAY_TAG_LENGTH))
markerIx = ARRAY_IX;
break;
case 'd': // Dictionary, data, or date; Fortunately, they all have the same marker length....
if (markerLength != DICT_TAG_LENGTH)
break;
if (!memcmp(marker, CFXMLPlistTags[DICT_IX], DICT_TAG_LENGTH))
markerIx = DICT_IX;
else if (!memcmp(marker, CFXMLPlistTags[DATA_IX], DATA_TAG_LENGTH))
markerIx = DATA_IX;
else if (!memcmp(marker, CFXMLPlistTags[DATE_IX], DATE_TAG_LENGTH))
markerIx = DATE_IX;
break;
case 'f': // false (boolean)
if (markerLength == FALSE_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[FALSE_IX], FALSE_TAG_LENGTH)) {
markerIx = FALSE_IX;
}
break;
case 'i': // integer
if (markerLength == INTEGER_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[INTEGER_IX], INTEGER_TAG_LENGTH))
markerIx = INTEGER_IX;
break;
case 'k': // Key of a dictionary
if (markerLength == KEY_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[KEY_IX], KEY_TAG_LENGTH)) {
markerIx = KEY_IX;
if (isKey) *isKey = true;
}
break;
case 'p': // Plist
if (markerLength == PLIST_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[PLIST_IX], PLIST_TAG_LENGTH))
markerIx = PLIST_IX;
break;
case 'r': // real
if (markerLength == REAL_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[REAL_IX], REAL_TAG_LENGTH))
markerIx = REAL_IX;
break;
case 's': // String
if (markerLength == STRING_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[STRING_IX], STRING_TAG_LENGTH))
markerIx = STRING_IX;
break;
case 't': // true (boolean)
if (markerLength == TRUE_TAG_LENGTH && !memcmp(marker, CFXMLPlistTags[TRUE_IX], TRUE_TAG_LENGTH))
markerIx = TRUE_IX;
break;
}
if (!pInfo->allowNewTypes && markerIx != PLIST_IX && markerIx != ARRAY_IX && markerIx != DICT_IX && markerIx != STRING_IX && markerIx != KEY_IX && markerIx != DATA_IX) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered new tag when expecting only old-style property list objects"));
return false;
}
switch (markerIx) {
case PLIST_IX:
if (isEmpty) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty plist tag"));
return false;
}
return parsePListTag(pInfo, out, curDepth);
case ARRAY_IX:
if (isEmpty) {
if (pInfo->skip) {
*out = NULL;
} else {
if (pInfo->mutabilityOption == kCFPropertyListImmutable) {
*out = CFArrayCreate(pInfo->allocator, NULL, 0, &kCFTypeArrayCallBacks);
} else {
*out = CFArrayCreateMutable(pInfo->allocator, 0, &kCFTypeArrayCallBacks);
}
}
return true;
} else {
return parseArrayTag(pInfo, out, curDepth + 1);
}
case DICT_IX:
if (isEmpty) {
if (pInfo->skip) {
*out = NULL;
} else {
if (pInfo->mutabilityOption == kCFPropertyListImmutable) {
*out = CFDictionaryCreate(pInfo->allocator, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
} else {
*out = CFDictionaryCreateMutable(pInfo->allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
}
return true;
} else {
return parseDictTag(pInfo, out, curDepth + 1);
}
case KEY_IX:
case STRING_IX:
{
int tagLen = (markerIx == KEY_IX) ? KEY_TAG_LENGTH : STRING_TAG_LENGTH;
if (isEmpty) {
if (pInfo->skip) {
*out = NULL;
} else {
if (pInfo->mutabilityOption == kCFPropertyListMutableContainersAndLeaves) {
*out = CFStringCreateMutable(pInfo->allocator, 0);
} else {
*out = CFStringCreateWithCharacters(pInfo->allocator, NULL, 0);
}
}
return true;
}
if (!parseStringTag(pInfo, (CFStringRef *)out)) {
return false; // parseStringTag will already have set the error string
}
if (!checkForCloseTag(pInfo, CFXMLPlistTags[markerIx], tagLen)) {
__CFPListRelease(*out, pInfo->allocator);
return false;
} else {
return true;
}
}
case DATA_IX:
if (isEmpty) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <data> on line %d"), lineNumber(pInfo));
return false;
} else {
return parseDataTag(pInfo, out);
}
case DATE_IX:
if (isEmpty) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <date> on line %d"), lineNumber(pInfo));
return false;
} else {
return parseDateTag(pInfo, out);
}
case TRUE_IX:
if (!isEmpty) {
if (!checkForCloseTag(pInfo, CFXMLPlistTags[TRUE_IX], TRUE_TAG_LENGTH)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered non-empty <true> on line %d"), lineNumber(pInfo));
return false;
}
}
if (pInfo->skip) {
*out = NULL;
} else {
*out = CFRetain(kCFBooleanTrue);
}
return true;
case FALSE_IX:
if (!isEmpty) {
if (!checkForCloseTag(pInfo, CFXMLPlistTags[FALSE_IX], FALSE_TAG_LENGTH)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered non-empty <false> on line %d"), lineNumber(pInfo));
return false;
}
}
if (pInfo->skip) {
*out = NULL;
} else {
*out = CFRetain(kCFBooleanFalse);
}
return true;
case REAL_IX:
if (isEmpty) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <real> on line %d"), lineNumber(pInfo));
return false;
} else {
return parseRealTag(pInfo, out);
}
case INTEGER_IX:
if (isEmpty) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered empty <integer> on line %d"), lineNumber(pInfo));
return false;
} else {
return parseIntegerTag(pInfo, out);
}
default: {
CFStringRef markerStr = CFStringCreateWithBytes(kCFAllocatorSystemDefault, (const UInt8 *)marker, markerLength, kCFStringEncodingUTF8, NO);
pInfo->curr = marker;
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown tag %@ on line %d"), markerStr ? markerStr : CFSTR("<unknown>"), lineNumber(pInfo));
if (markerStr) CFRelease(markerStr);
return false;
}
}
}
static Boolean parseXMLPropertyList(_CFXMLPlistParseInfo *pInfo, CFTypeRef *out) {
while (!pInfo->error && pInfo->curr < pInfo->end) {
UniChar ch;
skipWhitespace(pInfo);
if (pInfo->curr+1 >= pInfo->end) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("No XML content found"));
return false;
}
if (*(pInfo->curr) != '<') {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unexpected character %c at line %d"), *(pInfo->curr), lineNumber(pInfo));
return false;
}
ch = *(++ pInfo->curr);
if (ch == '!') {
// Comment or DTD
++ pInfo->curr;
if (pInfo->curr+1 < pInfo->end && *pInfo->curr == '-' && *(pInfo->curr+1) == '-') {
// skip `--` and set the cursor 1 past the two dashes
pInfo->curr += 3;
skipXMLComment(pInfo);
} else {
skipDTD(pInfo);
}
} else if (ch == '?') {
// Processing instruction
pInfo->curr++;
skipXMLProcessingInstruction(pInfo);
} else {
// Tag or malformed
return parseXMLElement(pInfo, NULL, out, 0);
// Note we do not verify that there was only one element, so a file that has garbage after the first element will nonetheless successfully parse
}
}
// Should never get here
if (!(pInfo->error)) {
pInfo->error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unexpected EOF"));
}
return false;
}
static CFStringEncoding encodingForXMLData(CFDataRef data, CFErrorRef *error, CFIndex *skip) {
const uint8_t *bytes = (uint8_t *)CFDataGetBytePtr(data);
UInt32 length = CFDataGetLength(data);
const uint8_t *idx, *end;
char quote;
// Check for the byte order mark first. If we find it, set the skip value so the parser doesn't attempt to parse the BOM itself.
if (length > 4) {
if (*bytes == 0x00 && *(bytes+1) == 0x00 && *(bytes+2) == 0xFE && *(bytes+3) == 0xFF) {
*skip = 4;
return kCFStringEncodingUTF32BE;
} else if (*bytes == 0xFF && *(bytes+1) == 0xFE && *(bytes+2) == 0x00 && *(bytes+3) == 0x00) {
*skip = 4;
return kCFStringEncodingUTF32LE;
}
}
if (length > 3) {
if (*bytes == 0xEF && *(bytes+1) == 0xBB && *(bytes+2) == 0xBF) {
*skip = 3;
return kCFStringEncodingUTF8;
}
}
if (length > 2) {
if (*bytes == 0xFF && *(bytes+1) == 0xFE) {
*skip = 2;
return kCFStringEncodingUTF16LE;
} else if (*bytes == 0xFE && *(bytes+1) == 0xFF) {
*skip = 2;
return kCFStringEncodingUTF16BE;
} else if (*bytes == 0x00 || *(bytes+1) == 0x00) { // This clause checks for a Unicode sequence lacking the byte order mark; technically an error, but this check is recommended by the XML spec
*skip = 2;
return kCFStringEncodingUnicode;
}
}
// Scan for the <?xml.... ?> opening
if (length < 5 || strncmp((char const *) bytes, "<?xml", 5) != 0) return kCFStringEncodingUTF8;
idx = bytes + 5;
end = bytes + length;
// Found "<?xml"; now we scan for "encoding"
while (idx < end) {
uint8_t ch = *idx;
const uint8_t *scan;
if ( ch == '?' || ch == '>') return kCFStringEncodingUTF8;
idx ++;
scan = idx;
if (idx + 8 >= end) {
if (error) *error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("End of buffer while looking for encoding name"));
return 0;
}
if (ch == 'e' && *scan++ == 'n' && *scan++ == 'c' && *scan++ == 'o' && *scan++ == 'd' && *scan++ == 'i'
&& *scan++ == 'n' && *scan++ == 'g' && *scan++ == '=') {
idx = scan;
break;
}
}
if (idx >= end) return kCFStringEncodingUTF8;
quote = *idx;
if (quote != '\'' && quote != '\"') return kCFStringEncodingUTF8;
else {
CFStringRef encodingName;
const uint8_t *base = idx+1; // Move past the quote character
UInt32 len;
idx ++;
while (idx < end && *idx != quote) idx ++;
if (idx >= end) return kCFStringEncodingUTF8;
len = idx - base;
if (len == 5 && (*base == 'u' || *base == 'U') && (base[1] == 't' || base[1] == 'T') && (base[2] == 'f' || base[2] == 'F') && (base[3] == '-') && (base[4] == '8'))
return kCFStringEncodingUTF8;
encodingName = CFStringCreateWithBytes(kCFAllocatorSystemDefault, base, len, kCFStringEncodingISOLatin1, false);
#if TARGET_OS_MAC || TARGET_OS_WIN32 || TARGET_OS_LINUX || TARGET_OS_WASI
CFStringEncoding enc = CFStringConvertIANACharSetNameToEncoding(encodingName);
if (enc != kCFStringEncodingInvalidId) {
if (encodingName) {CFRelease(encodingName); }
return enc;
}
#endif
if (error) {
*error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown encoding (%@)"), encodingName);
}
if (encodingName) { CFRelease(encodingName); }
return 0;
}
}
bool __CFTryParseBinaryPlist(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFPropertyListRef *plist, CFStringRef *errorString);
#define SAVE_PLISTS 0
#if SAVE_PLISTS
static Boolean __savePlistData(CFDataRef data, CFOptionFlags opt) {
uint8_t pn[2048];
uint8_t fn[2048];
uint32_t pnlen = sizeof(pn);
uint8_t *pnp = NULL;
if (0 == _NSGetExecutablePath((char *)pn, &pnlen)) {
pnp = strrchr((char *)pn, '/');
}
if (!pnp) {
pnp = pn;
} else {
pnp++;
}
if (0 == strcmp((char *)pnp, "parse_plists")) return true;
CFUUIDRef r = CFUUIDCreate(kCFAllocatorSystemDefault);
CFStringRef s = CFUUIDCreateString(kCFAllocatorSystemDefault, r);
CFStringRef p = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("/tmp/plists/%s#%@#0x%x"), pnp, s, opt);
_CFStringGetFileSystemRepresentation(p, fn, sizeof(fn));
CFRelease(r);
CFRelease(s);
CFRelease(p);
int fd = open((const char *)fn, O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (fd < 0) return false;
int len = CFDataGetLength(data);
int w = write(fd, CFDataGetBytePtr(data), len);
fsync(fd);
close(fd);
if (w != len) return false;
return true;
}
#endif
// If the data is from a converted string, then originalString is non-NULL. If originalString is NULL, then pass in guessedEncoding.
// keyPaths is a set of CFStrings, ':'-separated paths
static Boolean _CFPropertyListCreateFromUTF8Data(CFAllocatorRef allocator, CFDataRef xmlData, CFIndex skipBytes, CFStringRef originalString, CFStringEncoding guessedEncoding, CFOptionFlags option, CFErrorRef *outError, Boolean allowNewTypes, CFPropertyListFormat *format, CFSetRef keyPaths, CFTypeRef *out, Boolean doXML, Boolean doOpenStep) {
CFAssert1(xmlData != NULL, __kCFLogAssertion, "%s(): NULL data not allowed", __PRETTY_FUNCTION__);
CFIndex length = CFDataGetLength(xmlData);
if (!length) {
if (outError) *outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Conversion of string failed. The string is empty."));
return false;
}
CFTypeRef result = NULL;
_CFXMLPlistParseInfo pInfoBuf;
_CFXMLPlistParseInfo *pInfo = &pInfoBuf;
const char *buf = (const char *)CFDataGetBytePtr(xmlData);
// We may have to skip over starting stuff like BOM markers.
buf += skipBytes;
pInfo->begin = buf;
CFIndex unused;
if (os_add_overflow((CFIndex)buf, (CFIndex)length, &unused)) {
if (outError) *outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to address entirety of CFPropertyList"));
return false;
}
pInfo->end = buf + length - skipBytes;
pInfo->curr = buf;
pInfo->allocator = allocator;
pInfo->error = NULL;
pInfo->mutabilityOption = option & kCFPropertyListMutabilityMask;
pInfo->allowNewTypes = allowNewTypes;
pInfo->skip = false;
if (doXML) {
CFRetain(xmlData);
_createStringMap(pInfo);
pInfo->keyPaths = createTopLevelKeypaths(allocator, keyPaths);
Boolean success = parseXMLPropertyList(pInfo, &result);
if (success && result && format) *format = kCFPropertyListXMLFormat_v1_0;
_cleanupStringMap(pInfo);
if (pInfo->keyPaths) CFRelease(pInfo->keyPaths);
CFRelease(xmlData);
if (success) {
*out = result; // caller releases
return true;
}
}
if (!doOpenStep) {
if (outError) {
if (doXML && pInfo->error) {
*outError = pInfo->error; // caller releases
} else {
// pInfo->error will be nil because we didn't parse XML
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unsupported property list"));
}
} else if (pInfo->error) {
CFRelease(pInfo->error);
}
return false;
}
// Try again, old-style
CFErrorRef oldStyleError = NULL;
result = __CFCreateOldStylePropertyListOrStringsFile(allocator, xmlData, originalString, guessedEncoding, option, outError ? &oldStyleError : NULL, format);
if (result) {
// Release old error, return
if (pInfo->error) CFRelease(pInfo->error);
*out = result;
return true;
}
// Failure, both ways. Set up the error to be given back to caller.
if (!outError) {
if (pInfo->error) CFRelease(pInfo->error);
return false;
}
// Caller's responsibility to release outError
if (pInfo->error && oldStyleError) {
// Add the error from the old-style property list parser to the user info of the original error (pInfo->error), which had better exist
CFDictionaryRef oldUserInfo = CFErrorCopyUserInfo(pInfo->error);
CFMutableDictionaryRef newUserInfo = CFDictionaryCreateMutableCopy(kCFAllocatorSystemDefault, CFDictionaryGetCount(oldUserInfo) + 1, oldUserInfo);
CFDictionaryAddValue(newUserInfo, CFPropertyListOldStyleParserErrorKey, oldStyleError);
// Re-create the xml parser error with this new user info dictionary
CFErrorRef newError = CFErrorCreate(kCFAllocatorSystemDefault, CFErrorGetDomain(pInfo->error), CFErrorGetCode(pInfo->error), newUserInfo);
CFRelease(oldUserInfo);
CFRelease(newUserInfo);
CFRelease(oldStyleError);
CFRelease(pInfo->error);
*outError = newError;
} else if (pInfo->error && !oldStyleError) {
// Return original error
*outError = pInfo->error;
} else if (!pInfo->error && oldStyleError) {
// Return only old-style error
// Probably shouldn't get here
*outError = oldStyleError;
} else if (!pInfo->error && !oldStyleError) {
// Return unknown error
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Encountered unknown error during parse"));
}
return false;
}
static CFDataRef _createUTF8DataFromString(CFAllocatorRef allocator, CFStringRef str) {
CFIndex bytesNeeded = 0;
CFStringGetBytes(str, CFRangeMake(0, CFStringGetLength(str)), kCFStringEncodingUTF8, 0, false, NULL, 0, &bytesNeeded);
const char *bytes = (const char *)CFAllocatorAllocate(allocator, bytesNeeded, 0);
CFStringGetBytes(str, CFRangeMake(0, CFStringGetLength(str)), kCFStringEncodingUTF8, 0, false, (uint8_t *)bytes, bytesNeeded, NULL);
CFDataRef utf8Data = CFDataCreateWithBytesNoCopy(allocator, (const UInt8 *)bytes, bytesNeeded, allocator);
return utf8Data;
}
// Set topLevelKeys to a set of top level keys to decode. If NULL, all keys are decoded. If the top level object is not a dictionary, all objects are decoded. If the plist is not XML, all objects are decoded.
static Boolean _CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFErrorRef *outError, Boolean allowNewTypes, CFPropertyListFormat *format, CFSetRef topLevelKeys, CFTypeRef *out) {
CFStringEncoding encoding;
// we support the restriction of the kinds of parses we will try
Boolean doOpenStep = (option & kCFPropertyListSupportedFormatOpenStepFormat) != 0;
Boolean doBinary = (option & kCFPropertyListSupportedFormatBinary_v1_0) != 0;
Boolean doXML = (option & kCFPropertyListSupportedFormatXML_v1_0) != 0;
if (!doOpenStep && !doBinary && !doXML) {
// if you ask for nothing the historic behavior is to try everything
doOpenStep = true;
doBinary = true;
doXML = true;
}
if (!data || CFDataGetLength(data) == 0) {
if (outError) {
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Cannot parse a NULL or zero-length data"));
}
return false;
}
#if SAVE_PLISTS
__savePlistData(data, option);
#endif
// Ignore the error from CFTryParseBinaryPlist -- if it doesn't work, we're going to try again anyway using the XML parser.
// It would be lovely to be able to not just ignore the error and
// have the error message actually relay issues with bplists.
if (doBinary && __CFTryParseBinaryPlist(allocator, data, (option&kCFPropertyListMutabilityMask), out, NULL)) {
if (format) *format = kCFPropertyListBinaryFormat_v1_0;
return true;
}
// stop working if there is nothing left to do
if (!doXML && !doOpenStep) {
if (outError) {
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unsupported property list"));
}
return false;
}
// Use our own error variable here so we can check it against NULL later
CFErrorRef subError = NULL;
CFIndex skip = 0;
encoding = encodingForXMLData(data, &subError, &skip); // 0 is an error return, NOT MacRoman.
if (encoding == 0) {
// Couldn't find an encoding
// Note that encodingForXMLData() will give us the right values for a standard plist, too.
if (outError && subError == NULL) {
// encodingForXMLData didn't set an error, so we create a new one here
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not determine the encoding of the XML data"));
} else if (outError && subError) {
// give the caller the subError, they will release
*outError = subError;
} else if (!outError && subError) {
// Release the error
CFRelease(subError);
}
return false;
}
if (encoding == kCFStringEncodingUTF8) {
// Use fast path
return _CFPropertyListCreateFromUTF8Data(allocator, data, skip, NULL, encoding, option, outError, allowNewTypes, format, topLevelKeys, out, doXML, doOpenStep);
}
// Convert to UTF8 first
CFStringRef xmlString = CFStringCreateWithBytes(allocator, CFDataGetBytePtr(data) + skip, CFDataGetLength(data) - skip, encoding, false);
if (!xmlString) {
if (outError) *outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Could not determine the encoding of the XML data (string creation failed)"));
return false;
}
CFDataRef utf8Data = _createUTF8DataFromString(allocator, xmlString);
Boolean result = _CFPropertyListCreateFromUTF8Data(allocator, utf8Data, 0, xmlString, 0, option, outError, allowNewTypes, format, topLevelKeys, out, doXML, doOpenStep);
if (xmlString) CFRelease(xmlString);
if (utf8Data) CFRelease(utf8Data);
return result;
}
// -----------------------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Exported Parsing Functions
CFTypeRef _CFPropertyListCreateFromXMLStringError(CFAllocatorRef allocator, CFStringRef xmlString, CFOptionFlags option, CFErrorRef *error, Boolean allowNewTypes, CFPropertyListFormat *format) {
// Convert to UTF8 first
CFDataRef utf8Data = _createUTF8DataFromString(allocator, xmlString);
CFTypeRef result = NULL;
_CFPropertyListCreateFromUTF8Data(allocator, utf8Data, 0, xmlString, 0, option, error, allowNewTypes, format, NULL, &result, true, true);
if (utf8Data) CFRelease(utf8Data);
return result;
}
CFTypeRef _CFPropertyListCreateFromXMLString(CFAllocatorRef allocator, CFStringRef xmlString, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format) {
if (errorString) *errorString = NULL;
CFErrorRef error = NULL;
CFTypeRef result = _CFPropertyListCreateFromXMLStringError(allocator, xmlString, option, &error, allowNewTypes, format);
if (errorString && error) {
// The caller is interested in receiving an error message. Pull the debug string out of the CFError returned above
CFDictionaryRef userInfo = CFErrorCopyUserInfo(error);
CFStringRef debugString = NULL;
// Handle a special-case for compatibility - if the XML parse failed and the old-style plist parse failed, construct a special string
CFErrorRef underlyingError = NULL;
Boolean oldStyleFailed = CFDictionaryGetValueIfPresent(userInfo, CFPropertyListOldStyleParserErrorKey, (const void **)&underlyingError);
if (oldStyleFailed) {
CFStringRef xmlParserErrorString, oldStyleParserErrorString;
xmlParserErrorString = (CFStringRef)CFDictionaryGetValue(userInfo, kCFErrorDebugDescriptionKey);
CFDictionaryRef oldStyleParserUserInfo = CFErrorCopyUserInfo(underlyingError);
oldStyleParserErrorString = (CFStringRef)CFDictionaryGetValue(userInfo, kCFErrorDebugDescriptionKey);
// Combine the two strings into a single one that matches the previous implementation
debugString = CFStringCreateWithFormat(kCFAllocatorSystemDefault, NULL, CFSTR("XML parser error:\n\t%@\nOld-style plist parser error:\n\t%@\n"), xmlParserErrorString, oldStyleParserErrorString);
CFRelease(oldStyleParserUserInfo);
} else {
debugString = (CFStringRef)CFDictionaryGetValue(userInfo, kCFErrorDebugDescriptionKey);
if (debugString) CFRetain(debugString);
}
// Give the debugString to the caller, who is responsible for releasing it
CFRelease(userInfo);
*errorString = debugString;
}
if (error) {
CFRelease(error);
}
return result;
}
CF_PRIVATE bool __CFBinaryPlistCreateObjectFiltered(const uint8_t *databytes, uint64_t datalen, uint64_t startOffset, const CFBinaryPlistTrailer *trailer, CFAllocatorRef allocator, CFOptionFlags mutabilityOption, CFMutableDictionaryRef objects, CFMutableSetRef set, CFIndex curDepth, CFSetRef keyPaths, CFPropertyListRef *plist, CFTypeID *outPlistTypeID);
// Returns a subset of the property list, only including the key paths in the CFSet.
bool _CFPropertyListCreateFiltered(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFSetRef keyPaths, CFPropertyListRef *value, CFErrorRef *error) {
if (!keyPaths || !data) {
return false;
}
uint8_t marker;
CFBinaryPlistTrailer trailer;
uint64_t offset;
const uint8_t *databytes = CFDataGetBytePtr(data);
uint64_t datalen = CFDataGetLength(data);
bool success = false;
CFTypeRef out = NULL;
// First check to see if it is a binary property list
if (8 <= datalen && __CFBinaryPlistGetTopLevelInfo(databytes, datalen, &marker, &offset, &trailer)) {
uint64_t valueOffset = offset;
// Split up the key path
CFSetRef splitKeyPaths = createTopLevelKeypaths(allocator, keyPaths);
// Create a dictionary to cache objects in
CFMutableDictionaryRef objects = CFDictionaryCreateMutable(allocator, 0, NULL, &kCFTypeDictionaryValueCallBacks);
success = __CFBinaryPlistCreateObjectFiltered(databytes, datalen, valueOffset, &trailer, allocator, option, objects, NULL, 0, splitKeyPaths, &out, NULL);
CFRelease(splitKeyPaths);
CFRelease(objects);
} else {
// Try an XML property list
success = _CFPropertyListCreateWithData(allocator, data, option, error, true, NULL, keyPaths, &out);
}
if (success && value) {
*value = out; // caller releases
} else if (out) {
CFRelease(out);
}
return success;
}
/* Get a single value for a given key in a top-level dictionary in a property list.
@param allocator The allocator to use.
@param data The property list data.
@param option Currently unused, set to 0.
@param keyPath The keyPath to search for in the property list. Keys are colon-separated. Indexes into arrays are specified with an integer (zero-based).
@param value If the key is found and the parameter is non-NULL, this will be set to a reference to the value. It is the caller's responsibility to release the object. If no object is found, will be set to NULL. If this parameter is NULL, this function can be used to check for the existence of a key without creating it by just checking the return value.
@param error If an error occurs, will be set to a valid CFErrorRef. It is the caller's responsibility to release this value.
@return True if the key is found, false otherwise.
*/
bool _CFPropertyListCreateSingleValue(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFStringRef keyPath, CFPropertyListRef *value, CFErrorRef *error) {
if (!keyPath || CFStringGetLength(keyPath) == 0) {
return false;
}
uint8_t marker;
CFBinaryPlistTrailer trailer;
uint64_t offset;
const uint8_t *databytes = CFDataGetBytePtr(data);
uint64_t datalen = CFDataGetLength(data);
bool success = false;
// First check to see if it is a binary property list
if (8 <= datalen && __CFBinaryPlistGetTopLevelInfo(databytes, datalen, &marker, &offset, &trailer)) {
// Split up the key path
CFArrayRef keyPathArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorSystemDefault, keyPath, CFSTR(":"));
uint64_t keyOffset, valueOffset = offset;
// Create a dictionary to cache objects in
CFMutableDictionaryRef objects = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);
CFIndex keyPathCount = CFArrayGetCount(keyPathArray);
_CFDictionarySetCapacity(objects, keyPathCount + 1);
for (CFIndex i = 0; i < keyPathCount; i++) {
CFStringRef oneKey = (CFStringRef)CFArrayGetValueAtIndex(keyPathArray, i);
// Peek into the next level see what the type is
// if it is a dictionary interpret the key as a dictionary key
// if it is an array try to interpret the key as a integer key
//
const bool isDictionary = __CFBinaryPlistIsDictionary(databytes, datalen, valueOffset, &trailer);
if (isDictionary) {
// Treat as a string key into a dictionary
success = __CFBinaryPlistGetOffsetForValueFromDictionary3(databytes, datalen, valueOffset, &trailer, (CFTypeRef)oneKey, &keyOffset, &valueOffset, false, objects);
} else {
const bool isArray = __CFBinaryPlistIsArray(databytes, datalen, valueOffset, &trailer);
if (isArray) {
// Treat as integer index into an array
const SInt32 intValue = CFStringGetIntValue(oneKey);
if (intValue >= 0 && intValue != INT_MAX) {
success = __CFBinaryPlistGetOffsetForValueFromArray2(databytes, datalen, valueOffset, &trailer, intValue, &valueOffset, objects);
}
}
}
if (!success) {
break;
}
}
// value could be null if the caller wanted to check for the existence of a key but not bother creating it
if (success && value) {
CFPropertyListRef pl;
success = __CFBinaryPlistCreateObjectFiltered(databytes, datalen, valueOffset, &trailer, allocator, option, objects, NULL, 0, NULL, &pl, NULL);
if (success) {
// caller's responsibility to release the created object
*value = pl;
}
}
CFRelease(keyPathArray);
CFRelease(objects);
} else {
// Try an XML property list
// Note: This is currently not any more efficient than grabbing the whole thing. This could be improved in the future.
CFPropertyListRef plist = CFPropertyListCreateWithData(allocator, data, option, NULL, error);
if (plist) {
CFPropertyListRef nextObject = plist;
success = true;
CFArrayRef keyPathArray = CFStringCreateArrayBySeparatingStrings(kCFAllocatorSystemDefault, keyPath, CFSTR(":"));
for (CFIndex i = 0; i < CFArrayGetCount(keyPathArray); i++) {
CFStringRef oneKey = (CFStringRef)CFArrayGetValueAtIndex(keyPathArray, i);
SInt32 intValue = CFStringGetIntValue(oneKey);
if (((intValue == 0 && CFStringCompare(CFSTR("0"), oneKey, 0) != kCFCompareEqualTo) || intValue == INT_MAX || intValue == INT_MIN) && nextObject && CFGetTypeID((CFTypeRef)nextObject) == _kCFRuntimeIDCFDictionary) {
// Treat as a string key into a dictionary
nextObject = (CFPropertyListRef)CFDictionaryGetValue((CFDictionaryRef)nextObject, oneKey);
} else if (nextObject && CFGetTypeID((CFTypeRef)nextObject) == _kCFRuntimeIDCFArray) {
// Treat as integer index into an array
nextObject = (CFPropertyListRef)CFArrayGetValueAtIndex((CFArrayRef)nextObject, intValue);
} else {
success = false;
break;
}
}
if (success && nextObject && value) {
*value = nextObject;
// caller's responsibility to release the created object
CFRetain(*value);
} else if (!nextObject) {
success = false;
}
CFRelease(keyPathArray);
CFRelease(plist);
}
}
return success;
}
/*!
SPI to return just the keys from the top-level dictionary of a property-list. This can be valuable in cases where you want to check for the presence of a key.
@param allocator allocate to use when creating the array of objects
@param data data to explore
@param option currently unused, should be 0
@param outError optional out-param error
@return NULL if anything went wrong (`outError` should describe why)
*/
CFSetRef _CFPropertyListCopyTopLevelKeys(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags option, CFErrorRef *outError) {
CFSetRef result = NULL;
if (data != NULL) {
const uint8_t *databytes = CFDataGetBytePtr(data);
const uint64_t datalen = CFDataGetLength(data);
// only try xml if the bplist fails
bool tryXML = true;
// bplist:
if (8 <= datalen) {
uint8_t marker;
CFBinaryPlistTrailer trailer;
uint64_t offset;
if (__CFBinaryPlistGetTopLevelInfo(databytes, datalen, &marker, &offset, &trailer)) {
tryXML = false;
result = __CFBinaryPlistCopyTopLevelKeys(allocator, databytes, datalen, offset, &trailer);
}
}
if (tryXML) {
// xml:
// This path remains unoptimized; friends don't let friends use XML plists.
const CFPropertyListRef plist = CFPropertyListCreateWithData(allocator, data, option, NULL, outError);
if (plist) {
const CFTypeID type = CFGetTypeID(plist);
if (type != _kCFRuntimeIDCFDictionary) {
if (outError) {
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Cannot copy top-level keys for plist with non-dictionary root object"));
}
} else {
const CFIndex count = CFDictionaryGetCount(plist);
CFTypeRef *keyBuffer = malloc(sizeof(CFTypeRef) * count);
if (keyBuffer == NULL) {
if (outError) {
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to convert string to correct encoding"));
}
} else {
CFDictionaryGetKeysAndValues(plist, keyBuffer, NULL);
result = CFSetCreate(allocator, keyBuffer, count, &kCFTypeSetCallBacks);
free(keyBuffer);
}
}
CFRelease(plist);
}
}
}
if (result == NULL && outError) {
*outError = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("Unable to extract top-level keys"));
}
return result;
}
// Legacy
CFTypeRef _CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags option, CFStringRef *errorString, Boolean allowNewTypes, CFPropertyListFormat *format) {
CFTypeRef out = NULL;
if (errorString) *errorString = NULL;
CFErrorRef error = NULL;
Boolean result = _CFPropertyListCreateWithData(allocator, xmlData, option, &error, allowNewTypes, format, NULL, &out);
if (!result && error && errorString) {
*errorString = __copyErrorDebugDescription(error);
}
if (error) CFRelease(error);
return out;
}
CFPropertyListRef CFPropertyListCreateWithData(CFAllocatorRef allocator, CFDataRef data, CFOptionFlags options, CFPropertyListFormat *format, CFErrorRef *error) {
CFAssert1(data != NULL, __kCFLogAssertion, "%s(): NULL data not allowed", __PRETTY_FUNCTION__);
CFAssert2(options == kCFPropertyListImmutable || options == kCFPropertyListMutableContainers || options == kCFPropertyListMutableContainersAndLeaves, __kCFLogAssertion, "%s(): Unrecognized option %lu", __PRETTY_FUNCTION__, options);
CFPropertyListRef out = NULL;
_CFPropertyListCreateWithData(allocator, data, options, error, true, format, NULL, &out);
return out;
}
CFPropertyListRef CFPropertyListCreateFromXMLData(CFAllocatorRef allocator, CFDataRef xmlData, CFOptionFlags option, CFStringRef *errorString) {
if (errorString) *errorString = NULL;
CFErrorRef error = NULL;
CFPropertyListRef result = CFPropertyListCreateWithData(allocator, xmlData, option, NULL, &error);
if (error && errorString) {
*errorString = __copyErrorDebugDescription(error);
}
if (error) CFRelease(error);
return result;
}
CFDataRef CFPropertyListCreateData(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) {
CFAssert1(format != kCFPropertyListOpenStepFormat, __kCFLogAssertion, "%s(): kCFPropertyListOpenStepFormat not supported for writing", __PRETTY_FUNCTION__);
CFAssert2(format == kCFPropertyListXMLFormat_v1_0 || format == kCFPropertyListBinaryFormat_v1_0, __kCFLogAssertion, "%s(): Unrecognized option %ld", __PRETTY_FUNCTION__, format);
CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): Cannot be called with a NULL property list", __PRETTY_FUNCTION__);
__CFAssertIsPList(propertyList);
CFDataRef data = NULL;
if (format == kCFPropertyListOpenStepFormat) {
CFLog(kCFLogLevelError, CFSTR("Property list format kCFPropertyListOpenStepFormat not supported for writing"));
return NULL;
} else if (format == kCFPropertyListXMLFormat_v1_0) {
CFStringRef validErr = NULL;
if (!_CFPropertyListIsValidWithErrorString(propertyList, format, &validErr)) {
if (error) {
*error = __CFPropertyListCreateError(kCFPropertyListWriteStreamError, CFSTR("Property list invalid for format: %d (%@)"), format, validErr);
}
if (validErr) CFRelease(validErr);
return NULL;
}
data = _CFPropertyListCreateXMLData(allocator, propertyList, false);
} else if (format == kCFPropertyListBinaryFormat_v1_0) { // TODO: Is it more efficient to create a stream here or just use a mutable data?
CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers(kCFAllocatorSystemDefault, allocator);
CFWriteStreamOpen(stream);
CFIndex len = CFPropertyListWrite(propertyList, stream, format, options, error);
if (0 < len) {
data = (CFDataRef)CFWriteStreamCopyProperty(stream, kCFStreamPropertyDataWritten);
}
CFWriteStreamClose(stream);
CFRelease(stream);
} else {
CFLog(kCFLogLevelError, CFSTR("Unknown format option"));
}
return data;
}
CFIndex CFPropertyListWrite(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFOptionFlags options, CFErrorRef *error) {
CFAssert1(stream != NULL, __kCFLogAssertion, "%s(): NULL stream not allowed", __PRETTY_FUNCTION__);
CFAssert1(format != kCFPropertyListOpenStepFormat, __kCFLogAssertion, "%s(): kCFPropertyListOpenStepFormat not supported for writing", __PRETTY_FUNCTION__);
CFAssert2(format == kCFPropertyListXMLFormat_v1_0 || format == kCFPropertyListBinaryFormat_v1_0, __kCFLogAssertion, "%s(): Unrecognized option %ld", __PRETTY_FUNCTION__, format);
CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): Cannot be called with a NULL property list", __PRETTY_FUNCTION__);
__CFAssertIsPList(propertyList);
CFAssert1(CFWriteStreamGetTypeID() == CFGetTypeID(stream), __kCFLogAssertion, "%s(): stream argument is not a write stream", __PRETTY_FUNCTION__);
CFAssert1(kCFStreamStatusOpen == CFWriteStreamGetStatus(stream) || kCFStreamStatusWriting == CFWriteStreamGetStatus(stream), __kCFLogAssertion, "%s(): stream is not open", __PRETTY_FUNCTION__);
CFStringRef validErr = NULL;
if (!_CFPropertyListIsValidWithErrorString(propertyList, format, &validErr)) {
if (error) {
*error = __CFPropertyListCreateError(kCFPropertyListWriteStreamError, CFSTR("Property list invalid for format: %d (%@)"), format, validErr);
}
if (validErr) CFRelease(validErr);
return 0;
}
if (format == kCFPropertyListOpenStepFormat) {
CFLog(kCFLogLevelError, CFSTR("Property list format kCFPropertyListOpenStepFormat not supported for writing"));
return 0;
}
if (format == kCFPropertyListXMLFormat_v1_0) {
CFDataRef data = _CFPropertyListCreateXMLData(kCFAllocatorSystemDefault, propertyList, true);
if (!data) {
CFLog(kCFLogLevelError, CFSTR("Property list format kCFPropertyListXMLFormat_v1_0 specified but was not a valid property list type"));
return 0;
}
CFIndex len = CFDataGetLength(data);
const uint8_t *ptr = CFDataGetBytePtr(data);
while (0 < len) {
CFIndex ret = CFWriteStreamWrite(stream, ptr, len);
if (ret == 0) {
if (error) *error = __CFPropertyListCreateError(kCFPropertyListWriteStreamError, CFSTR("Property list writing could not be completed because stream is full."));
CFRelease(data);
return 0;
}
if (ret < 0) {
CFErrorRef underlyingError = CFWriteStreamCopyError(stream);
if (underlyingError) {
if (error) {
// Wrap the error from CFWriteStreamCopy in a new error
CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, CFSTR("Property list writing could not be completed because the stream had an unknown error."));
CFDictionarySetValue(userInfo, kCFErrorUnderlyingErrorKey, underlyingError);
*error = CFErrorCreate(kCFAllocatorSystemDefault, kCFErrorDomainCocoa, kCFPropertyListWriteStreamError, userInfo);
CFRelease(userInfo);
}
CFRelease(underlyingError);
}
CFRelease(data);
return 0;
}
ptr += ret;
len -= ret;
}
len = CFDataGetLength(data);
CFRelease(data);
return len;
}
if (format == kCFPropertyListBinaryFormat_v1_0) {
CFIndex len = __CFBinaryPlistWrite(propertyList, stream, 0, options, error);
return len;
}
CFLog(kCFLogLevelError, CFSTR("Unknown format option"));
return 0;
}
CFIndex CFPropertyListWriteToStream(CFPropertyListRef propertyList, CFWriteStreamRef stream, CFPropertyListFormat format, CFStringRef *errorString) {
if (errorString) *errorString = NULL;
CFErrorRef error = NULL;
// For backwards compatibility, we check the format parameter up front since these do not have CFError counterparts in the newer API
if (format == kCFPropertyListOpenStepFormat) {
if (errorString) *errorString = (CFStringRef)CFRetain(CFSTR("Property list format kCFPropertyListOpenStepFormat not supported for writing"));
return 0;
}
if (format != kCFPropertyListBinaryFormat_v1_0 && format != kCFPropertyListXMLFormat_v1_0) {
if (errorString) *errorString = (CFStringRef)CFRetain(CFSTR("Unknown format option"));
return 0;
}
CFIndex result = CFPropertyListWrite(propertyList, stream, format, 0, &error);
if (error && errorString) {
*errorString = __copyErrorDebugDescription(error);
}
if (error) CFRelease(error);
return result;
}
static bool __convertReadStreamToBytes(CFReadStreamRef stream, CFIndex max, uint8_t **buffer, CFIndex *length, CFErrorRef *error) {
int32_t buflen = 0, bufsize = 0, retlen;
uint8_t *buf = NULL, sbuf[8192];
for (;;) {
retlen = CFReadStreamRead(stream, sbuf, __CFMin(8192, max));
if (retlen <= 0) {
*buffer = buf;
*length = buflen;
if (retlen < 0 && error) {
// Copy the error out
*error = CFReadStreamCopyError(stream);
return false;
}
return true;
}
if (bufsize < buflen + retlen) {
if (bufsize < 256 * 1024) {
bufsize *= 4;
} else if (bufsize < 16 * 1024 * 1024) {
bufsize *= 2;
} else {
// once in this stage, this will be really slow
// and really potentially fragment memory
bufsize += 256 * 1024;
}
if (bufsize < buflen + retlen) bufsize = buflen + retlen;
buf = __CFSafelyReallocateWithAllocator(kCFAllocatorSystemDefault, buf, bufsize, 0, NULL);
if (!buf) HALT;
}
memmove(buf + buflen, sbuf, retlen);
buflen += retlen;
max -= retlen;
if (max <= 0) {
*buffer = buf;
*length = buflen;
return true;
}
}
return true;
}
CFPropertyListRef CFPropertyListCreateWithStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex streamLength, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFErrorRef *error) {
CFAssert1(stream != NULL, __kCFLogAssertion, "%s(): NULL stream not allowed", __PRETTY_FUNCTION__);
CFAssert1(CFReadStreamGetTypeID() == CFGetTypeID(stream), __kCFLogAssertion, "%s(): stream argument is not a read stream", __PRETTY_FUNCTION__);
CFAssert1(kCFStreamStatusOpen == CFReadStreamGetStatus(stream) || kCFStreamStatusReading == CFReadStreamGetStatus(stream), __kCFLogAssertion, "%s(): stream is not open", __PRETTY_FUNCTION__);
CFAssert2(mutabilityOption == kCFPropertyListImmutable || mutabilityOption == kCFPropertyListMutableContainers || mutabilityOption == kCFPropertyListMutableContainersAndLeaves, __kCFLogAssertion, "%s(): Unrecognized option %lu", __PRETTY_FUNCTION__, mutabilityOption);
if (0 == streamLength) streamLength = LONG_MAX;
CFErrorRef underlyingError = NULL;
CFIndex buflen = 0;
uint8_t *buffer = NULL;
if (!__convertReadStreamToBytes(stream, streamLength, &buffer, &buflen, &underlyingError)) {
if (error) {
// Wrap the error from CFReadStream in a new error in the cocoa domain
CFMutableDictionaryRef userInfo = CFDictionaryCreateMutable(kCFAllocatorSystemDefault, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(userInfo, kCFErrorDebugDescriptionKey, CFSTR("Property list reading could not be completed because the stream had an unknown error. Did you forget to open the stream?"));
if (underlyingError) {
CFDictionarySetValue(userInfo, kCFErrorUnderlyingErrorKey, underlyingError);
}
*error = CFErrorCreate(kCFAllocatorSystemDefault, kCFErrorDomainCocoa, kCFPropertyListReadStreamError, userInfo);
CFRelease(userInfo);
}
if (underlyingError) {
CFRelease(underlyingError);
}
return NULL;
}
if (!buffer || buflen < 6) {
if (buffer) CFAllocatorDeallocate(kCFAllocatorSystemDefault, buffer);
if (error) *error = __CFPropertyListCreateError(kCFPropertyListReadCorruptError, CFSTR("stream had too few bytes"));
return NULL;
}
CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorSystemDefault, buffer, buflen, kCFAllocatorSystemDefault);
CFPropertyListRef pl = NULL; // initialize to null, because if the following call fails we must return NULL
_CFPropertyListCreateWithData(allocator, data, mutabilityOption, error, true, format, NULL, &pl);
CFRelease(data);
return pl;
}
CFPropertyListRef CFPropertyListCreateFromStream(CFAllocatorRef allocator, CFReadStreamRef stream, CFIndex length, CFOptionFlags mutabilityOption, CFPropertyListFormat *format, CFStringRef *errorString) {
if (errorString) *errorString = NULL;
CFErrorRef error = NULL;
CFPropertyListRef result = CFPropertyListCreateWithStream(allocator, stream, length, mutabilityOption, format, &error);
if (error && errorString) {
*errorString = __copyErrorDebugDescription(error);
}
if (error) CFRelease(error);
return result;
}
bool _CFPropertyListValidateData(CFDataRef data, CFTypeID *outTopLevelTypeID) {
uint8_t marker;
CFBinaryPlistTrailer trailer;
uint64_t offset;
const uint8_t *databytes = CFDataGetBytePtr(data);
uint64_t datalen = CFDataGetLength(data);
bool result = true;
if (8 <= datalen && __CFBinaryPlistGetTopLevelInfo(databytes, datalen, &marker, &offset, &trailer)) {
// Object-less plist parsing does not use an objects dictionary.
CFTypeID typeID = _kCFRuntimeNotATypeID;
if (!__CFBinaryPlistCreateObjectFiltered(databytes, datalen, offset, &trailer, kCFAllocatorSystemDefault, 0, NULL, NULL, 0, NULL, NULL, &typeID)) {
result = false;
}
if (outTopLevelTypeID) *outTopLevelTypeID = typeID;
} else {
// Try an XML property list
// Note: This is currently not any more efficient than grabbing the whole thing. This could be improved in the future.
CFPropertyListRef plist = CFPropertyListCreateWithData(kCFAllocatorSystemDefault, data, kCFPropertyListMutableContainers, NULL, NULL);
if (plist) {
if (outTopLevelTypeID) *outTopLevelTypeID = CFGetTypeID(plist);
CFRelease(plist);
} else {
result = false;
}
}
return result;
}
#pragma mark -
#pragma mark Property List Copies
static CFArrayRef _arrayDeepImmutableCopy(CFAllocatorRef allocator, CFArrayRef array, CFOptionFlags mutabilityOption) {
CFArrayRef result = NULL;
CFIndex i, c = CFArrayGetCount(array);
if (c == 0) {
result = CFArrayCreate(allocator, NULL, 0, &kCFTypeArrayCallBacks);
} else {
new_cftype_array(values, c);
CFArrayGetValues(array, CFRangeMake(0, c), values);
for (i = 0; i < c; i ++) {
CFTypeRef newValue = CFPropertyListCreateDeepCopy(allocator, values[i], mutabilityOption);
if (newValue == NULL) {
break;
}
*((void **)values + i) = (void *)newValue;
}
result = (i == c) ? CFArrayCreate(allocator, values, c, &kCFTypeArrayCallBacks) : NULL;
c = i;
for (i = 0; i < c; i ++) CFRelease(values[i]);
free_cftype_array(values);
}
return result;
}
static CFMutableArrayRef _arrayDeepMutableCopy(CFAllocatorRef allocator, CFArrayRef array, CFOptionFlags mutabilityOption) {
CFIndex i, c = CFArrayGetCount(array);
CFMutableArrayRef result = CFArrayCreateMutable(allocator, 0, &kCFTypeArrayCallBacks);
if (result) {
for (i = 0; i < c; i ++) {
CFTypeRef newValue = CFPropertyListCreateDeepCopy(allocator, CFArrayGetValueAtIndex(array, i), mutabilityOption);
if (!newValue) break;
CFArrayAppendValue(result, newValue);
CFRelease(newValue);
}
if (i != c) {
CFRelease(result);
result = NULL;
}
}
return result;
}
CFPropertyListRef CFPropertyListCreateDeepCopy(CFAllocatorRef allocator, CFPropertyListRef propertyList, CFOptionFlags mutabilityOption) {
CFPropertyListRef result = NULL;
CFAssert1(propertyList != NULL, __kCFLogAssertion, "%s(): cannot copy a NULL property list", __PRETTY_FUNCTION__);
__CFAssertIsPList(propertyList);
CFAssert2(mutabilityOption == kCFPropertyListImmutable || mutabilityOption == kCFPropertyListMutableContainers || mutabilityOption == kCFPropertyListMutableContainersAndLeaves, __kCFLogAssertion, "%s(): Unrecognized option %lu", __PRETTY_FUNCTION__, mutabilityOption);
if (!CFPropertyListIsValid(propertyList, kCFPropertyListBinaryFormat_v1_0)) return NULL;
CFTypeID typeID = CFGetTypeID(propertyList);
if (typeID == _kCFRuntimeIDCFDictionary) {
CFDictionaryRef dict = (CFDictionaryRef)propertyList;
Boolean isMutable = (mutabilityOption != kCFPropertyListImmutable);
CFIndex count = CFDictionaryGetCount(dict);
if (count == 0) {
result = isMutable ? CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks): CFDictionaryCreate(allocator, NULL, NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
} else {
new_cftype_array(keys, 2 * count);
CFTypeRef *values;
CFIndex i;
values = keys+count;
CFDictionaryGetKeysAndValues(dict, keys, values);
for (i = 0; i < count; i ++) {
CFTypeRef newKey = CFStringCreateCopy(allocator, (CFStringRef)keys[i]);
if (newKey == NULL) {
break;
}
*((void **)keys + i) = (void *)newKey;
CFTypeRef newValue = CFPropertyListCreateDeepCopy(allocator, values[i], mutabilityOption);
if (newValue == NULL) {
CFRelease(keys[i]);
break;
}
*((void **)values + i) = (void *)newValue;
}
if (i == count) {
result = isMutable ? CFDictionaryCreateMutable(allocator, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) : CFDictionaryCreate(allocator, keys, values, count, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
for (i = 0; i < count; i ++) {
if (isMutable) {
CFDictionarySetValue((CFMutableDictionaryRef)result, keys[i], values[i]);
}
CFRelease(keys[i]);
CFRelease(values[i]);
}
} else {
result = NULL;
count = i;
for (i = 0; i < count; i ++) {
CFRelease(keys[i]);
CFRelease(values[i]);
}
}
free_cftype_array(keys);
}
} else if (typeID == _kCFRuntimeIDCFArray) {
if (mutabilityOption == kCFPropertyListImmutable) {
result = _arrayDeepImmutableCopy(allocator, (CFArrayRef)propertyList, mutabilityOption);
} else {
result = _arrayDeepMutableCopy(allocator, (CFArrayRef)propertyList, mutabilityOption);
}
} else if (typeID == _kCFRuntimeIDCFData) {
if (mutabilityOption == kCFPropertyListMutableContainersAndLeaves) {
result = CFDataCreateMutableCopy(allocator, 0, (CFDataRef)propertyList);
} else {
result = CFDataCreateCopy(allocator, (CFDataRef)propertyList);
}
} else if (typeID == _kCFRuntimeIDCFNumber) {
// Warning - this will break if byteSize is ever greater than 128
uint8_t bytes[128];
CFNumberType numType = _CFNumberGetType2((CFNumberRef)propertyList);
CFNumberGetValue((CFNumberRef)propertyList, numType, (void *)bytes);
result = CFNumberCreate(allocator, numType, (void *)bytes);
} else if (typeID == _kCFRuntimeIDCFBoolean) {
// Booleans are immutable & shared instances
CFRetain(propertyList);
result = propertyList;
} else if (typeID == _kCFRuntimeIDCFDate) {
// Dates are immutable
result = CFDateCreate(allocator, CFDateGetAbsoluteTime((CFDateRef)propertyList));
} else if (typeID == _kCFRuntimeIDCFString) {
if (mutabilityOption == kCFPropertyListMutableContainersAndLeaves) {
result = CFStringCreateMutableCopy(allocator, 0, (CFStringRef)propertyList);
} else {
result = CFStringCreateCopy(allocator, (CFStringRef)propertyList);
}
} else {
CFAssert2(false, __kCFLogAssertion, "%s(): %p is not a property list type", __PRETTY_FUNCTION__, propertyList);
result = NULL;
}
return result;
}
|